瀏覽代碼

Reintagrating netcode branch to the trunk.

Michał W. Urbańczyk 17 年之前
父節點
當前提交
a78311f63d
共有 100 個文件被更改,包括 6542 次插入10286 次删除
  1. 1 0
      AI/EmptyAI/CEmptyAI.cpp
  2. 6 6
      AI/EmptyAI/exp_funcs.cpp
  3. 9 10
      AI_Base.h
  4. 0 1
      AUTHORS
  5. 6 5
      AdventureMapButton.cpp
  6. 47 45
      CAdvmapInterface.cpp
  7. 58 55
      CBattleInterface.cpp
  8. 3 2
      CBattleInterface.h
  9. 147 672
      CCallback.cpp
  10. 25 54
      CCallback.h
  11. 30 26
      CCastleInterface.cpp
  12. 66 73
      CConsoleHandler.cpp
  13. 2 0
      CConsoleHandler.h
  14. 18 215
      CCursorHandler.cpp
  15. 7 11
      CCursorHandler.h
  16. 1 1
      CGameInfo.cpp
  17. 4 11
      CGameInfo.h
  18. 0 2
      CGameInterface.cpp
  19. 7 12
      CGameInterface.h
  20. 816 368
      CGameState.cpp
  21. 98 69
      CGameState.h
  22. 98 93
      CHeroWindow.cpp
  23. 2 2
      CHeroWindow.h
  24. 360 370
      CLua.cpp
  25. 44 63
      CLua.h
  26. 41 41
      CLuaHandler.cpp
  27. 131 877
      CMT.cpp
  28. 6 7
      CMessage.cpp
  29. 12 11
      CPathfinder.cpp
  30. 163 203
      CPlayerInterface.cpp
  31. 23 24
      CPlayerInterface.h
  32. 163 127
      CPreGame.cpp
  33. 4 4
      CPreGame.h
  34. 0 45
      CScreenHandler.cpp
  35. 0 17
      CScreenHandler.h
  36. 0 1
      ChangeLog
  37. 二進制
      DefSorter.exe
  38. 45 37
      Makefile.am
  39. 0 1
      NEWS
  40. 二進制
      Projekt.dia
  41. 0 1
      README
  42. 4 184
      SDL_Extensions.cpp
  43. 0 6
      SDL_Extensions.h
  44. 0 1231
      SDL_rotozoom.cpp
  45. 0 117
      SDL_rotozoom.h
  46. 29 8
      StartInfo.h
  47. 1 0
      aclocal.m4
  48. 147 0
      aclocal/m4/ax_boost_thread.m4
  49. 352 0
      client/CBitmapHandler.cpp
  50. 39 0
      client/CBitmapHandler.h
  51. 352 0
      client/CCreatureAnimation.cpp
  52. 45 0
      client/CCreatureAnimation.h
  53. 425 0
      client/Client.cpp
  54. 53 0
      client/Client.h
  55. 486 0
      client/Graphics.cpp
  56. 53 0
      client/Graphics.h
  57. 83 0
      client/Makefile.am
  58. 570 0
      client/VCMI_client.vcproj
  59. 3 0
      config.h.in
  60. 2 1
      configure.ac
  61. 30 27
      global.h
  62. 11 11
      hch/CAbilityHandler.cpp
  63. 43 2707
      hch/CAmbarCendamo.cpp
  64. 5 26
      hch/CAmbarCendamo.h
  65. 29 128
      hch/CArtHandler.cpp
  66. 4 4
      hch/CArtHandler.h
  67. 7 5
      hch/CBuildingHandler.cpp
  68. 4 3
      hch/CBuildingHandler.h
  69. 0 2
      hch/CCastleHandler.cpp
  70. 0 51
      hch/CCastleHandler.h
  71. 11 458
      hch/CCreatureHandler.cpp
  72. 11 67
      hch/CCreatureHandler.h
  73. 24 21
      hch/CDefHandler.cpp
  74. 63 76
      hch/CDefHandler.h
  75. 8 20
      hch/CDefObjInfoHandler.cpp
  76. 6 15
      hch/CDefObjInfoHandler.h
  77. 6 115
      hch/CGeneralTextHandler.cpp
  78. 2 17
      hch/CGeneralTextHandler.h
  79. 43 147
      hch/CHeroHandler.cpp
  80. 10 24
      hch/CHeroHandler.h
  81. 56 549
      hch/CLodHandler.cpp
  82. 8 33
      hch/CLodHandler.h
  83. 45 45
      hch/CMusicHandler.cpp
  84. 43 40
      hch/CObjectHandler.cpp
  85. 57 304
      hch/CObjectHandler.h
  86. 3 3
      hch/CPreGameTextHandler.cpp
  87. 0 148
      hch/CSemiDefHandler.cpp
  88. 0 31
      hch/CSemiDefHandler.h
  89. 0 12
      hch/CSemiLodHandler.cpp
  90. 0 13
      hch/CSemiLodHandler.h
  91. 2 2
      hch/CSpellHandler.cpp
  92. 12 46
      hch/CTownHandler.cpp
  93. 7 19
      hch/CTownHandler.h
  94. 24 8
      int3.h
  95. 13 0
      lib/BattleAction.h
  96. 13 0
      lib/CondSh.h
  97. 104 0
      lib/Connection.cpp
  98. 382 0
      lib/Connection.h
  99. 32 0
      lib/Makefile.am
  100. 337 0
      lib/NetPacks.h

+ 1 - 0
AI/EmptyAI/CEmptyAI.cpp

@@ -10,6 +10,7 @@ void CEmptyAI::init(ICallback * CB)
 }
 void CEmptyAI::yourTurn()
 {
+	cb->endTurn();
 }
 void CEmptyAI::heroKilled(const CGHeroInstance *)
 {

+ 6 - 6
AI/EmptyAI/exp_funcs.cpp

@@ -1,30 +1,30 @@
+#define VCMI_DLL
 #include "../../AI_Base.h"
 #include "CEmptyAI.h"
 #include <cstring>
 #include <set>
 std::set<CGlobalAI*> ais;
-
-DLL_EXPORT int GetGlobalAiVersion()
+extern "C" DLL_EXPORT int GetGlobalAiVersion()
 {
 	return AI_INTERFACE_VER;
 }
 
-DLL_EXPORT void GetAiName(char* name)
+extern "C" DLL_EXPORT void GetAiName(char* name)
 {
 	strcpy(name,NAME);
 }
-DLL_EXPORT char * GetAiNameS()
+extern "C" DLL_EXPORT char * GetAiNameS()
 {
 	char * ret = new char[50];
 	strcpy(ret,NAME);
 	return ret;
 }
-DLL_EXPORT CGlobalAI * GetNewAI()
+extern "C" DLL_EXPORT CGlobalAI * GetNewAI()
 {
 	return new CEmptyAI();
 // return
 }
-DLL_EXPORT void ReleaseAI(CGlobalAI * i)
+extern "C" DLL_EXPORT void ReleaseAI(CGlobalAI * i)
 {
 	delete (CEmptyAI*)i;
 	ais.erase(i);

+ 9 - 10
AI_Base.h

@@ -1,16 +1,15 @@
 #pragma once
 #include <vector>
 #include <iostream>
-#include "int3.h"
 #include "CGameInterface.h"
 
 #define AI_INTERFACE_VER 1
-#ifdef _WIN32
-	#define DLL_EXPORT extern "C" __declspec(dllexport)
-	#define VCMI_API
-#elif __GNUC__ >= 4
-	#define DLL_EXPORT extern "C" __attribute__ ((visibility("default")))
-	#define VCMI_API __attribute__ ((visibility("default")))
-#else
-	#define VCMI_EXPORT extern "C"
-#endif
+
+
+
+
+
+
+
+
+

+ 0 - 1
AUTHORS

@@ -1 +0,0 @@
-

+ 6 - 5
AdventureMapButton.cpp

@@ -7,6 +7,7 @@
 #include "hch/CTownHandler.h"
 #include "CLua.h"
 #include "CCallback.h"
+#include "client/Graphics.h"
 AdventureMapButton::AdventureMapButton ()
 {
 	type=2;
@@ -31,14 +32,14 @@ AdventureMapButton::AdventureMapButton
 	helpBox=HelpBox;
 	colorChange = playerColoredButton;
 	int est = LOCPLINT->playerID;
-	CDefHandler * temp = CGI->spriteh->giveDef(defName);
+	CDefHandler * temp = CDefHandler::giveDef(defName); 
 	temp->notFreeImgs = true;
 	for (int i=0;i<temp->ourImages.size();i++)
 	{
 		imgs.resize(1);
 		imgs[0].push_back(temp->ourImages[i].bitmap);
 		if(playerColoredButton)
-			CSDL_Ext::blueToPlayersAdv(imgs[curimg][i],LOCPLINT->playerID);
+			graphics->blueToPlayersAdv(imgs[curimg][i],LOCPLINT->playerID);
 	}
 	delete temp;
 	if (add)
@@ -46,13 +47,13 @@ AdventureMapButton::AdventureMapButton
 		imgs.resize(imgs.size()+add->size());
 		for (int i=0; i<add->size();i++)
 		{
-			temp = CGI->spriteh->giveDef((*add)[i]);
+			temp = CDefHandler::giveDef((*add)[i]);
 			temp->notFreeImgs = true;
 			for (int j=0;j<temp->ourImages.size();j++)
 			{
 				imgs[i+1].push_back(temp->ourImages[j].bitmap);
 				if(playerColoredButton)
-					CSDL_Ext::blueToPlayersAdv(imgs[1+i][j],LOCPLINT->playerID);
+					graphics->blueToPlayersAdv(imgs[1+i][j],LOCPLINT->playerID);
 			}
 			delete temp;
 		}
@@ -245,7 +246,7 @@ CSlider::CSlider(int x, int y, int totalw, boost::function<void(int)> Moved, int
 {
 	moving = false;
 	strongInterest = true;
-	imgs = CGI->spriteh->giveDefEss("IGPCRDIV.DEF");
+	imgs = CDefHandler::giveDefEss("IGPCRDIV.DEF");
 
 	left.pos.y = slider.pos.y = right.pos.y = pos.y = y;
 	left.pos.x = pos.x = x;

+ 47 - 45
CAdvmapInterface.cpp

@@ -1,9 +1,10 @@
 #include "stdafx.h"
 #include "CAdvmapInterface.h"
-#include "hch/CLodHandler.h"
+#include "client/CBitmapHandler.h"
 #include "CPlayerInterface.h"
 #include "hch/CPreGameTextHandler.h"
 #include "hch/CGeneralTextHandler.h"
+#include "hch/CDefHandler.h"
 #include "hch/CTownHandler.h"
 #include "CPathfinder.h"
 #include "CGameInfo.h"
@@ -19,7 +20,11 @@
 #include <sstream>
 #include "AdventureMapButton.h"
 #include "CHeroWindow.h"
-#pragma warning (disable : 4355)
+#include "client/Graphics.h"
+#include "hch/CObjectHandler.h"
+#include <boost/thread.hpp>
+#include "map.h"
+#pragma warning (disable : 4355) 
 extern TTF_Font * TNRB16, *TNR, *GEOR13, *GEORXX; //fonts
 
 using namespace boost::logic;
@@ -62,7 +67,7 @@ CMinimap::CMinimap(bool draw)
 	}
 	SDL_SetColorKey(radar,SDL_SRCCOLORKEY,SDL_MapRGB(radar->format,0,255,255));
 
-	//radar = CGI->spriteh->giveDef("RADAR.DEF");
+	//radar = CDefHandler::giveDef("RADAR.DEF");
 	std::ifstream is("config/minimap.txt",std::ifstream::in);
 	for (int i=0;i<TERRAIN_TYPES;i++)
 	{
@@ -112,11 +117,11 @@ void CMinimap::draw()
 		{
 			for (int jj=0; jj<ho; jj++)
 			{
-				SDL_PutPixel(temps,maplgp.x+ii,maplgp.y+jj,CGI->playerColors[hh[i]->getOwner()].r,CGI->playerColors[hh[i]->getOwner()].g,CGI->playerColors[hh[i]->getOwner()].b);
+				SDL_PutPixel(temps,maplgp.x+ii,maplgp.y+jj,graphics->playerColors[hh[i]->getOwner()].r,graphics->playerColors[hh[i]->getOwner()].g,graphics->playerColors[hh[i]->getOwner()].b);
 			}
 		}
 	}
-	blitAt(FoW[LOCPLINT->adventureInt->position.z],0,0,temps);
+	//blitAt(FoW[LOCPLINT->adventureInt->position.z],0,0,temps);
 
 	//draw radar
 	int bx = (((float)LOCPLINT->adventureInt->position.x)/(((float)CGI->mh->sizes.x)))*pos.w,
@@ -127,7 +132,7 @@ void CMinimap::draw()
 }
 void CMinimap::redraw(int level)// (level==-1) => redraw all levels
 {
-	(CGameInfo::mainObj);
+	(CGI);
 	for (int i=0; i<CGI->mh->sizes.z; i++)
 	{
 		SDL_Surface * pom ;
@@ -142,9 +147,9 @@ void CMinimap::redraw(int level)// (level==-1) => redraw all levels
 			{
 				int mx=(CGI->mh->sizes.x*x)/pos.w;
 				int my=(CGI->mh->sizes.y*y)/pos.h;
-				if (CGI->mh->ttiles[mx][my][i].blocked && (!CGI->mh->ttiles[mx][my][i].visitable))
-					SDL_PutPixel(pom,x,y,colorsBlocked[CGI->mh->ttiles[mx][my][i].terType].r,colorsBlocked[CGI->mh->ttiles[mx][my][i].terType].g,colorsBlocked[CGI->mh->ttiles[mx][my][i].terType].b);
-				else SDL_PutPixel(pom,x,y,colors[CGI->mh->ttiles[mx][my][i].terType].r,colors[CGI->mh->ttiles[mx][my][i].terType].g,colors[CGI->mh->ttiles[mx][my][i].terType].b);
+				if (CGI->mh->ttiles[mx][my][i].tileInfo->blocked && (!CGI->mh->ttiles[mx][my][i].tileInfo->visitable))
+					SDL_PutPixel(pom,x,y,colorsBlocked[CGI->mh->ttiles[mx][my][i].tileInfo->tertype].r,colorsBlocked[CGI->mh->ttiles[mx][my][i].tileInfo->tertype].g,colorsBlocked[CGI->mh->ttiles[mx][my][i].tileInfo->tertype].b);
+				else SDL_PutPixel(pom,x,y,colors[CGI->mh->ttiles[mx][my][i].tileInfo->tertype].r,colors[CGI->mh->ttiles[mx][my][i].tileInfo->tertype].g,colors[CGI->mh->ttiles[mx][my][i].tileInfo->tertype].b);
 			}
 		}
 		map.push_back(pom);
@@ -212,17 +217,17 @@ void CMinimap::deactivate()
 }
 void CMinimap::showTile(int3 pos)
 {
-	int mw = map[0]->w, mh = map[0]->h;
-	double wo = ((double)mw)/CGI->mh->sizes.x, ho = ((double)mh)/CGI->mh->sizes.y;
-	for (int ii=0; ii<wo; ii++)
-	{
-		for (int jj=0; jj<ho; jj++)
-		{
-			if ((pos.x*wo+ii<this->pos.w) && (pos.y*ho+jj<this->pos.h))
-				CSDL_Ext::SDL_PutPixel(FoW[pos.z],pos.x*wo+ii,pos.y*ho+jj,0,0,0,0,0);
+	//int mw = map[0]->w, mh = map[0]->h;
+	//double wo = ((double)mw)/CGI->mh->sizes.x, ho = ((double)mh)/CGI->mh->sizes.y;
+	//for (int ii=0; ii<wo; ii++)
+	//{
+	//	for (int jj=0; jj<ho; jj++)
+	//	{
+	//		if ((pos.x*wo+ii<this->pos.w) && (pos.y*ho+jj<this->pos.h))
+	//			CSDL_Ext::SDL_PutPixel(FoW[pos.z],pos.x*wo+ii,pos.y*ho+jj,0,0,0,0,0);
 
-		}
-	}
+	//	}
+	//}
 }
 void CMinimap::hideTile(int3 pos)
 {
@@ -235,7 +240,7 @@ CTerrainRect::CTerrainRect():currentPath(NULL)
 	pos.y=6;
 	pos.w=593;
 	pos.h=547;
-	arrows = CGI->spriteh->giveDef("ADAG.DEF");
+	arrows = CDefHandler::giveDef("ADAG.DEF");
 	for(int y=0; y<arrows->ourImages.size(); ++y)
 	{
 		arrows->ourImages[y].bitmap = CSDL_Ext::alphaTransform(arrows->ourImages[y].bitmap);
@@ -259,7 +264,6 @@ void CTerrainRect::deactivate()
 };
 void CTerrainRect::clickLeft(tribool down)
 {
-	LOGE("Left mouse button down2");
 	if ((down==false) || indeterminate(down))
 		return;
 	if (LOCPLINT->adventureInt->selection.type != HEROI_TYPE)
@@ -280,7 +284,9 @@ void CTerrainRect::clickLeft(tribool down)
 		if ( (currentPath->endPos()) == mp)
 		{ //move
 			CPath sended(*currentPath); //temporary path - engine will operate on it
+			LOCPLINT->pim->unlock();
 			mres = LOCPLINT->cb->moveHero( ((const CGHeroInstance*)LOCPLINT->adventureInt->selection.selected)->type->ID,&sended,1,0);
+			LOCPLINT->pim->lock();
 			if(!mres)
 			{
 				delete currentPath;
@@ -557,7 +563,7 @@ void CTerrainRect::show()
 	SDL_Surface * teren = CGI->mh->terrainRect
 		(LOCPLINT->adventureInt->position.x,LOCPLINT->adventureInt->position.y,
 		tilesw,tilesh,LOCPLINT->adventureInt->position.z,LOCPLINT->adventureInt->anim,
-		LOCPLINT->cb->getVisibilityMap(), true, LOCPLINT->adventureInt->heroAnim,
+		&LOCPLINT->cb->getVisibilityMap(), true, LOCPLINT->adventureInt->heroAnim,
 		screen,&genRect(547,594,7,6)
 		);
 	//SDL_BlitSurface(teren,&genRect(pos.h,pos.w,0,0),screen,&genRect(547,594,7,6));
@@ -593,13 +599,9 @@ void CResDataBar::deactivate()
 }
 CResDataBar::CResDataBar()
 {
-	bg = CGI->bitmaph->loadBitmap("ZRESBAR.bmp");
+	bg = BitmapHandler::loadBitmap("ZRESBAR.bmp");
 	SDL_SetColorKey(bg,SDL_SRCCOLORKEY,SDL_MapRGB(bg->format,0,255,255));
-	//std::vector<SDL_Color> kolory;
-	//SDL_Color p1={40,65,139,255}, p2={36,59,125,255}, p3={35,56,121,255};
-	//kolory+=p1,p2,p3;
-	//blueToPlayersAdv(bg,LOCPLINT->playerID,2,&kolory);
-	blueToPlayersAdv(bg,LOCPLINT->playerID,2);
+	graphics->blueToPlayersAdv(bg,LOCPLINT->playerID);
 	pos = genRect(bg->h,bg->w,3,575);
 
 	txtpos  +=  (std::pair<int,int>(35,577)),(std::pair<int,int>(120,577)),(std::pair<int,int>(205,577)),
@@ -638,11 +640,11 @@ CInfoBar::CInfoBar()
 	pos.y=389;
 	pos.w=194;
 	pos.h=186;
-	day = CGI->spriteh->giveDef("NEWDAY.DEF");
-	week1 = CGI->spriteh->giveDef("NEWWEEK1.DEF");
-	week2 = CGI->spriteh->giveDef("NEWWEEK2.DEF");
-	week3 = CGI->spriteh->giveDef("NEWWEEK3.DEF");
-	week4 = CGI->spriteh->giveDef("NEWWEEK4.DEF");
+	day = CDefHandler::giveDef("NEWDAY.DEF");
+	week1 = CDefHandler::giveDef("NEWWEEK1.DEF");
+	week2 = CDefHandler::giveDef("NEWWEEK2.DEF");
+	week3 = CDefHandler::giveDef("NEWWEEK3.DEF");
+	week4 = CDefHandler::giveDef("NEWWEEK4.DEF");
 }
 CInfoBar::~CInfoBar()
 {
@@ -680,14 +682,14 @@ void CInfoBar::draw(const CGObjectInstance * specific)
 
 	if(specific->ID == 34) //hero
 	{
-		if(LOCPLINT->heroWins.find(specific->subID)!=LOCPLINT->heroWins.end())
-			blitAt(LOCPLINT->heroWins[specific->subID],pos.x,pos.y);
+		if(graphics->heroWins.find(specific->subID)!=graphics->heroWins.end())
+			blitAt(graphics->heroWins[specific->subID],pos.x,pos.y);
 	}
 	else if (specific->ID == 98)
 	{
 		const CGTownInstance * t = static_cast<const CGTownInstance*>(specific);
-		if(LOCPLINT->townWins.find(t->identifier)!=LOCPLINT->townWins.end())
-			blitAt(LOCPLINT->townWins[t->identifier],pos.x,pos.y);
+		if(graphics->townWins.find(t->identifier)!=graphics->townWins.end())
+			blitAt(graphics->townWins[t->identifier],pos.x,pos.y);
 	}
 
 	//SDL_Surface * todr = LOCPLINT->infoWin(specific);
@@ -775,7 +777,7 @@ void CInfoBar::newDay(int Day)
 
 void CInfoBar::showComp(SComponent * comp, int time)
 {
-	SDL_Surface * b = CGI->bitmaph->loadBitmap("ADSTATOT.bmp");
+	SDL_Surface * b = BitmapHandler::loadBitmap("ADSTATOT.bmp");
 	blitAt(b,pos.x+8,pos.y+11);
 	blitAt(comp->getImg(),pos.x+52,pos.y+54);
 	printAtMiddle(comp->subtitle,pos.x+91,pos.y+158,GEOR13,zwykly);
@@ -849,8 +851,8 @@ townList(5,&genRect(192,48,747,196),747,196,747,372)
 {
 	townList.fun = boost::bind(&CAdvMapInt::selectionChanged,this);
 	LOCPLINT->adventureInt=this;
-	bg = CGI->bitmaph->loadBitmap("ADVMAP.bmp");
-	blueToPlayersAdv(bg,player);
+	bg = BitmapHandler::loadBitmap("ADVMAP.bmp");
+	graphics->blueToPlayersAdv(bg,player);
 	scrollingLeft = false;
 	scrollingRight  = false;
 	scrollingUp = false ;
@@ -868,10 +870,10 @@ townList(5,&genRect(192,48,747,196),747,196,747,372)
 
 	heroWindow = new CHeroWindow(this->player);
 
-	gems.push_back(CGI->spriteh->giveDef("agemLL.def"));
-	gems.push_back(CGI->spriteh->giveDef("agemLR.def"));
-	gems.push_back(CGI->spriteh->giveDef("agemUL.def"));
-	gems.push_back(CGI->spriteh->giveDef("agemUR.def"));
+	gems.push_back(CDefHandler::giveDef("agemLL.def"));
+	gems.push_back(CDefHandler::giveDef("agemLR.def"));
+	gems.push_back(CDefHandler::giveDef("agemUL.def"));
+	gems.push_back(CDefHandler::giveDef("agemUR.def"));
 }
 
 void CAdvMapInt::fshowOverview()
@@ -879,7 +881,7 @@ void CAdvMapInt::fshowOverview()
 }
 void CAdvMapInt::fswitchLevel()
 {
-	if(!CGI->ac->map.twoLevel)
+	if(!CGI->mh->map->twoLevel)
 		return;
 	if (position.z)
 	{

+ 58 - 55
CBattleInterface.cpp

@@ -4,15 +4,23 @@
 #include "SDL_Extensions.h"
 #include "CAdvmapInterface.h"
 #include "AdventureMapButton.h"
+#include "hch/CObjectHandler.h"
 #include "hch/CHeroHandler.h"
 #include "hch/CDefHandler.h"
 #include "CCallback.h"
 #include "CGameState.h"
 #include "hch/CGeneralTextHandler.h"
+#include "client/CCreatureAnimation.h"
+#include "client/Graphics.h"
 #include <queue>
 #include <sstream>
+#include "lib/CondSh.h"
+#ifndef __GNUC__
+const double M_PI = 3.14159265358979323846;
+#else
 #define _USE_MATH_DEFINES
 #include <cmath>
+#endif
 
 extern SDL_Surface * screen;
 extern TTF_Font * GEOR13;
@@ -22,6 +30,7 @@ SDL_Surface * CBattleInterface::cellBorder, * CBattleInterface::cellShade;
 CBattleInterface::CBattleInterface(CCreatureSet * army1, CCreatureSet * army2, CGHeroInstance *hero1, CGHeroInstance *hero2)
 : printCellBorders(true), attackingHeroInstance(hero1), defendingHeroInstance(hero2), animCount(0), activeStack(-1), givenCommand(NULL), attackingInfo(NULL), myTurn(false)
 {
+	givenCommand = new CondSh<BattleAction *>(NULL);
 	//initializing armies
 	this->army1 = army1;
 	this->army2 = army2;
@@ -35,14 +44,14 @@ CBattleInterface::CBattleInterface(CCreatureSet * army1, CCreatureSet * army2, C
 		creDir[b->second.ID] = b->second.owner==attackingHeroInstance->tempOwner;
 	}
 	//preparing menu background and terrain
-	std::vector< std::string > & backref = CGI->mh->battleBacks[ LOCPLINT->cb->battleGetBattlefieldType() ];
-	background = CGI->bitmaph->loadBitmap(backref[ rand() % backref.size()] );
-	menu = CGI->bitmaph->loadBitmap("CBAR.BMP");
-	CSDL_Ext::blueToPlayersAdv(menu, hero1->tempOwner);
+	std::vector< std::string > & backref = graphics->battleBacks[ LOCPLINT->cb->battleGetBattlefieldType() ];
+	background = BitmapHandler::loadBitmap(backref[ rand() % backref.size()] );
+	menu = BitmapHandler::loadBitmap("CBAR.BMP");
+	graphics->blueToPlayersAdv(menu, hero1->tempOwner);
 
 	//preparing graphics for displaying amounts of creatures
-	amountBasic = CGI->bitmaph->loadBitmap("CMNUMWIN.BMP");
-	amountNormal = CGI->bitmaph->loadBitmap("CMNUMWIN.BMP");
+	amountBasic = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
+	amountNormal = BitmapHandler::loadBitmap("CMNUMWIN.BMP");
 	CSDL_Ext::alphaTransform(amountNormal);
 	for(int g=0; g<amountNormal->format->palette->ncolors; ++g)
 	{
@@ -81,7 +90,7 @@ CBattleInterface::CBattleInterface(CCreatureSet * army1, CCreatureSet * army2, C
 	//loading hero animations
 	if(hero1) // attacking hero
 	{
-		attackingHero = new CBattleHero(CGI->mh->battleHeroes[hero1->type->heroType], 0, 0, false, hero1->tempOwner);
+		attackingHero = new CBattleHero(graphics->battleHeroes[hero1->type->heroType], 0, 0, false, hero1->tempOwner);
 		attackingHero->pos = genRect(attackingHero->dh->ourImages[0].bitmap->h, attackingHero->dh->ourImages[0].bitmap->w, -40, 0);
 	}
 	else
@@ -90,7 +99,7 @@ CBattleInterface::CBattleInterface(CCreatureSet * army1, CCreatureSet * army2, C
 	}
 	if(hero2) // defending hero
 	{
-		defendingHero = new CBattleHero(CGI->mh->battleHeroes[hero2->type->heroType], 0, 0, true, hero2->tempOwner);
+		defendingHero = new CBattleHero(graphics->battleHeroes[hero2->type->heroType], 0, 0, true, hero2->tempOwner);
 		defendingHero->pos = genRect(defendingHero->dh->ourImages[0].bitmap->h, defendingHero->dh->ourImages[0].bitmap->w, 690, 0);
 	}
 	else
@@ -99,9 +108,9 @@ CBattleInterface::CBattleInterface(CCreatureSet * army1, CCreatureSet * army2, C
 	}
 
 	//preparing cells and hexes
-	cellBorder = CGI->bitmaph->loadBitmap("CCELLGRD.BMP");
+	cellBorder = BitmapHandler::loadBitmap("CCELLGRD.BMP");
 	CSDL_Ext::alphaTransform(cellBorder);
-	cellShade = CGI->bitmaph->loadBitmap("CCELLSHD.BMP");
+	cellShade = BitmapHandler::loadBitmap("CCELLSHD.BMP");
 	CSDL_Ext::alphaTransform(cellShade);
 	for(int h=0; h<187; ++h)
 	{
@@ -124,7 +133,7 @@ CBattleInterface::CBattleInterface(CCreatureSet * army1, CCreatureSet * army2, C
 	{
 		if(g->second.creature->isShooting() && CGI->creh->idToProjectile[g->second.creature->idNumber] != std::string())
 		{
-			idToProjectile[g->second.creature->idNumber] = CGI->spriteh->giveDef(CGI->creh->idToProjectile[g->second.creature->idNumber]);
+			idToProjectile[g->second.creature->idNumber] = CDefHandler::giveDef(CGI->creh->idToProjectile[g->second.creature->idNumber]);
 
 			if(idToProjectile[g->second.creature->idNumber]->ourImages.size() > 2) //add symmetric images
 			{
@@ -161,6 +170,7 @@ CBattleInterface::~CBattleInterface()
 	delete bConsoleUp;
 	delete bConsoleDown;
 	delete console;
+	delete givenCommand;
 
 	delete attackingHero;
 	delete defendingHero;
@@ -351,7 +361,7 @@ bool CBattleInterface::reverseCreature(int number, int hex, bool wideTrick)
 	}
 	creDir[number] = !creDir[number];
 
-	CStack curs = LOCPLINT->cb->battleGetStackByID(number);
+	CStack curs = *LOCPLINT->cb->battleGetStackByID(number);
 	std::pair <int, int> coords = CBattleHex::getXYUnitAnim(hex, creDir[number], curs.creature);
 	creAnims[number]->pos.x = coords.first;
 	//creAnims[number]->pos.y = coords.second;
@@ -383,9 +393,7 @@ void CBattleInterface::bSurrenderf()
 
 void CBattleInterface::bFleef()
 {
-	BattleAction * ba = new BattleAction;
-	ba->actionType = 4;
-	givenCommand = ba;
+	giveCommand(4,0,0);
 }
 
 void CBattleInterface::bAutofightf()
@@ -402,10 +410,7 @@ void CBattleInterface::bWaitf()
 
 void CBattleInterface::bDefencef()
 {
-	BattleAction * ba = new BattleAction;
-	ba->actionType = 3;
-	ba->stackNumber = activeStack;
-	givenCommand = ba;
+	giveCommand(3,0,activeStack);
 }
 
 void CBattleInterface::bConsoleUpf()
@@ -439,7 +444,7 @@ void CBattleInterface::stackKilled(int ID, int dmg, int killed, int IDby, bool b
 	}
 	if(byShooting) //delay hit animation
 	{
-		CStack attacker = LOCPLINT->cb->battleGetStackByID(IDby);
+		CStack attacker = *LOCPLINT->cb->battleGetStackByID(IDby);
 		while(true)
 		{
 			bool found = false;
@@ -474,7 +479,7 @@ void CBattleInterface::stackKilled(int ID, int dmg, int killed, int IDby, bool b
 
 void CBattleInterface::stackActivated(int number)
 {
-	givenCommand = NULL;
+	//givenCommand = NULL;
 	activeStack = number;
 	shadedHexes = LOCPLINT->cb->battleGetAvailableHexes(number);
 	myTurn = true;
@@ -562,7 +567,7 @@ void CBattleInterface::stackMoved(int number, int destHex, bool startMoving, boo
 			CSDL_Ext::update();
 			SDL_framerateDelay(LOCPLINT->mainFPSmng);
 		}
-		if( (LOCPLINT->cb->battleGetStackByID(number).owner == attackingHeroInstance->tempOwner ) != creDir[number])
+		if( (LOCPLINT->cb->battleGetStackByID(number)->owner == attackingHeroInstance->tempOwner ) != creDir[number])
 		{
 			reverseCreature(number, curStackPos, true);
 		}
@@ -643,7 +648,7 @@ void CBattleInterface::stackMoved(int number, int destHex, bool startMoving, boo
 	}
 
 	creAnims[number]->setType(2); //resetting to default
-	CStack curs = LOCPLINT->cb->battleGetStackByID(number);
+	CStack curs = *LOCPLINT->cb->battleGetStackByID(number);
 	if(endMoving) //resetting to default
 	{
 		if(creDir[number] != (curs.owner == attackingHeroInstance->tempOwner))
@@ -664,7 +669,7 @@ void CBattleInterface::stackIsAttacked(int ID, int dmg, int killed, int IDby, bo
 	}
 	if(byShooting) //delay hit animation
 	{
-		CStack attacker = LOCPLINT->cb->battleGetStackByID(IDby);
+		CStack attacker = *LOCPLINT->cb->battleGetStackByID(IDby);
 		while(true)
 		{
 			bool found = false;
@@ -704,7 +709,7 @@ void CBattleInterface::stackAttacking(int ID, int dest)
 	{
 		return; //something went wrong
 	}
-	CStack aStack = LOCPLINT->cb->battleGetStackByID(ID); //attacking stack
+	CStack aStack = *LOCPLINT->cb->battleGetStackByID(ID); //attacking stack
 	if(aStack.creature->isDoubleWide())
 	{
 		switch(CBattleHex::mutualPosition(aStack.position, dest)) //attack direction
@@ -783,6 +788,16 @@ void CBattleInterface::newRound(int number)
 	console->addText(CGI->generaltexth->allTexts[412]);
 }
 
+void CBattleInterface::giveCommand(ui8 action, ui16 tile, ui32 stack)
+{
+	BattleAction * ba = new BattleAction(); //to be deleted by engine
+	ba->actionType = action;
+	ba->destinationTile = tile;
+	ba->stackNumber = stack;
+	givenCommand->setn(ba);
+	myTurn = false;
+}
+
 void CBattleInterface::hexLclicked(int whichOne)
 {
 	if((whichOne%17)!=0 && (whichOne%17)!=16) //if player is trying to attack enemey unit or move creature stack
@@ -794,28 +809,16 @@ void CBattleInterface::hexLclicked(int whichOne)
 		//LOCPLINT->cb->battleGetCreature();
 		if(atCre==-1) //normal move action
 		{
-			BattleAction * ba = new BattleAction(); //to be deleted by engine
-			ba->actionType = 2;
-			ba->destinationTile = whichOne;
-			ba->stackNumber = activeStack;
-			givenCommand = ba;
+			giveCommand(2,whichOne,activeStack);
 		}
-		else if(LOCPLINT->cb->battleGetStackByID(atCre).owner != attackingHeroInstance->tempOwner
+		else if(LOCPLINT->cb->battleGetStackByID(atCre)->owner != attackingHeroInstance->tempOwner
 			&& LOCPLINT->cb->battleCanShoot(activeStack, whichOne)) //shooting
 		{
-			BattleAction * ba = new BattleAction(); //to be deleted by engine
-			ba->actionType = 7;
-			ba->destinationTile = whichOne;
-			ba->stackNumber = activeStack;
-			givenCommand = ba;
+			giveCommand(7,whichOne,activeStack);
 		}
-		else if(LOCPLINT->cb->battleGetStackByID(atCre).owner != attackingHeroInstance->tempOwner) //attacking
+		else if(LOCPLINT->cb->battleGetStackByID(atCre)->owner != attackingHeroInstance->tempOwner) //attacking
 		{
-			BattleAction * ba = new BattleAction(); //to be deleted by engine
-			ba->actionType = 6;
-			ba->destinationTile = whichOne;
-			ba->stackNumber = activeStack;
-			givenCommand = ba;
+			giveCommand(6,whichOne,activeStack);
 		}
 	}
 }
@@ -835,7 +838,7 @@ void CBattleInterface::stackIsShooting(int ID, int dest)
 		projectileAngle = -projectileAngle;
 
 	SProjectileInfo spi;
-	spi.creID = LOCPLINT->cb->battleGetStackByID(ID).creature->idNumber;
+	spi.creID = LOCPLINT->cb->battleGetStackByID(ID)->creature->idNumber;
 
 	spi.step = 0;
 	spi.frameNum = 0;
@@ -907,7 +910,7 @@ void CBattleInterface::attackingShowHelper()
 	{
 		if(attackingInfo->frame == 0)
 		{
-			CStack aStack = LOCPLINT->cb->battleGetStackByID(attackingInfo->ID); //attacking stack
+			CStack aStack = *LOCPLINT->cb->battleGetStackByID(attackingInfo->ID); //attacking stack
 			if(attackingInfo->shooting)
 			{
 				creAnims[attackingInfo->ID]->setType(attackingInfo->shootingGroup);
@@ -967,7 +970,7 @@ void CBattleInterface::attackingShowHelper()
 		else if(attackingInfo->frame == (attackingInfo->maxframe - 1))
 		{
 			attackingInfo->reversing = true;
-			CStack aStack = LOCPLINT->cb->battleGetStackByID(attackingInfo->ID); //attacking stack
+			CStack aStack = *LOCPLINT->cb->battleGetStackByID(attackingInfo->ID); //attacking stack
 			if(aStack.creature->isDoubleWide())
 			{
 				switch(CBattleHex::mutualPosition(aStack.position, attackingInfo->dest)) //attack direction
@@ -1025,8 +1028,8 @@ void CBattleInterface::attackingShowHelper()
 void CBattleInterface::printConsoleAttacked(int ID, int dmg, int killed, int IDby)
 {
 	char tabh[200];
-	CStack attacker = LOCPLINT->cb->battleGetStackByID(IDby);
-	CStack defender = LOCPLINT->cb->battleGetStackByID(ID);
+	CStack attacker = *LOCPLINT->cb->battleGetStackByID(IDby);
+	CStack defender = *LOCPLINT->cb->battleGetStackByID(ID);
 	int end = sprintf(tabh, CGI->generaltexth->allTexts[attacker.amount > 1 ? 377 : 376].c_str(),
 		(attacker.amount > 1 ? attacker.creature->namePl.c_str() : attacker.creature->nameSing.c_str()),
 		dmg);
@@ -1123,7 +1126,7 @@ void CBattleHero::show(SDL_Surface *to)
 
 CBattleHero::CBattleHero(std::string defName, int phaseG, int imageG, bool flipG, unsigned char player): phase(phaseG), image(imageG), flip(flipG), flagAnim(0)
 {
-	dh = CGI->spriteh->giveDef( defName );
+	dh = CDefHandler::giveDef( defName );
 	for(int i=0; i<dh->ourImages.size(); ++i) //transforming images
 	{
 		if(flip)
@@ -1137,15 +1140,15 @@ CBattleHero::CBattleHero(std::string defName, int phaseG, int imageG, bool flipG
 	dh->alphaTransformed = true;
 
 	if(flip)
-		flag = CGI->spriteh->giveDef("CMFLAGR.DEF");
+		flag = CDefHandler::giveDef("CMFLAGR.DEF");
 	else
-		flag = CGI->spriteh->giveDef("CMFLAGL.DEF");
+		flag = CDefHandler::giveDef("CMFLAGL.DEF");
 
 	//coloring flag and adding transparency
 	for(int i=0; i<flag->ourImages.size(); ++i)
 	{
 		flag->ourImages[i].bitmap = CSDL_Ext::alphaTransform(flag->ourImages[i].bitmap);
-		CSDL_Ext::blueToPlayersAdv(flag->ourImages[i].bitmap, player);
+		graphics->blueToPlayersAdv(flag->ourImages[i].bitmap, player);
 	}
 }
 
@@ -1249,11 +1252,11 @@ void CBattleHex::mouseMoved(SDL_MouseMotionEvent &sEvent)
 	if(hovered && strictHovered) //print attacked creature to console
 	{
 		if(myInterface->console->alterTxt.size() == 0 && LOCPLINT->cb->battleGetStack(myNumber) != -1 &&
-			LOCPLINT->cb->battleGetStackByPos(myNumber).owner != LOCPLINT->playerID &&
-			LOCPLINT->cb->battleGetStackByPos(myNumber).alive)
+			LOCPLINT->cb->battleGetStackByPos(myNumber)->owner != LOCPLINT->playerID &&
+			LOCPLINT->cb->battleGetStackByPos(myNumber)->alive)
 		{
 			char tabh[160];
-			CStack attackedStack = LOCPLINT->cb->battleGetStackByPos(myNumber);
+			CStack attackedStack = *LOCPLINT->cb->battleGetStackByPos(myNumber);
 			std::string attackedName = attackedStack.amount == 1 ? attackedStack.creature->nameSing : attackedStack.creature->namePl;
 			sprintf(tabh, CGI->generaltexth->allTexts[220].c_str(), attackedName.c_str());
 			myInterface->console->alterTxt = std::string(tabh);
@@ -1280,7 +1283,7 @@ void CBattleHex::clickRight(boost::logic::tribool down)
 	int stID = LOCPLINT->cb->battleGetStack(myNumber); //id of stack being on this tile
 	if(hovered && strictHovered && stID!=-1)
 	{
-		CStack myst = LOCPLINT->cb->battleGetStackByID(stID); //stack info
+		CStack myst = *LOCPLINT->cb->battleGetStackByID(stID); //stack info
 		StackState *pom = NULL;
 		if(down)
 		{

+ 3 - 2
CBattleInterface.h

@@ -9,6 +9,7 @@ class CDefHandler;
 class CStack;
 class CCallback;
 class AdventureMapButton;
+template <typename T> struct CondSh;
 
 class CBattleHero : public IShowable, public CIntObject
 {
@@ -112,7 +113,7 @@ private:
 	};
 	std::list<SProjectileInfo> projectiles;
 	void projectileShowHelper(SDL_Surface * to=NULL); //prints projectiles present on the battlefield
-	
+	void giveCommand(ui8 action, ui16 tile, ui32 stack);
 public:
 	CBattleInterface(CCreatureSet * army1, CCreatureSet * army2, CGHeroInstance *hero1, CGHeroInstance *hero2); //c-tor
 	~CBattleInterface(); //d-tor
@@ -122,7 +123,7 @@ public:
 	CBattleHex bfield[187]; //11 lines, 17 hexes on each
 	std::vector< CBattleObstacle * > obstacles; //vector of obstacles on the battlefield
 	static SDL_Surface * cellBorder, * cellShade;
-	BattleAction * givenCommand; //true if we have i.e. moved current unit
+	CondSh<BattleAction *> *givenCommand; //data != NULL if we have i.e. moved current unit
 	bool myTurn; //if true, interface is active (commands can be ordered
 
 	//button handle funcs:

+ 147 - 672
CCallback.cpp

@@ -8,77 +8,30 @@
 #include "mapHandler.h"
 #include "CGameState.h"
 #include "CPlayerInterface.h"
-#include "CLua.h"
 #include "hch/CGeneralTextHandler.h"
 #include "CAdvmapInterface.h"
 #include "CPlayerInterface.h"
 #include "hch/CBuildingHandler.h"
-
-#ifndef _MSC_VER
-extern "C" {
+#include "hch/CObjectHandler.h"
+#include "lib/Connection.h"
+#include "client/Client.h"
+#include <boost/thread.hpp>
+#include <boost/foreach.hpp>
+#include "lib/NetPacks.h"
+#include <boost/thread/shared_mutex.hpp>
+#ifdef min
+#undef min
 #endif
-
-LUALIB_API int (luaL_error) (lua_State *L, const char *fmt, ...);
-
-#ifndef _MSC_VER
-}
+#ifdef max
+#undef max
 #endif
+extern CSharedCond<std::set<IPack*> > mess;
 
-int CCallback::lowestSpeed(CGHeroInstance * chi)
+HeroMoveDetails::HeroMoveDetails(int3 Src, int3 Dst, CGHeroInstance*Ho)
+	:src(Src),dst(Dst),ho(Ho)
 {
-	int min = 150;
-	for (  std::map<int,std::pair<CCreature*,int> >::iterator i = chi->army.slots.begin();
-		   i!=chi->army.slots.end();		 i++													)
-	{
-		if (min>(*i).second.first->speed)
-			min = (*i).second.first->speed;
-	}
-	return min;
-}
-int CCallback::valMovePoints(CGHeroInstance * chi)
-{
-	int ret = 1270+70*lowestSpeed(chi);
-	if (ret>2000)
-		ret=2000;
-
-	//TODO: additional bonuses (but they aren't currently stored in chi)
-
-	return ret;
-}
-void CCallback::newTurn()
-{
-	//std::map<int, PlayerState>::iterator i = gs->players.begin() ;
-	gs->day++;
-	for (std::set<CCPPObjectScript *>::iterator i=gs->cppscripts.begin();i!=gs->cppscripts.end();i++)
-	{
-		(*i)->newTurn();
-	}
-	for ( std::map<int, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
-	{
-		//handle heroes/////////////////////////////
-		for (int j=0;j<(*i).second.heroes.size();j++)
-		{
-			(*i).second.heroes[j]->movement = valMovePoints((*i).second.heroes[j]);
-		}
-
-
-		//handle towns/////////////////////////////
-		for(int j=0;j<i->second.towns.size();j++)
-		{
-			i->second.towns[j]->builded=0;
-			if(getDate(1)==1) //first day of week
-			{
-				for(int k=0;k<CREATURES_PER_TOWN;k++)
-				{
-					if(i->second.towns[j]->creatureDwelling(k))//there is dwelling
-						i->second.towns[j]->strInfo.creatures[k]+=i->second.towns[j]->creatureGrowth(k);
-				}
-			}
-			if((gs->day>1) && i->first<PLAYER_LIMIT)
-				i->second.resources[6]+=i->second.towns[j]->dailyIncome();
-		}
-	}
-}
+	owner = ho->getOwner();
+};
 bool CCallback::moveHero(int ID, CPath * path, int idtype, int pathType)
 {
 	CGHeroInstance * hero = NULL;
@@ -101,7 +54,7 @@ bool CCallback::moveHero(int ID, CPath * path, int idtype, int pathType)
 	else //idtype==1; player<0
 	{
 
-		for(std::map<int, PlayerState>::iterator j=CGI->state->players.begin(); j!=CGI->state->players.end(); ++j)
+		for(std::map<ui8, PlayerState>::iterator j=gs->players.begin(); j!=gs->players.end(); ++j)
 		{
 			for (int i=0; i<(*j).second.heroes.size();i++)
 			{
@@ -127,124 +80,26 @@ bool CCallback::moveHero(int ID, CPath * path, int idtype, int pathType)
 #else
 		throw std::exception();
 #endif
-	CPath * ourPath = path;
+
+	CPath * ourPath = path; 
 	if(!ourPath)
 		return false;
 	for(int i=ourPath->nodes.size()-1; i>0; i--)
 	{
-		int3 stpos, endpos;
-		stpos = int3(ourPath->nodes[i].coord.x, ourPath->nodes[i].coord.y, hero->pos.z);
-		endpos = int3(ourPath->nodes[i-1].coord.x, ourPath->nodes[i-1].coord.y, hero->pos.z);
-		HeroMoveDetails curd;
-		curd.src = stpos;
-		curd.dst = endpos;
-		curd.ho = hero;
-		curd.owner = hero->getOwner();
-		/*if(player!=-1)
-		{
-			hero->pos = endpos;
-		}*/
-		if(hero->movement >= (ourPath->nodes.size()>=2 ?  (*(ourPath->nodes.end()-2)).dist : 0) - ourPath->nodes[i].dist  || player==-1)
-		{ //performing move
-			hero->movement -= (ourPath->nodes.size()>=2 ?  (*(ourPath->nodes.end()-2)).dist : 0) - ourPath->nodes[i].dist;
-			ourPath->nodes.pop_back();
-
-			std::vector< CGObjectInstance * > vis = CGI->mh->getVisitableObjs(CGHeroInstance::convertPosition(curd.dst,false));
-			bool blockvis = false;
-			for (int pit = 0; pit<vis.size();pit++)
-				if (vis[pit]->blockVisit)
-					blockvis = true;
-
-			if (!blockvis)
-			{
-				curd.successful = true;
-				hero->pos = curd.dst;
-
-				//inform leaved objects
-				std::vector< CGObjectInstance * > leave = CGI->mh->getVisitableObjs(CGHeroInstance::convertPosition(curd.src,false));
-				for (int iii=0; iii<leave.size(); iii++) //if object is visitable we call onHeroVisit
-				{
-					//TODO: allow to handle this in LUA
-					if(leave[iii]->state) //hard-coded function
-						leave[iii]->state->onHeroLeave(leave[iii],curd.ho->subID);
-				}
-
-
-				//reveal fog of war
-				int heroSight = hero->getSightDistance();
-				int xbeg = stpos.x - heroSight - 2;
-				if(xbeg < 0)
-					xbeg = 0;
-				int xend = stpos.x + heroSight + 2;
-				if(xend >= CGI->ac->map.width)
-					xend = CGI->ac->map.width;
-				int ybeg = stpos.y - heroSight - 2;
-				if(ybeg < 0)
-					ybeg = 0;
-				int yend = stpos.y + heroSight + 2;
-				if(yend >= CGI->ac->map.height)
-					yend = CGI->ac->map.height;
-				for(int xd=xbeg; xd<xend; ++xd) //revealing part of map around heroes
-				{
-					for(int yd=ybeg; yd<yend; ++yd)
-					{
-						int deltaX = (hero->getPosition(false).x-xd)*(hero->getPosition(false).x-xd);
-						int deltaY = (hero->getPosition(false).y-yd)*(hero->getPosition(false).y-yd);
-						if(deltaX+deltaY<hero->getSightDistance()*hero->getSightDistance())
-						{
-							if(gs->players[player].fogOfWarMap[xd][yd][hero->getPosition(false).z] == 0)
-							{
-								CGI->playerint[gs->players[player].serial]->tileRevealed(int3(xd, yd, hero->getPosition(false).z));
-							}
-							gs->players[player].fogOfWarMap[xd][yd][hero->getPosition(false).z] = 1;
-						}
-					}
-				}
-
-
-				//notify interfacesabout move
-				int nn=0; //number of interfece of currently browsed player
-				for(std::map<int, PlayerState>::iterator j=CGI->state->players.begin(); j!=CGI->state->players.end(); ++j)//CGI->state->players.size(); ++j) //for testing
-				{
-					if (j->first > PLAYER_LIMIT)
-						break;
-					if(j->second.fogOfWarMap[stpos.x-1][stpos.y][stpos.z] || j->second.fogOfWarMap[endpos.x-1][endpos.y][endpos.z])
-					{ //player should be notified
-						CGI->playerint[j->second.serial]->heroMoved(curd);
-					}
-					++nn;
-				}
-
-
-				//call objects if they arevisited
-				for (int iii=0; iii<vis.size(); iii++) //if object is visitable we call onHeroVisit
-				{
-					if(gs->checkFunc(vis[iii]->ID,"heroVisit")) //script function
-						gs->objscr[vis[iii]->ID]["heroVisit"]->onHeroVisit(vis[iii],curd.ho->subID);
-					if(vis[iii]->state) //hard-coded function
-						vis[iii]->state->onHeroVisit(vis[iii],curd.ho->subID);
-				}
-			}
-			else //interaction with blocking object (like resources)
-			{
-				curd.successful = false;
-				CGI->playerint[gs->players[hero->getOwner()].serial]->heroMoved(curd);
-				for (int iii=0; iii<vis.size(); iii++) //if object is visitable we call onHeroVisit
-				{
-					if (vis[iii]->blockVisit)
-					{
-						if(gs->checkFunc(vis[iii]->ID,"heroVisit")) //script function
-							gs->objscr[vis[iii]->ID]["heroVisit"]->onHeroVisit(vis[iii],curd.ho->subID);
-						if(vis[iii]->state) //hard-coded function
-							vis[iii]->state->onHeroVisit(vis[iii],curd.ho->subID);
-					}
-				}
+		int3 stpos(ourPath->nodes[i].coord.x, ourPath->nodes[i].coord.y, hero->pos.z), 
+			endpos(ourPath->nodes[i-1].coord.x, ourPath->nodes[i-1].coord.y, hero->pos.z);
+		HeroMoveDetails curd(stpos,endpos,hero);
+		*cl->serv << ui16(501) << hero->id << stpos << endpos;
+		{//wait till there is server answer
+			boost::unique_lock<boost::mutex> lock(*mess.mx);
+			while(std::find_if(mess.res->begin(),mess.res->end(),IPack::isType<501>) == mess.res->end())
+				mess.cv->wait(lock);
+			std::set<IPack*>::iterator itr = std::find_if(mess.res->begin(),mess.res->end(),IPack::isType<501>);
+			TryMoveHero tmh = *static_cast<TryMoveHero*>(*itr);
+			mess.res->erase(itr);
+			if(!tmh.result)
 				return false;
-			}
-
 		}
-		else
-			return true; //move ended - no more movement points
 	}
 	return true;
 }
@@ -252,8 +107,8 @@ bool CCallback::moveHero(int ID, CPath * path, int idtype, int pathType)
 void CCallback::selectionMade(int selection, int asker)
 {
 	//todo - jak bedzie multiplayer po sieci, to moze wymagac przerobek zaleznych od obranego modelu
-	IChosen * ask = (IChosen *)asker;
-	ask->chosen(selection);
+	//IChosen * ask = (IChosen *)asker;
+	//ask->chosen(selection);
 }
 void CCallback::recruitCreatures(const CGObjectInstance *obj, int ID, int amount)
 {
@@ -266,12 +121,12 @@ void CCallback::recruitCreatures(const CGObjectInstance *obj, int ID, int amount
 		//verify
 		bool found = false;
 		typedef std::pair<const int,int> Parka;
-		for(std::map<int,int>::iterator av=t->strInfo.creatures.begin();av!=t->strInfo.creatures.end();av++)
+		for(std::map<si32,ui32>::iterator av=t->strInfo.creatures.begin();av!=t->strInfo.creatures.end();av++)
 		{
 			if(	(   found  = (ID == t->town->basicCreatures[av->first])   ) //creature is available among basic cretures
 				|| (found  = (ID == t->town->upgradedCreatures[av->first]))			)//creature is available among upgraded cretures
 			{
-				amount = std::min(amount,av->second); //reduce recruited amount up to available amount
+				amount = std::min(amount,(int)av->second); //reduce recruited amount up to available amount
 				ser = av->first;
 				break;
 			}
@@ -290,11 +145,11 @@ void CCallback::recruitCreatures(const CGObjectInstance *obj, int ID, int amount
 
 		//recruit
 		int slot = -1; //slot ID
-		std::pair<int,std::pair<CCreature*,int> > parb;
+		std::pair<si32,std::pair<ui32,si32> > parb;	
 
 		for(int i=0;i<7;i++) //TODO: if there is already stack of same creatures it should be used always
 		{
-			if((!t->army.slots[i].first) || (t->army.slots[i].first->idNumber == ID)) //slot is free or there is saem creature
+			if(((!t->army.slots[i].first) && (!t->army.slots[i].second)) || (t->army.slots[i].first == ID)) //slot is free or there is saem creature
 			{
 				slot = i;
 				break;
@@ -314,10 +169,10 @@ void CCallback::recruitCreatures(const CGObjectInstance *obj, int ID, int amount
 		}
 		else //create new stack in the garrison
 		{
-			t->army.slots[slot].first = &CGI->creh->creatures[ID];
+			t->army.slots[slot].first = ID;
 			t->army.slots[slot].second = amount;
 		}
-		CGI->playerint[gs->players[player].serial]->garrisonChanged(obj);
+		cl->playerint[player]->garrisonChanged(obj);
 
 	}
 	//TODO: recruit from dwellings on the adventure map
@@ -326,11 +181,9 @@ void CCallback::recruitCreatures(const CGObjectInstance *obj, int ID, int amount
 
 bool CCallback::dismissCreature(const CArmedInstance *obj, int stackPos)
 {
-	if((player>=0)  &&  obj->tempOwner != player)
+	if(((player>=0)  &&  obj->tempOwner != player) || obj->army.slots.size()<2)
 		return false;
-	CArmedInstance *ob = const_cast<CArmedInstance*>(obj);
-	ob->army.slots.erase(stackPos);
-	CGI->playerint[gs->players[player].serial]->garrisonChanged(obj);
+	*cl->serv << ui16(503) << obj->id <<  ui8(stackPos);
 	return true;
 }
 bool CCallback::upgradeCreature(const CArmedInstance *obj, int stackPos, int newID)
@@ -338,10 +191,17 @@ bool CCallback::upgradeCreature(const CArmedInstance *obj, int stackPos, int new
 	//TODO: write
 	return false;
 }
+void CCallback::endTurn()
+{
+	std::cout << "Player "<<(unsigned)player<<" end his turn."<<std::endl;
+	cl->serv->wmx->lock();
+	*cl->serv << ui16(100); //report that we ended turn
+	cl->serv->wmx->unlock();
+}
 UpgradeInfo CCallback::getUpgradeInfo(const CArmedInstance *obj, int stackPos)
 {
 	UpgradeInfo ret;
-	CCreature *base = ((CArmedInstance*)obj)->army.slots[stackPos].first;
+	CCreature *base = &CGI->creh->creatures[((CArmedInstance *)obj)->army.slots[stackPos].first];
 	if((obj->ID == 98)  ||  ((obj->ID == 34) && static_cast<const CGHeroInstance*>(obj)->visitedTown))
 	{
 		CGTownInstance * t;
@@ -349,7 +209,7 @@ UpgradeInfo CCallback::getUpgradeInfo(const CArmedInstance *obj, int stackPos)
 			t = static_cast<CGTownInstance *>(const_cast<CArmedInstance *>(obj));
 		else
 			t = static_cast<const CGHeroInstance*>(obj)->visitedTown;
-		for(std::set<int>::iterator i=t->builtBuildings.begin();  i!=t->builtBuildings.end(); i++)
+		for(std::set<si32>::iterator i=t->builtBuildings.begin();  i!=t->builtBuildings.end(); i++)
 		{
 			if( (*i) >= 37   &&   (*i) < 44 ) //upgraded creature dwelling
 			{
@@ -376,6 +236,11 @@ UpgradeInfo CCallback::getUpgradeInfo(const CArmedInstance *obj, int stackPos)
 	return ret;
 }
 
+const StartInfo * CCallback::getStartInfo()
+{
+	return gs->scenarioOps;
+}
+
 int CCallback::howManyTowns()
 {
 	return gs->players[gs->currentPlayer].towns.size();
@@ -384,7 +249,7 @@ const CGTownInstance * CCallback::getTownInfo(int val, bool mode) //mode = 0 ->
 {
 	if (!mode)
 		return gs->players[gs->currentPlayer].towns[val];
-	else
+	else 
 	{
 		//TODO: add some smart ID to the CTownInstance
 
@@ -400,17 +265,19 @@ const CGTownInstance * CCallback::getTownInfo(int val, bool mode) //mode = 0 ->
 }
 int CCallback::howManyHeroes()
 {
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
 	return gs->players[player].heroes.size();
 }
 const CGHeroInstance * CCallback::getHeroInfo(int player, int val, bool mode) //mode = 0 -> val = serial; mode = 1 -> val = ID
 {
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
 	if (gs->currentPlayer!=player) //TODO: checking if we are allowed to give that info
 		return NULL;
 	if (!mode)
 		if(val<gs->players[player].heroes.size())
 			return gs->players[player].heroes[val];
 		else return NULL;
-	else
+	else 
 	{
 		for (int i=0; i<gs->players[player].heroes.size();i++)
 		{
@@ -423,45 +290,33 @@ const CGHeroInstance * CCallback::getHeroInfo(int player, int val, bool mode) //
 
 int CCallback::getResourceAmount(int type)
 {
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
 	return gs->players[player].resources[type];
 }
-std::vector<int> CCallback::getResourceAmount()
+std::vector<si32> CCallback::getResourceAmount()
 {
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
 	return gs->players[player].resources;
 }
 int CCallback::getDate(int mode)
 {
-	int temp;
-	switch (mode)
-	{
-	case 0:
-		return gs->day;
-		break;
-	case 1:
-		temp = (gs->day)%7;
-		if (temp)
-			return temp;
-		else return 7;
-		break;
-	case 2:
-		temp = ((gs->day-1)/7)+1;
-		if (!(temp%4))
-			return 4;
-		else
-			return (temp%4);
-		break;
-	case 3:
-		return ((gs->day-1)/28)+1;
-		break;
-	}
-	return 0;
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
+	return gs->getDate(mode);
+}
+std::vector < std::string > CCallback::getObjDescriptions(int3 pos)
+{
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
+	std::vector<std::string> ret;
+	BOOST_FOREACH(const CGObjectInstance * obj, gs->map->terrain[pos.x][pos.y][pos.z].blockingObjects)
+		ret.push_back(obj->hoverName);
+	return ret;
 }
 bool CCallback::verifyPath(CPath * path, bool blockSea)
 {
 	for (int i=0;i<path->nodes.size();i++)
 	{
-		if ( CGI->mh->ttiles[path->nodes[i].coord.x][path->nodes[i].coord.y][path->nodes[i].coord.z].blocked
-			&& (! (CGI->mh->ttiles[path->nodes[i].coord.x][path->nodes[i].coord.y][path->nodes[i].coord.z].visitable)))
+		if ( CGI->mh->ttiles[path->nodes[i].coord.x][path->nodes[i].coord.y][path->nodes[i].coord.z].tileInfo->blocked 
+			&& (! (CGI->mh->ttiles[path->nodes[i].coord.x][path->nodes[i].coord.y][path->nodes[i].coord.z].tileInfo->visitable)))
 			return false; //path is wrong - one of the tiles is blocked
 
 		if (blockSea)
@@ -470,16 +325,16 @@ bool CCallback::verifyPath(CPath * path, bool blockSea)
 				continue;
 
 			if (
-					((CGI->mh->ttiles[path->nodes[i].coord.x][path->nodes[i].coord.y][path->nodes[i].coord.z].terType==water)
+					((CGI->mh->ttiles[path->nodes[i].coord.x][path->nodes[i].coord.y][path->nodes[i].coord.z].tileInfo->tertype==water)
 					&&
-					(CGI->mh->ttiles[path->nodes[i-1].coord.x][path->nodes[i-1].coord.y][path->nodes[i-1].coord.z].terType!=water))
+					(CGI->mh->ttiles[path->nodes[i-1].coord.x][path->nodes[i-1].coord.y][path->nodes[i-1].coord.z].tileInfo->tertype!=water))
 				  ||
-					((CGI->mh->ttiles[path->nodes[i].coord.x][path->nodes[i].coord.y][path->nodes[i].coord.z].terType!=water)
+					((CGI->mh->ttiles[path->nodes[i].coord.x][path->nodes[i].coord.y][path->nodes[i].coord.z].tileInfo->tertype!=water)
 					&&
-					(CGI->mh->ttiles[path->nodes[i-1].coord.x][path->nodes[i-1].coord.y][path->nodes[i-1].coord.z].terType==water))
+					(CGI->mh->ttiles[path->nodes[i-1].coord.x][path->nodes[i-1].coord.y][path->nodes[i-1].coord.z].tileInfo->tertype==water))
 				  ||
-				  (CGI->mh->ttiles[path->nodes[i-1].coord.x][path->nodes[i-1].coord.y][path->nodes[i-1].coord.z].terType==rock)
-
+				  (CGI->mh->ttiles[path->nodes[i-1].coord.x][path->nodes[i-1].coord.y][path->nodes[i-1].coord.z].tileInfo->tertype==rock)
+					
 				)
 				return false;
 		}
@@ -489,28 +344,24 @@ bool CCallback::verifyPath(CPath * path, bool blockSea)
 	return true;
 }
 
-std::vector < std::string > CCallback::getObjDescriptions(int3 pos)
-{
-	if(gs->players[player].fogOfWarMap[pos.x][pos.y][pos.z])
-		return CGI->mh->getObjDescriptions(pos);
-	else return std::vector< std::string > ();
-}
-
-PseudoV< PseudoV< PseudoV<unsigned char> > > & CCallback::getVisibilityMap()
+std::vector< std::vector< std::vector<unsigned char> > > & CCallback::getVisibilityMap()
 {
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
 	return gs->players[player].fogOfWarMap;
 }
 
 
 bool CCallback::isVisible(int3 pos, int Player)
 {
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
 	return gs->players[Player].fogOfWarMap[pos.x][pos.y][pos.z];
 }
 
 std::vector < const CGTownInstance *> CCallback::getTownsInfo(bool onlyOur)
 {
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
 	std::vector < const CGTownInstance *> ret = std::vector < const CGTownInstance *>();
-	for ( std::map<int, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
+	for ( std::map<ui8, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
 	{
 		for (int j=0;j<(*i).second.towns.size();j++)
 		{
@@ -524,17 +375,16 @@ std::vector < const CGTownInstance *> CCallback::getTownsInfo(bool onlyOur)
 }
 std::vector < const CGHeroInstance *> CCallback::getHeroesInfo(bool onlyOur)
 {
-	std::vector < const CGHeroInstance *> ret = std::vector < const CGHeroInstance *>();
-	for ( std::map<int, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
+	std::vector < const CGHeroInstance *> ret;
+	for(int i=0;i<gs->map->heroes.size();i++)
 	{
-		for (int j=0;j<(*i).second.heroes.size();j++)
+		if(	 (gs->map->heroes[i]->tempOwner==player) ||
+		   (isVisible(gs->map->heroes[i]->getPosition(false),player) && !onlyOur)	)
 		{
-			if ( ( isVisible((*i).second.heroes[j]->getPosition(false),player) ) || (*i).first==player)
-			{
-				ret.push_back((*i).second.heroes[j]);
-			}
+			ret.push_back(gs->map->heroes[i]);
 		}
-	} //	for ( std::map<int, PlayerState>::iterator i=gs->players.begin() ; i!=gs->players.end();i++)
+	}
 	return ret;
 }
 
@@ -549,6 +399,7 @@ int CCallback::getMyColor()
 }
 int CCallback::getHeroSerial(const CGHeroInstance * hero)
 {
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
 	for (int i=0; i<gs->players[player].heroes.size();i++)
 	{
 		if (gs->players[player].heroes[i]==hero)
@@ -569,143 +420,42 @@ const CCreatureSet* CCallback::getGarrison(const CGObjectInstance *obj)
 
 int CCallback::swapCreatures(const CGObjectInstance *s1, const CGObjectInstance *s2, int p1, int p2)
 {
-	CCreatureSet *S1 = const_cast<CCreatureSet*>(getGarrison(s1)), *S2 = const_cast<CCreatureSet*>(getGarrison(s2));
-	if (((s1->ID == 34)&&(S1->slots.size()==1)&&(!S2->slots[p2].first)) || ((s2->ID == 34)&&(S2->slots.size()==1)&&(!S1->slots[p1].first)) || (0/*we are not allowed*/)) 
-	{
-		//TODO: check if we are allowed to swap these creatures
+	if(s1->tempOwner != player   ||   s2->tempOwner != player)
 		return -1;
-	}
 
-	CCreature * pom = S2->slots[p2].first;
-	S2->slots[p2].first = S1->slots[p1].first;
-	S1->slots[p1].first = pom;
-	int pom2 = S2->slots[p2].second;
-	S2->slots[p2].second = S1->slots[p1].second;
-	S1->slots[p1].second = pom2;
-
-	if(!S1->slots[p1].first)
-		S1->slots.erase(p1);
-	if(!S2->slots[p2].first)
-		S2->slots.erase(p2);
-
-	if(s1->tempOwner<PLAYER_LIMIT)
-	{
-		for(int b=0; b<CGI->playerint.size(); ++b)
-		{
-			if(CGI->playerint[b]->playerID == s1->tempOwner)
-			{
-				CGI->playerint[b]->garrisonChanged(s1);
-				break;
-			}
-		}
-	}
-	if((s2->tempOwner<PLAYER_LIMIT) && (s2 != s1))
-	{
-		for(int b=0; b<CGI->playerint.size(); ++b)
-		{
-			if(CGI->playerint[b]->playerID == s2->tempOwner)
-			{
-				CGI->playerint[b]->garrisonChanged(s2);
-				break;
-			}
-		}
-	}
+	*cl->serv << ui16(502) << ui8(1) << s1->id << ui8(p1) << s2->id << ui8(p2);
 	return 0;
 }
 
 int CCallback::mergeStacks(const CGObjectInstance *s1, const CGObjectInstance *s2, int p1, int p2)
-{
-	CCreatureSet *S1 = const_cast<CCreatureSet*>(getGarrison(s1)), *S2 = const_cast<CCreatureSet*>(getGarrison(s2));
-	if ((S1->slots[p1].first != S2->slots[p2].first) && (true /*we are allowed to*/))
+{	
+	if ((s1->tempOwner!= player  ||  s2->tempOwner!=player))
 	{
 		return -1;
 	}
-
-
-	S2->slots[p2].second += S1->slots[p1].second;
-	S1->slots[p1].first = NULL;
-	S1->slots[p1].second = 0;
-
-	S1->slots.erase(p1);
-
-	if(s1->tempOwner<PLAYER_LIMIT)
-	{
-		for(int b=0; b<CGI->playerint.size(); ++b)
-		{
-			if(CGI->playerint[b]->playerID == s1->tempOwner)
-			{
-				CGI->playerint[b]->garrisonChanged(s1);
-				break;
-			}
-		}
-	}
-	if((s2->tempOwner<PLAYER_LIMIT) && (s2 != s1))
-	{
-		for(int b=0; b<CGI->playerint.size(); ++b)
-		{
-			if(CGI->playerint[b]->playerID == s2->tempOwner)
-			{
-				CGI->playerint[b]->garrisonChanged(s2);
-				break;
-			}
-		}
-	}
+	*cl->serv << ui16(502) << ui8(2) << s1->id << ui8(p1) << s2->id << ui8(p2);
 	return 0;
 }
 int CCallback::splitStack(const CGObjectInstance *s1, const CGObjectInstance *s2, int p1, int p2, int val)
 {
-	if(!val)
-		return -1;
-	CCreatureSet *S1 = const_cast<CCreatureSet*>(getGarrison(s1)), *S2 = const_cast<CCreatureSet*>(getGarrison(s2));
-	if ((S1->slots[p1].second<val) || ((S1->slots[p1].second==val)&&(S1->slots.size()==2)) || (0/*we are not allowed*/))
+	if (s1->tempOwner!= player  ||  s2->tempOwner!=player || (!val))
 	{
 		return -1;
 	}
-
-	S2->slots[p2].first = S1->slots[p1].first;
-	S2->slots[p2].second = val;
-	S1->slots[p1].second -= val;
-	if(!S1->slots[p1].second) //if we've moved all creatures
-		S1->slots.erase(p1);
-
-
-	if(s1->tempOwner<PLAYER_LIMIT)
-	{
-		for(int b=0; b<CGI->playerint.size(); ++b)
-		{
-			if(CGI->playerint[b]->playerID == s1->tempOwner)
-			{
-				CGI->playerint[b]->garrisonChanged(s1);
-				break;
-			}
-		}
-	}
-	if((s2->tempOwner<PLAYER_LIMIT) && (s2 != s1))
-	{
-		for(int b=0; b<CGI->playerint.size(); ++b)
-		{
-			if(CGI->playerint[b]->playerID == s2->tempOwner)
-			{
-				CGI->playerint[b]->garrisonChanged(s2);
-				break;
-			}
-		}
-	}
+	*cl->serv << ui16(502) << ui8(3) << s1->id << ui8(p1) << s2->id << ui8(p2) << si32(val);
 	return 0;
 }
 
 bool CCallback::dismissHero(const CGHeroInstance *hero)
 {
-	CGHeroInstance * Vhero = const_cast<CGHeroInstance *>(hero);
-	CGI->mh->removeObject(Vhero);
-	std::vector<CGHeroInstance*>::iterator nitr = find(CGI->state->players[player].heroes.begin(), CGI->state->players[player].heroes.end(), Vhero);
-	CGI->state->players[player].heroes.erase(nitr);
-	LOCPLINT->adventureInt->heroList.updateHList();
-	return false;
+	if(player!=hero->tempOwner) return false;
+	*cl->serv << ui16(500) << hero->id;
+	return true;
 }
 
 int CCallback::getMySerial()
-{
+{	
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
 	return gs->players[player].serial;
 }
 
@@ -732,391 +482,116 @@ bool CCallback::swapArifacts(const CGHeroInstance * hero1, bool worn1, int pos1,
 	{
 		std::swap(Uhero1->artifacts[pos1], Uhero2->artifacts[pos2]);
 	}
-
+	
 	return true;
 }
 
-bool CCallback::buildBuilding(const CGTownInstance *town, int buildingID)
+bool CCallback::buildBuilding(const CGTownInstance *town, si32 buildingID)
 {
 	CGTownInstance * t = const_cast<CGTownInstance *>(town);
-	CBuilding *b = CGI->buildh->buildings[t->subID][buildingID];
 
-	if(0/*not allowed*/)//TODO: check if we are allowed to build
+	if(town->tempOwner!=player)
 		return false;
-
-	if(buildingID>36) //upg dwelling
-	{
-		if(t->getHordeLevel(0) == (buildingID-37))
-			t->builtBuildings.insert(19);
-		else if(t->getHordeLevel(1) == (buildingID-37))
-			t->builtBuildings.insert(25);
-	}
-	else if(buildingID >= 30) //bas. dwelling
-	{
-		t->strInfo.creatures[buildingID-30] = CGI->creh->creatures[t->town->basicCreatures[buildingID-30]].growth;
-	}
-
-	t->builtBuildings.insert(buildingID);
+	CBuilding *b = CGI->buildh->buildings[t->subID][buildingID];
 	for(int i=0;i<7;i++)
-		gs->players[player].resources[i]-=b->resources[i];
-	t->builded++;
-	CGI->playerint[CGI->state->players[player].serial]->buildChanged(town,buildingID,1);
+		if(b->resources[i] > gs->players[player].resources[i])
+			return false; //lack of resources
+
+	*cl->serv << ui16(504) << town->id << buildingID;
+//TODO: check if we are allowed to build
 	return true;
 }
 
 int CCallback::battleGetBattlefieldType()
 {
-	return CGI->mh->ttiles[CGI->state->curB->tile.x][CGI->state->curB->tile.y][CGI->state->curB->tile.z].terType;
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
+	return CGI->mh->ttiles[gs->curB->tile.x][gs->curB->tile.y][gs->curB->tile.z].tileInfo->tertype;
 }
 
-int CCallback::battleGetObstaclesAtTile(int tile) //returns bitfield
+int CCallback::battleGetObstaclesAtTile(int tile) //returns bitfield 
 {
 	//TODO - write
 	return -1;
 }
 int CCallback::battleGetStack(int pos)
 {
-	return CGI->state->battleGetStack(pos);
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
+	return gs->battleGetStack(pos);
 }
 
-CStack CCallback::battleGetStackByID(int ID)
+CStack* CCallback::battleGetStackByID(int ID)
 {
-	for(int g=0; g<CGI->state->curB->stacks.size(); ++g)
-	{
-		if(CGI->state->curB->stacks[g]->ID == ID)
-			return *(CGI->state->curB->stacks[g]);
-	}
-	return CStack();
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
+	if(!gs->curB) return NULL;
+	return gs->curB->getStack(ID);
 }
 
-CStack CCallback::battleGetStackByPos(int pos)
+CStack* CCallback::battleGetStackByPos(int pos)
 {
 	return battleGetStackByID(battleGetStack(pos));
 }
 
 int CCallback::battleGetPos(int stack)
 {
-	for(int g=0; g<CGI->state->curB->stacks.size(); ++g)
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
+	for(int g=0; g<gs->curB->stacks.size(); ++g)
 	{
-		if(CGI->state->curB->stacks[g]->ID == stack)
-			return CGI->state->curB->stacks[g]->position;
+		if(gs->curB->stacks[g]->ID == stack)
+			return gs->curB->stacks[g]->position;
 	}
 	return -1;
 }
 
 std::map<int, CStack> CCallback::battleGetStacks()
 {
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
 	std::map<int, CStack> ret;
-	for(int g=0; g<CGI->state->curB->stacks.size(); ++g)
+	for(int g=0; g<gs->curB->stacks.size(); ++g)
 	{
-		ret[CGI->state->curB->stacks[g]->ID] = *(CGI->state->curB->stacks[g]);
+		ret[gs->curB->stacks[g]->ID] = *(gs->curB->stacks[g]);
 	}
 	return ret;
 }
 
 CCreature CCallback::battleGetCreature(int number)
 {
-	for(int h=0; h<CGI->state->curB->stacks.size(); ++h)
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
+	for(int h=0; h<gs->curB->stacks.size(); ++h)
 	{
-		if(CGI->state->curB->stacks[h]->ID == number) //creature found
-			return *(CGI->state->curB->stacks[h]->creature);
+		if(gs->curB->stacks[h]->ID == number) //creature found
+			return *(gs->curB->stacks[h]->creature);
 	}
 #ifndef __GNUC__
 	throw new std::exception("Cannot find the creature");
 #else
-	throw std::exception();
+	throw new std::exception();
 #endif
 }
 
 std::vector<int> CCallback::battleGetAvailableHexes(int ID)
 {
-	return CGI->state->battleGetRange(ID);
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
+	return gs->curB->getAccessibility(ID);
+	//return gs->battleGetRange(ID);
 }
 
 bool CCallback::battleIsStackMine(int ID)
 {
-	for(int h=0; h<CGI->state->curB->stacks.size(); ++h)
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
+	for(int h=0; h<gs->curB->stacks.size(); ++h)
 	{
-		if(CGI->state->curB->stacks[h]->ID == ID) //creature found
-			return CGI->state->curB->stacks[h]->owner == player;
+		if(gs->curB->stacks[h]->ID == ID) //creature found
+			return gs->curB->stacks[h]->owner == player;
 	}
 	return false;
 }
-
 bool CCallback::battleCanShoot(int ID, int dest) //TODO: finish
 {
-	if(battleGetStackByID(ID).creature->isShooting() 
+	boost::shared_lock<boost::shared_mutex> lock(*gs->mx);
+	if(battleGetStackByID(ID)->creature->isShooting() 
 		&& battleGetStack(dest) != -1 
-		&& battleGetStackByPos(dest).owner != battleGetStackByID(ID).owner
-		&& battleGetStackByPos(dest).alive)
+		&& battleGetStackByPos(dest)->owner != battleGetStackByID(ID)->owner
+		&& battleGetStackByPos(dest)->alive)
 		return true;
 	return false;
 }
-
-int3 CScriptCallback::getPos(CGObjectInstance * ob)
-{
-	return ob->pos;
-}
-void CScriptCallback::changePrimSkill(int ID, int which, int val)
-{
-	CGHeroInstance * hero = CGI->state->getHero(ID,0);
-	if (which<PRIMARY_SKILLS)
-	{
-		hero->primSkills[which]+=val;
-		for (int i=0; i<CGI->playerint.size(); i++)
-		{
-			if (CGI->playerint[i]->playerID == hero->getOwner())
-			{
-				CGI->playerint[i]->heroPrimarySkillChanged(hero, which, val);
-				break;
-			}
-		}
-	}
-	else if (which==4)
-	{
-		hero->exp+=val;
-		if(hero->exp >= CGI->heroh->reqExp(hero->level+1)) //new level
-		{
-			hero->level++;
-			std::cout << hero->name <<" got level "<<hero->level<<std::endl;
-			int r = rand()%100, pom=0, x=0;
-			int std::pair<int,int>::*g  =  (hero->level>9) ? (&std::pair<int,int>::second) : (&std::pair<int,int>::first);
-			for(;x<PRIMARY_SKILLS;x++)
-			{
-				pom += hero->type->heroClass->primChance[x].*g;
-				if(r<pom)
-					break;
-			}
-			std::cout << "Bohater dostaje umiejetnosc pierwszorzedna " << x << " (wynik losowania "<<r<<")"<<std::endl;
-			hero->primSkills[x]++;
-
-			//TODO: dac dwie umiejetnosci 2-rzedne to wyboru
-
-		}
-		//TODO - powiadomic interfejsy, sprawdzic czy nie ma awansu itp
-	}
-}
-
-int CScriptCallback::getHeroOwner(int heroID)
-{
-	CGHeroInstance * hero = CGI->state->getHero(heroID,0);
-	return hero->getOwner();
-}
-void CScriptCallback::showInfoDialog(int player, std::string text, std::vector<SComponent*> * components)
-{
-	//TODO: upewniac sie ze mozemy to zrzutowac (przy customowych interfejsach cos moze sie kopnac)
-	if (player>=0)
-	{
-		CGameInterface * temp = CGI->playerint[CGI->state->players[player].serial];
-		if (temp->human)
-			((CPlayerInterface*)(temp))->showInfoDialog(text,*components);
-		return;
-	}
-	else
-	{
-		for (int i=0; i<CGI->playerint.size();i++)
-		{
-			if (CGI->playerint[i]->human)
-				((CPlayerInterface*)(CGI->playerint[i]))->showInfoDialog(text,*components);
-		}
-	}
-}
-
-void CScriptCallback::showSelDialog(int player, std::string text, std::vector<CSelectableComponent*>*components, IChosen * asker)
-{
-	CGameInterface * temp = CGI->playerint[CGI->state->players[player].serial];
-	if (temp->human)
-		((CPlayerInterface*)(temp))->showSelDialog(text,*components,(int)asker);
-	return;
-}
-int CScriptCallback::getSelectedHero()
-{
-	int ret;
-	if (LOCPLINT->adventureInt->selection.type == HEROI_TYPE)
-		ret = ((CGHeroInstance*)(LOCPLINT->adventureInt->selection.selected))->subID;
-	else
-		ret = -1;;
-	return ret;
-}
-int CScriptCallback::getDate(int mode)
-{
-	int temp;
-	switch (mode)
-	{
-	case 0:
-		return gs->day;
-		break;
-	case 1:
-		temp = (gs->day)%7;
-		if (temp)
-			return temp;
-		else return 7;
-		break;
-	case 2:
-		temp = ((gs->day-1)/7)+1;
-		if (!(temp%4))
-			return 4;
-		else
-			return (temp%4);
-		break;
-	case 3:
-		return ((gs->day-1)/28)+1;
-		break;
-	}
-	return 0;
-}
-void CScriptCallback::giveResource(int player, int which, int val)
-{
-	gs->players[player].resources[which]+=val;
-	CGI->playerint[gs->players[player].serial]->receivedResource(which,val);
-}
-void CScriptCallback::showCompInfo(int player, SComponent * comp)
-{
-	CPlayerInterface * i = dynamic_cast<CPlayerInterface*>(CGI->playerint[gs->players[player].serial]);
-	if(i)
-		i->showComp(*comp);
-}
-void CScriptCallback::heroVisitCastle(CGObjectInstance * ob, int heroID)
-{
-	CGTownInstance * n;
-	if(n = dynamic_cast<CGTownInstance*>(ob))
-	{
-		n->visitingHero = CGI->state->getHero(heroID,0);
-		CGI->state->getHero(heroID,0)->visitedTown = n;
-		for(int b=0; b<CGI->playerint.size(); ++b)
-		{
-			if(CGI->playerint[b]->playerID == getHeroOwner(heroID))
-			{
-				CGI->playerint[b]->heroVisitsTown(CGI->state->getHero(heroID,0),n);
-				break;
-			}
-		}
-	}
-	else
-		return;
-}
-
-void CScriptCallback::stopHeroVisitCastle(CGObjectInstance * ob, int heroID)
-{
-	CGTownInstance * n;
-	if(n = dynamic_cast<CGTownInstance*>(ob))
-	{
-		CGI->state->getHero(heroID,0)->visitedTown = NULL;
-		if(n->visitingHero && n->visitingHero->type->ID == heroID)
-			n->visitingHero = NULL;
-		return;
-	}
-	else
-		return;
-}
-void CScriptCallback::giveHeroArtifact(int artid, int hid, int position) //pos==-1 - first free slot in backpack
-{
-	CGHeroInstance* h = gs->getHero(hid,0);
-	if(position<0)
-	{
-		for(int i=0;i<h->artifacts.size();i++)
-		{
-			if(!h->artifacts[i])
-			{
-				h->artifacts[i] = &CGI->arth->artifacts[artid];
-				return;
-			}
-		}
-		h->artifacts.push_back(&CGI->arth->artifacts[artid]);
-		return;
-	}
-	else
-	{
-		if(h->artifWorn[position]) //slot is occupied
-		{
-			giveHeroArtifact(h->artifWorn[position]->id,hid,-1);
-		}
-		h->artifWorn[position] = &CGI->arth->artifacts[artid];
-	}
-}
-
-void CScriptCallback::startBattle(CCreatureSet * army1, CCreatureSet * army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2) //use hero=NULL for no hero
-{
-	gs->battle(army1,army2,tile,hero1,hero2);
-}
-void CScriptCallback::startBattle(int heroID, CCreatureSet * army, int3 tile) //for hero<=>neutral army
-{
-	CGHeroInstance* h = gs->getHero(heroID,0);
-	gs->battle(&h->army,army,tile,h,NULL);
-}
-void CLuaCallback::registerFuncs(lua_State * L)
-{
-	lua_newtable(L);
-
-#define REGISTER_C_FUNC(x) \
-	lua_pushstring(L, #x);      \
-	lua_pushcfunction(L, x);    \
-	lua_rawset(L, -3)
-
-	REGISTER_C_FUNC(getPos);
-	REGISTER_C_FUNC(changePrimSkill);
-	REGISTER_C_FUNC(getGnrlText);
-	REGISTER_C_FUNC(getSelectedHero);
-
-	/*
-	REGISTER_C_FUNC(changePrimSkill);
-	REGISTER_C_FUNC(getGnrlText);
-	REGISTER_C_FUNC(changePrimSkill);
-	REGISTER_C_FUNC(getGnrlText);
-	REGISTER_C_FUNC(changePrimSkill);
-	REGISTER_C_FUNC(getGnrlText);*/
-
-
-	lua_setglobal(L, "vcmi");
-	#undef REGISTER_C_FUNC
-}
-int CLuaCallback::getPos(lua_State * L)//(CGObjectInstance * object);
-{
-	const int args = lua_gettop(L); // number of arguments
-	if ((args < 1) || !lua_isnumber(L, 1) )
-		luaL_error(L,
-			"Incorrect arguments to getPos([Object address])");
-	CGObjectInstance * object = (CGObjectInstance *)(lua_tointeger(L, 1));
-	lua_pushinteger(L,object->pos.x);
-	lua_pushinteger(L,object->pos.y);
-	lua_pushinteger(L,object->pos.z);
-	return 3;
-}
-int CLuaCallback::changePrimSkill(lua_State * L)//(int ID, int which, int val);
-{
-	const int args = lua_gettop(L); // number of arguments
-	if ((args < 1) || !lua_isnumber(L, 1) ||
-	    ((args >= 2) && !lua_isnumber(L, 2)) ||
-	    ((args >= 3) && !lua_isnumber(L, 3))		)
-	{
-		luaL_error(L,
-			"Incorrect arguments to changePrimSkill([Hero ID], [Which Primary skill], [Change by])");
-	}
-	int ID = lua_tointeger(L, 1),
-		which = lua_tointeger(L, 2),
-		val = lua_tointeger(L, 3);
-
-	CScriptCallback::changePrimSkill(ID,which,val);
-
-	return 0;
-}
-int CLuaCallback::getGnrlText(lua_State * L) //(int which),returns string
-{
-	const int args = lua_gettop(L); // number of arguments
-	if ((args < 1) || !lua_isnumber(L, 1) )
-		luaL_error(L,
-			"Incorrect arguments to getGnrlText([Text ID])");
-	int which = lua_tointeger(L,1);
-	lua_pushstring(L,CGI->generaltexth->allTexts[which].c_str());
-	return 1;
-}
-int CLuaCallback::getSelectedHero(lua_State * L) //(),returns int (ID of hero, -1 if no hero is seleceted)
-{
-	int ret;
-	if (LOCPLINT->adventureInt->selection.type == HEROI_TYPE)
-		ret = ((CGHeroInstance*)(LOCPLINT->adventureInt->selection.selected))->subID;
-	else
-		ret = -1;
-	lua_pushinteger(L,ret);
-	return 1;
-}

+ 25 - 54
CCallback.h

@@ -1,7 +1,7 @@
 #ifndef CCALLBACK_H
 #define CCALLBACK_H
 
-#include "mapHandler.h"
+#include "global.h"
 #ifdef _WIN32
 #include "tchar.h"
 #else
@@ -9,15 +9,20 @@
 #endif
 #include "CGameState.h"
 
+class CGHeroInstance;
 class CGameState;
 struct CPath;
 class CGObjectInstance;
+class CArmedInstance;
 class SComponent;
 class IChosen;
 class CSelectableComponent;
 struct BattleAction;
-typedef struct lua_State lua_State;
-
+class CGTownInstance;
+struct StartInfo;
+class CStack;
+struct lua_State;
+class CClient;
 //structure gathering info about upgrade possibilites
 struct UpgradeInfo
 {
@@ -40,11 +45,12 @@ public:
 	virtual void recruitCreatures(const CGObjectInstance *obj, int ID, int amount)=0;
 	virtual bool dismissCreature(const CArmedInstance *obj, int stackPos)=0;
 	virtual bool upgradeCreature(const CArmedInstance *obj, int stackPos, int newID=-1)=0; //if newID==-1 then best possible upgrade will be made
+	virtual void endTurn()=0;
 
 //get info
 	virtual bool verifyPath(CPath * path, bool blockSea)=0;
 	virtual int getDate(int mode=0)=0; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
-	virtual PseudoV< PseudoV< PseudoV<unsigned char> > > & getVisibilityMap()=0; //returns visibility map (TODO: make it const)
+	virtual std::vector< std::vector< std::vector<unsigned char> > > & getVisibilityMap()=0; //returns visibility map (TODO: make it const)
 	virtual const CGHeroInstance * getHeroInfo(int player, int val, bool mode)=0; //mode = 0 -> val = serial; mode = 1 -> val = ID
 	virtual int getResourceAmount(int type)=0;
 	virtual int howManyHeroes()=0;
@@ -58,13 +64,14 @@ public:
 	virtual int getHeroSerial(const CGHeroInstance * hero)=0;
 	virtual const CCreatureSet* getGarrison(const CGObjectInstance *obj)=0;
 	virtual UpgradeInfo getUpgradeInfo(const CArmedInstance *obj, int stackPos)=0;
+	virtual const StartInfo * getStartInfo()=0;
 
 //battle
 	virtual int battleGetBattlefieldType()=0; //   1. sand/shore   2. sand/mesas   3. dirt/birches   4. dirt/hills   5. dirt/pines   6. grass/hills   7. grass/pines   8. lava   9. magic plains   10. snow/mountains   11. snow/trees   12. subterranean   13. swamp/trees   14. fiery fields   15. rock lands   16. magic clouds   17. lucid pools   18. holy ground   19. clover field   20. evil fog   21. "favourable winds" text on magic plains background   22. cursed ground   23. rough   24. ship to ship   25. ship
 	virtual int battleGetObstaclesAtTile(int tile)=0; //returns bitfield
 	virtual int battleGetStack(int pos)=0; //returns ID of stack on the tile
-	virtual CStack battleGetStackByID(int ID)=0; //returns stack info by given ID
-	virtual CStack battleGetStackByPos(int pos)=0; //returns stack info by given pos
+	virtual CStack * battleGetStackByID(int ID)=0; //returns stack info by given ID
+	virtual CStack * battleGetStackByPos(int pos)=0; //returns stack info by given pos
 	virtual int battleGetPos(int stack)=0; //returns position (tile ID) of stack
 	//virtual int battleMakeAction(BattleAction* action)=0;//perform action with an active stack (or custom action)
 	virtual std::map<int, CStack> battleGetStacks()=0; //returns stacks on battlefield
@@ -77,6 +84,8 @@ public:
 
 struct HeroMoveDetails
 {
+	HeroMoveDetails(){};
+	HeroMoveDetails(int3 Src, int3 Dst, CGHeroInstance*Ho);
 	int3 src, dst; //source and destination points
 	CGHeroInstance * ho; //object instance of this hero
 	int owner;
@@ -86,11 +95,9 @@ struct HeroMoveDetails
 class CCallback : public ICallback
 {
 private:
-	void newTurn();
-	CCallback(CGameState * GS, int Player):gs(GS),player(Player){};
+	CCallback(CGameState * GS, int Player, CClient *C):gs(GS),player(Player),cl(C){};
 	CGameState * gs;
-	int lowestSpeed(CGHeroInstance * chi); //speed of the slowest stack
-	int valMovePoints(CGHeroInstance * chi);
+	CClient *cl;
 	bool isVisible(int3 pos, int Player);
 
 protected:
@@ -106,19 +113,19 @@ public:
 	int splitStack(const CGObjectInstance *s1, const CGObjectInstance *s2, int p1, int p2, int val);
 	bool dismissHero(const CGHeroInstance * hero);
 	bool swapArifacts(const CGHeroInstance * hero1, bool worn1, int pos1, const CGHeroInstance * hero2, bool worn2, int pos2);
-	bool buildBuilding(const CGTownInstance *town, int buildingID);
+	bool buildBuilding(const CGTownInstance *town, si32 buildingID);
 	void recruitCreatures(const CGObjectInstance *obj, int ID, int amount);
 	bool dismissCreature(const CArmedInstance *obj, int stackPos);
 	bool upgradeCreature(const CArmedInstance *obj, int stackPos, int newID=-1);
-
+	void endTurn();
 
 //get info
 	bool verifyPath(CPath * path, bool blockSea);
 	int getDate(int mode=0); //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
-	PseudoV< PseudoV< PseudoV<unsigned char> > > & getVisibilityMap(); //returns visibility map (TODO: make it const)
+	std::vector< std::vector< std::vector<unsigned char> > > & getVisibilityMap(); //returns visibility map (TODO: make it const)
 	const CGHeroInstance * getHeroInfo(int player, int val, bool mode); //mode = 0 -> val = serial; mode = 1 -> val = ID
 	int getResourceAmount(int type);
-	std::vector<int> getResourceAmount();
+	std::vector<si32> getResourceAmount();
 	int howManyHeroes();
 	const CGTownInstance * getTownInfo(int val, bool mode); //mode = 0 -> val = serial; mode = 1 -> val = ID
 	std::vector < const CGTownInstance *> getTownsInfo(bool onlyOur=true);
@@ -131,13 +138,14 @@ public:
 	int getMySerial();
 	const CCreatureSet* getGarrison(const CGObjectInstance *obj);
 	UpgradeInfo getUpgradeInfo(const CArmedInstance *obj, int stackPos);
+	virtual const StartInfo * getStartInfo();
 
 	//battle
 	int battleGetBattlefieldType(); //   1. sand/shore   2. sand/mesas   3. dirt/birches   4. dirt/hills   5. dirt/pines   6. grass/hills   7. grass/pines   8. lava   9. magic plains   10. snow/mountains   11. snow/trees   12. subterranean   13. swamp/trees   14. fiery fields   15. rock lands   16. magic clouds   17. lucid pools   18. holy ground   19. clover field   20. evil fog   21. "favourable winds" text on magic plains background   22. cursed ground   23. rough   24. ship to ship   25. ship
 	int battleGetObstaclesAtTile(int tile); //returns bitfield
 	int battleGetStack(int pos); //returns ID of stack on the tile
-	CStack battleGetStackByID(int ID); //returns stack info by given ID
-	CStack battleGetStackByPos(int pos); //returns stack info by given pos
+	CStack * battleGetStackByID(int ID); //returns stack info by given ID
+	CStack * battleGetStackByPos(int pos); //returns stack info by given pos
 	int battleGetPos(int stack); //returns position (tile ID) of stack
 	//int battleMakeAction(BattleAction* action);//perform action with an active stack (or custom action)
 	std::map<int, CStack> battleGetStacks(); //returns stacks on battlefield
@@ -150,48 +158,11 @@ public:
 
 
 //friends
+	friend class CClient;
 #ifndef __GNUC__
 	friend int _tmain(int argc, _TCHAR* argv[]);
 #else
 	friend int main(int argc, _TCHAR* argv[]);
 #endif
 };
-class CScriptCallback
-{
-public:
-	CGameState * gs;
-
-	//get info
-	static int3 getPos(CGObjectInstance * ob);
-	int getHeroOwner(int heroID);
-	int getSelectedHero();
-	int getDate(int mode=0);
-
-	//do sth
-	static void changePrimSkill(int ID, int which, int val);
-	void showInfoDialog(int player, std::string text, std::vector<SComponent*> * components); //TODO: obslugiwac nulle
-	void showSelDialog(int player, std::string text, std::vector<CSelectableComponent*>*components, IChosen * asker);
-	void giveResource(int player, int which, int val);
-	void showCompInfo(int player, SComponent * comp);
-	void heroVisitCastle(CGObjectInstance * ob, int heroID);
-	void stopHeroVisitCastle(CGObjectInstance * ob, int heroID);
-	void giveHeroArtifact(int artid, int hid, int position); //pos==-1 - first free slot in backpack
-	void startBattle(CCreatureSet * army1, CCreatureSet * army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2); //use hero=NULL for no hero
-	void startBattle(int heroID, CCreatureSet * army, int3 tile); //for hero<=>neutral army
-
-	//friends
-	friend void initGameState(CGameInfo * cgi);
-};
-class CLuaCallback : public CScriptCallback
-{
-private:
-
-	static void registerFuncs(lua_State * L);
-	static int getPos(lua_State * L);//(CGObjectInstance * object);
-	static int changePrimSkill(lua_State * L);//(int ID, int which, int val);
-	static int getGnrlText(lua_State * L);//(int ID, int which, int val);
-	static int getSelectedHero(lua_State * L);//()
-
-	friend void initGameState(CGameInfo * cgi);
-};
 #endif //CCALLBACK_H

+ 30 - 26
CCastleInterface.cpp

@@ -8,15 +8,17 @@
 #include "hch/CTownHandler.h"
 #include "AdventureMapButton.h"
 #include "hch/CBuildingHandler.h"
+#include "hch/CDefHandler.h"
 #include <sstream>
 #include "CMessage.h"
 #include "hch/CGeneralTextHandler.h"
 #include "CCallback.h"
+#include "client/Graphics.h"
 extern TTF_Font * GEOR16;
 CBuildingRect::CBuildingRect(Structure *Str)
 :str(Str), moi(false), offset(0)
 {
-	def = CGI->spriteh->giveDef(Str->defName);
+	def = CDefHandler::giveDef(Str->defName);
 	max = def->ourImages.size();
 
 	if(str->ID == 33    &&    str->townID == 4) //little 'hack' for estate in necropolis - background color is not always the first color in the palette
@@ -36,11 +38,11 @@ CBuildingRect::CBuildingRect(Structure *Str)
 		area = border = NULL;
 		return;
 	}
-	if (border = CGI->bitmaph->loadBitmap(str->borderName))
+	if (border = BitmapHandler::loadBitmap(str->borderName))
 		SDL_SetColorKey(border,SDL_SRCCOLORKEY,SDL_MapRGB(border->format,0,255,255));
 	else
 		std::cout << "Warning: no border for "<<Str->ID<<std::endl;
-	if (area = CGI->bitmaph->loadBitmap(str->areaName))
+	if (area = BitmapHandler::loadBitmap(str->areaName))
 		;//SDL_SetColorKey(area,SDL_SRCCOLORKEY,SDL_MapRGB(area->format,0,255,255));
 	else
 		std::cout << "Warning: no area for "<<Str->ID<<std::endl;
@@ -213,11 +215,11 @@ public:
 CCastleInterface::CCastleInterface(const CGTownInstance * Town, bool Activate)
 {
 	hall = NULL;
-	townInt = CGI->bitmaph->loadBitmap("TOWNSCRN.bmp");
-	cityBg = CGI->bitmaph->loadBitmap(getBgName(Town->subID));
-	hall = CGI->spriteh->giveDef("ITMTL.DEF");
-	fort = CGI->spriteh->giveDef("ITMCL.DEF");
-	flag =  CGI->spriteh->giveDef("CREST58.DEF");
+	townInt = BitmapHandler::loadBitmap("TOWNSCRN.bmp");
+	cityBg = BitmapHandler::loadBitmap(getBgName(Town->subID));
+	hall = CDefHandler::giveDef("ITMTL.DEF");
+	fort = CDefHandler::giveDef("ITMCL.DEF");
+	flag =  CDefHandler::giveDef("CREST58.DEF");
 	hBuild = NULL;
 	count=0;
 	town = Town;
@@ -238,7 +240,7 @@ CCastleInterface::CCastleInterface(const CGTownInstance * Town, bool Activate)
 	if((townlist->selected+1) > townlist->SIZE)
 		townlist->from = townlist->selected -  townlist->SIZE + 2;
 
-	CSDL_Ext::blueToPlayersAdv(townInt,LOCPLINT->playerID);
+	graphics->blueToPlayersAdv(townInt,LOCPLINT->playerID);
 	exit->bitmapOffset = 4;
 
 
@@ -291,7 +293,7 @@ CCastleInterface::CCastleInterface(const CGTownInstance * Town, bool Activate)
 		throw new std::exception();
 #endif
 	}
-	bicons = CGI->spriteh->giveDefEss(defname);
+	bicons = CDefHandler::giveDefEss(defname);
 	//blit buildings on bg
 	//for(int i=0;i<buildings.size();i++)
 	//{
@@ -422,7 +424,7 @@ void CCastleInterface::showAll(SDL_Surface * to)
 			int pomx, pomy;
 			pomx = 22 + (55*((i>3)?(i-4):i));
 			pomy = (i>3)?(507):(459);
-			blitAt(CGI->creh->smallImgs[cid],pomx,pomy,to);
+			blitAt(graphics->smallImgs[cid],pomx,pomy,to);
 			std::ostringstream oss;
 			oss << '+' << town->creatureGrowth(i);
 			CSDL_Ext::printAtMiddle(oss.str(),pomx+16,pomy+37,GEOR13,zwykly,to);
@@ -441,7 +443,7 @@ void CCastleInterface::showAll(SDL_Surface * to)
 		pom += F_NUMBER*2;
 	if(town->builded >= MAX_BUILDING_PER_TURN)
 		pom++;
-	blitAt(LOCPLINT->bigTownPic->ourImages[pom].bitmap,15,387,to);
+	blitAt(graphics->bigTownPic->ourImages[pom].bitmap,15,387,to);
 
 	//flag
 	if(town->getOwner()<PLAYER_LIMIT)
@@ -516,7 +518,9 @@ void CCastleInterface::deactivate()
 void CCastleInterface::addBuilding(int bid)
 {
 	//TODO: lepiej by bylo tylko dodawac co trzeba pamietajac o grupach
+	deactivate();
 	recreateBuildings();
+	activate();
 }
 
 void CCastleInterface::removeBuilding(int bid)
@@ -539,7 +543,7 @@ void CCastleInterface::recreateBuildings()
 	std::set< std::pair<int,int> > s; //group - id
 
 
-	for (std::set<int>::const_iterator i=town->builtBuildings.begin();i!=town->builtBuildings.end();i++)
+	for (std::set<si32>::const_iterator i=town->builtBuildings.begin();i!=town->builtBuildings.end();i++)
 	{
 		if(CGI->townh->structures.find(town->subID) != CGI->townh->structures.end()) //we have info about structures in this town
 		{
@@ -669,9 +673,9 @@ void CHallInterface::CResDataBar::show(SDL_Surface * to)
 }
 CHallInterface::CResDataBar::CResDataBar()
 {
-	bg = CGI->bitmaph->loadBitmap("Z2ESBAR.bmp");
+	bg = BitmapHandler::loadBitmap("Z2ESBAR.bmp");
 	SDL_SetColorKey(bg,SDL_SRCCOLORKEY,SDL_MapRGB(bg->format,0,255,255));
-	CSDL_Ext::blueToPlayersAdv(bg,LOCPLINT->playerID);
+	graphics->blueToPlayersAdv(bg,LOCPLINT->playerID);
 	pos.x = 7;
 	pos.y = 575;
 	pos.w = bg->w;
@@ -780,10 +784,10 @@ CHallInterface::CBuildingBox::CBuildingBox(int id, int x, int y)
 
 CHallInterface::CHallInterface(CCastleInterface * owner)
 {
-	bg = CGI->bitmaph->loadBitmap(CGI->buildh->hall[owner->town->subID].first);
-	CSDL_Ext::blueToPlayersAdv(bg,LOCPLINT->playerID);
-	bars = CGI->spriteh->giveDefEss("TPTHBAR.DEF");
-	status = CGI->spriteh->giveDefEss("TPTHCHK.DEF");
+	bg = BitmapHandler::loadBitmap(CGI->buildh->hall[owner->town->subID].first);
+	graphics->blueToPlayersAdv(bg,LOCPLINT->playerID);
+	bars = CDefHandler::giveDefEss("TPTHBAR.DEF");
+	status = CDefHandler::giveDefEss("TPTHCHK.DEF");
 	exit = new AdventureMapButton
 		(CGI->townh->tcommands[8],"",boost::bind(&CHallInterface::close,this),748,556,"TPMAGE1.DEF",false,NULL,false);
 
@@ -926,12 +930,12 @@ void CHallInterface::CBuildWindow::deactivate()
 }
 void CHallInterface::CBuildWindow::Buy()
 {
-	LOCPLINT->cb->buildBuilding(LOCPLINT->castleInt->town,bid);
 	deactivate();
-	delete this;
-	delete LOCPLINT->castleInt->hallInt;
 	LOCPLINT->castleInt->hallInt = NULL;
 	LOCPLINT->castleInt->activate();
+	LOCPLINT->cb->buildBuilding(LOCPLINT->castleInt->town,bid);
+	delete this;
+	delete LOCPLINT->castleInt->hallInt;
 	LOCPLINT->castleInt->showAll();
 }
 void CHallInterface::CBuildWindow::close()
@@ -1019,13 +1023,13 @@ std::string CHallInterface::CBuildWindow::getTextForState(int state)
 CHallInterface::CBuildWindow::CBuildWindow(int Tid, int Bid, int State, bool Mode)
 :tid(Tid),bid(Bid),mode(Mode), state(State)
 {
-	SDL_Surface *hhlp = CGI->bitmaph->loadBitmap("TPUBUILD.bmp");
+	SDL_Surface *hhlp = BitmapHandler::loadBitmap("TPUBUILD.bmp");
+	graphics->blueToPlayersAdv(hhlp,LOCPLINT->playerID);
 	bitmap = SDL_ConvertSurface(hhlp,screen->format,0); //na 8bitowej mapie by sie psulo
 	SDL_SetColorKey(hhlp,SDL_SRCCOLORKEY,SDL_MapRGB(hhlp->format,0,255,255));
 	SDL_FreeSurface(hhlp);
 	pos.x = screen->w/2 - bitmap->w/2;
 	pos.y = screen->h/2 - bitmap->h/2;
-	CSDL_Ext::blueToPlayersAdv(bitmap,LOCPLINT->playerID);
 	blitAt(LOCPLINT->castleInt->bicons->ourImages[bid].bitmap,125,50,bitmap);
 	std::vector<std::string> pom; pom.push_back(CGI->buildh->buildings[tid][bid]->name);
 	CSDL_Ext::printAtMiddleWB(CGI->buildh->buildings[tid][bid]->description,197,168,GEOR16,40,zwykly,bitmap);
@@ -1045,12 +1049,12 @@ CHallInterface::CBuildWindow::CBuildWindow(int Tid, int Bid, int State, bool Mod
 		if(it<4)
 		{
 			CSDL_Ext::printAtMiddle(buf,(bitmap->w/2-row1w/2)+77*it+16,ah+42,GEOR16,zwykly,bitmap);
-			blitAt(CGI->townh->resources->ourImages[cn].bitmap,(bitmap->w/2-row1w/2)+77*it++,ah,bitmap);
+			blitAt(graphics->resources32->ourImages[cn].bitmap,(bitmap->w/2-row1w/2)+77*it++,ah,bitmap);
 		}
 		else
 		{
 			CSDL_Ext::printAtMiddle(buf,(bitmap->w/2-row2w/2)+77*it+16-308,ah+42,GEOR16,zwykly,bitmap);
-			blitAt(CGI->townh->resources->ourImages[cn].bitmap,(bitmap->w/2-row2w/2)+77*it++ - 308,ah,bitmap);
+			blitAt(graphics->resources32->ourImages[cn].bitmap,(bitmap->w/2-row2w/2)+77*it++ - 308,ah,bitmap);
 		}
 		if(it==4)
 			ah+=75;

+ 66 - 73
CConsoleHandler.cpp

@@ -53,7 +53,7 @@ int internalFunc(void * callback)
 				boost::filesystem::create_directory("Extracted_txts");
 				std::cout<<"Command accepted. Opening .lod file...\t";
 				CLodHandler * txth = new CLodHandler;
-				txth->init(std::string(DATADIR "Data" PATHSEPARATOR "H3bitmap.lod"));
+				txth->init(std::string(DATA_DIR "Data" PATHSEPARATOR "H3bitmap.lod"),"data");
 				std::cout<<"done.\nScanning .lod file\n";
 				int curp=0;
 				std::string pattern = ".TXT";
@@ -79,80 +79,73 @@ int internalFunc(void * callback)
 			int heroZ;
 			switch (*cn.c_str())
 			{
-			case 'P':
-				std::cout<<"Policzyc sciezke."<<std::endl;
-				readed>>src>>dst;
-
-				p = CGI->pathf->GetPath(Coordinate(src),Coordinate(dst),CGI->heroh->heroInstances[0]);
-				LOCPLINT->adventureInt->terrain.currentPath = CGI->pathf->ConvertToOldFormat(p);
-				//LOCPLINT->adventureInt->terrain.currentPath = CGI->pathf->getPath(src,dst,CGI->heroh->heroInstances[0]);
-				break;
-			case 'm': //number of heroes
-				std::cout<<"Number of heroes: "<<CGI->heroh->heroInstances.size()<<std::endl;
-				break;
-			case 'H': //position of hero
-				readed>>heronum;
-				#ifndef __GNUC__
-				std::cout<<"Position of hero "<<heronum<<": "<<CGI->heroh->heroInstances[heronum]->getPosition(false)<<std::endl;
-				#else
-				heroX = CGI->heroh->heroInstances[heronum]->getPosition(false).x;
-				heroY = CGI->heroh->heroInstances[heronum]->getPosition(false).y;
-				heroZ = CGI->heroh->heroInstances[heronum]->getPosition(false).z;
-				std::cout<<"Position of hero "<<heronum<<": x:"<<heroX<<"- y:"<<heroY<<"- z:"<<heroZ<<std::endl;
-				#endif
-				break;
-			case 'M': //move heroa
-				{
-					readed>>heronum>>dest;
-					const CGHeroInstance * hero = cb->getHeroInfo(0,heronum,0);
-					p = CGI->pathf->GetPath(Coordinate(hero->getPosition(false)),Coordinate(dest),hero);
-					cb->moveHero(heronum, CGI->pathf->ConvertToOldFormat(p), 0, 0);
-					//LOCPLINT->adventureInt->terrain.currentPath = CGI->pathf->getPath(src,dst,CGI->heroh->heroInstances[0]);
-					break;
-				}
-			case 'D': //pos description
-				readed>>src;
-				CGI->mh->getObjDescriptions(src);
-				break;
-			case 'I':
-				{
-					SDL_Surface * temp = LOCPLINT->infoWin(NULL);
-					blitAtWR(temp,605,389);
-					SDL_FreeSurface(temp);
-					break;
-				}
-			case 'T': //test rect
-				readed>>src;
-				for(int g=0; g<8; ++g)
-				{
-					for(int v=0; v<8; ++v)
-					{
-						int3 csrc = src;
-						csrc.y+=g;
-						csrc.x+=v;
-						if(CGI->mh->getObjDescriptions(csrc).size())
-							std::cout<<'x';
-						else
-							std::cout<<'o';
-					}
-					std::cout<<std::endl;
-				}
-				break;
-			case 'A':  //hide everything from map
-				for(int c=0; c<CGI->objh->objInstances.size(); ++c)
-				{
-					CGI->mh->hideObject(CGI->objh->objInstances[c]);
-				}
-				break;
-			case 'R': //restora all objects after A has been pressed
-				for(int c=0; c<CGI->objh->objInstances.size(); ++c)
-				{
-					CGI->mh->printObject(CGI->objh->objInstances[c]);
-				}
-				break;
+			//case 'P':
+			//	std::cout<<"Policzyc sciezke."<<std::endl;		
+			//	readed>>src>>dst;
+			//	
+			//	p = CGI->pathf->GetPath(Coordinate(src),Coordinate(dst),CGI->heroh->heroInstances[0]);
+			//	LOCPLINT->adventureInt->terrain.currentPath = CGI->pathf->ConvertToOldFormat(p);
+			//	//LOCPLINT->adventureInt->terrain.currentPath = CGI->pathf->getPath(src,dst,CGI->heroh->heroInstances[0]);
+			//	break;
+			//case 'm': //number of heroes
+			//	std::cout<<"Number of heroes: "<<CGI->heroh->heroInstances.size()<<std::endl;
+			//	break;
+			//case 'H': //position of hero
+			//	readed>>heronum;
+			//	std::cout<<"Position of hero "<<heronum<<": "<<CGI->heroh->heroInstances[heronum]->getPosition(false)<<std::endl;
+			//	break;
+			//case 'M': //move heroa
+			//	{
+			//		readed>>heronum>>dest;
+			//		const CGHeroInstance * hero = cb->getHeroInfo(0,heronum,0);
+			//		p = CGI->pathf->GetPath(Coordinate(hero->getPosition(false)),Coordinate(dest),hero);
+			//		cb->moveHero(heronum, CGI->pathf->ConvertToOldFormat(p), 0, 0);
+			//		//LOCPLINT->adventureInt->terrain.currentPath = CGI->pathf->getPath(src,dst,CGI->heroh->heroInstances[0]);
+			//		break;
+			//	}
+			//case 'D': //pos description
+			//	readed>>src;
+			//	CGI->mh->getObjDescriptions(src);
+			//	break;
+			//case 'I': 
+			//	{
+			//		SDL_Surface * temp = LOCPLINT->infoWin(NULL);
+			//		blitAtWR(temp,605,389);
+			//		SDL_FreeSurface(temp);
+			//		break;
+			//	}
+			//case 'T': //test rect
+			//	readed>>src;
+			//	for(int g=0; g<8; ++g)
+			//	{
+			//		for(int v=0; v<8; ++v)
+			//		{
+			//			int3 csrc = src;
+			//			csrc.y+=g;
+			//			csrc.x+=v;
+			//			if(CGI->mh->getObjDescriptions(csrc).size())
+			//				std::cout<<'x';
+			//			else
+			//				std::cout<<'o';
+			//		}
+			//		std::cout<<std::endl;
+			//	}
+			//	break;
+			//case 'A':  //hide everything from map
+			//	for(int c=0; c<CGI->objh->objInstances.size(); ++c)
+			//	{
+			//		CGI->mh->hideObject(CGI->objh->objInstances[c]);
+			//	}
+			//	break;
+			//case 'R': //restora all objects after A has been pressed
+			//	for(int c=0; c<CGI->objh->objInstances.size(); ++c)
+			//	{
+			//		CGI->mh->printObject(CGI->objh->objInstances[c]);
+			//	}
+			//	break;
 			}
 			//SDL_Delay(100);
-			delete p;
+			//delete p;
 		}
 		SDL_Delay(10);
 	}

+ 2 - 0
CConsoleHandler.h

@@ -7,6 +7,8 @@ class CConsoleHandler
 public:
 	void runConsole();
 
+	friend class CClient;
+
 #ifndef __GNUC__
 	friend int _tmain(int argc, _TCHAR* argv[]);
 #else

+ 18 - 215
CCursorHandler.cpp

@@ -1,237 +1,40 @@
 #include "stdafx.h"
 #include "CCursorHandler.h"
 #include "SDL.h"
-#include "SDL_thread.h"
+#include "SDL_Extensions.h"
 #include "CGameInfo.h"
-#include "SDL_framerate.h"
-#include "hch/CLodHandler.h"
+#include "hch/CDefHandler.h"
 
 extern SDL_Surface * screen;
 
-/* Creates a new mouse cursor from an XPM */
-
-
-/* XPM */
-static const char *arrow[] = { //no cursor mode
-  /* width height num_colors chars_per_pixel */
-  "    32    32        3            1",
-  /* colors */
-  "X c #000000",
-  ". c #ffffff",
-  "  c None",
-  /* pixels */
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "0,0"
-};
-
-/* XPM */
-static const char *arrow2[] = { //normal cursor
-  /* width height num_colors chars_per_pixel */
-  "    32    32        3            1",
-  /* colors */
-  "X c #000000",
-  ". c #ffffff",
-  "  c None",
-  /* pixels */
-  "X                               ",
-  "XX                              ",
-  "X.X                             ",
-  "X..X                            ",
-  "X...X                           ",
-  "X....X                          ",
-  "X.....X                         ",
-  "X......X                        ",
-  "X.......X                       ",
-  "X........X                      ",
-  "X.....XXXXX                     ",
-  "X..X..X                         ",
-  "X.X X..X                        ",
-  "XX  X..X                        ",
-  "X    X..X                       ",
-  "     X..X                       ",
-  "      X..X                      ",
-  "      X..X                      ",
-  "       XX                       ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "                                ",
-  "0,0"
-};
-
-static SDL_Cursor *init_system_cursor(const char *image[])
-{
-  int i, row, col;
-  Uint8 data[4*32];
-  Uint8 mask[4*32];
-  int hot_x, hot_y;
-
-  i = -1;
-  for ( row=0; row<32; ++row ) {
-    for ( col=0; col<32; ++col ) {
-      if ( col % 8 ) {
-        data[i] <<= 1;
-        mask[i] <<= 1;
-      } else {
-        ++i;
-        data[i] = mask[i] = 0;
-      }
-      switch (image[4+row][col]) {
-        case 'X':
-          data[i] |= 0x01;
-          //k[i] |= 0x01;
-          break;
-        case '.':
-          mask[i] |= 0x01;
-          break;
-        case ' ':
-          break;
-      }
-    }
-  }
-  sscanf(image[4+row], "%d,%d", &hot_x, &hot_y);
-  return SDL_CreateCursor(data, mask, 32, 32, hot_x, hot_y);
-}
-
-//int cursorHandlerFunc(void * cursorHandler)
-//{
-//	FPSmanager * cursorFramerateKeeper = new FPSmanager;
-//	SDL_initFramerate(cursorFramerateKeeper);
-//	SDL_setFramerate(cursorFramerateKeeper, 200);
-//
-//	CCursorHandler * ch = (CCursorHandler *) cursorHandler;
-//	while(true)
-//	{
-//		if(ch->xbef!=-1 && ch->ybef!=-1) //restore surface under cursor
-//		{
-//			blitAtWR(ch->behindCur, ch->xbef, ch->ybef);
-//		}
-//		ch->xbef = ch->xpos;
-//		ch->ybef = ch->ypos;
-//		//prepare part of surface to restore
-//		SDL_BlitSurface(screen, &genRect(32, 32, ch->xpos, ch->ypos), ch->behindCur, NULL);
-//		CSDL_Ext::update(ch->behindCur);
-//
-//		//blit cursor
-//		if(ch->curVisible)
-//		{
-//			switch(ch->mode)
-//			{
-//			case 0:
-//				{
-//					break;
-//				}
-//			case 1:
-//				{
-//					break;
-//				}
-//			case 2:
-//				{
-//					blitAtWR(ch->deflt->ourImages[ch->number].bitmap, ch->xpos, ch->ypos);
-//					break;
-//				}
-//			}
-//		}
-//		SDL_framerateDelay(cursorFramerateKeeper);
-//		//SDL_Delay(5); //to avoid great usage of CPU
-//	}
-//	return 0;
-//}
-
 void CCursorHandler::initCursor()
 {
-//#if SDL_BYTEORDER == SDL_BIG_ENDIAN
-//    int rmask = 0xff000000;
-//    int gmask = 0x00ff0000;
-//    int bmask = 0x0000ff00;
-//    int amask = 0x000000ff;
-//#else
-//    int rmask = 0x000000ff;
-//    int gmask = 0x0000ff00;
-//    int bmask = 0x00ff0000;
-//    int amask = 0xff000000;
-//#endif
-//	curVisible = true;
-//	xpos = ypos = 0;
-//	behindCur = SDL_CreateRGBSurface(SDL_SWSURFACE, 32, 32, 32, rmask, gmask, bmask, amask);
-//	xbef = ybef = 0;
-//	adventure = CGI->spriteh->giveDef("CRADVNTR.DEF");
-//	combat = CGI->spriteh->giveDef("CRCOMBAT.DEF");
-//	deflt = CGI->spriteh->giveDef("CRDEFLT.DEF");
-//	spell = CGI->spriteh->giveDef("CRSPELL.DEF");
-//	//SDL_SetCursor(init_system_cursor(arrow));
-//	//SDL_Thread * myth = SDL_CreateThread(&cursorHandlerFunc, this);
+	mode = number = xpos = ypos = 0;
+	help = CSDL_Ext::newSurface(32,32);
+	cursors.push_back(CDefHandler::giveDef("CRADVNTR.DEF"));
+	cursors.push_back(CDefHandler::giveDef("CRCOMBAT.DEF"));
+	cursors.push_back(CDefHandler::giveDef("CRDEFLT.DEF"));
+	cursors.push_back(CDefHandler::giveDef("CRSPELL.DEF"));
+	SDL_ShowCursor(SDL_DISABLE);
 }
 
 void CCursorHandler::changeGraphic(int type, int no)
 {
-	//mode = type;
-	//number = no;
+	mode = type;
+	number = no;
 }
 
 void CCursorHandler::cursorMove(int x, int y)
 {
-	//xbef = xpos;
-	//ybef = ypos;
-	//xpos = x;
-	//ypos = y;
+	xpos = x;
+	ypos = y;
 }
-
-void CCursorHandler::hardwareCursor()
+void CCursorHandler::draw1()
 {
-	//curVisible = false;
-	//SDL_SetCursor(init_system_cursor(arrow2));
+	SDL_BlitSurface(screen,&genRect(32,32,xpos,ypos),help,&genRect(32,32,0,0));
+	blitAt(cursors[mode]->ourImages[number].bitmap,xpos,ypos);
 }
-
-void CCursorHandler::hideCursor()
+void CCursorHandler::draw2()
 {
-	//curVisible = false;
-	//SDL_SetCursor(init_system_cursor(arrow));
+	blitAt(help,xpos,ypos);
 }
-
-void CCursorHandler::showGraphicCursor()
-{
-	//curVisible = true;
-	//SDL_SetCursor(init_system_cursor(arrow));
-	//changeGraphic(0, 0);
-}

+ 7 - 11
CCursorHandler.h

@@ -1,6 +1,7 @@
 #ifndef CCURSORHANDLER_H
 #define CCURSORHANDLER_H
-
+#include "global.h"
+#include <vector>
 struct SDL_Thread;
 class CDefHandler;
 struct SDL_Surface;
@@ -8,21 +9,16 @@ struct SDL_Surface;
 class CCursorHandler //handles cursor
 {
 public:
-	SDL_Thread * myThread; //thread that updates cursor
-	bool curVisible; //true if cursor is visible
 	int mode, number;
-	SDL_Surface * behindCur;
-	int xbef, ybef; //position of cursor after last move (to restore background)
+	SDL_Surface * help;
 
-	CDefHandler * adventure, * combat, * deflt, * spell; //read - only
-	int xpos, ypos; //position of cursor - read only
+	std::vector<CDefHandler*> cursors;
+	int xpos, ypos; //position of cursor
 	void initCursor(); //inits cursorHandler
-	void showGraphicCursor(); //shows default graphic cursor
 	void cursorMove(int x, int y); //change cursor's positions to (x, y)
 	void changeGraphic(int type, int no); //changes cursor graphic for type type (0 - adventure, 1 - combat, 2 - default, 3 - spellbook) and frame no (not used for type 3)
-	void hideCursor(); //no cursor will be visible
-	void hardwareCursor(); // returns to hardware cursor mode
-	friend int cursorHandlerFunc(void * cursorHandler);
+	void draw1();
+	void draw2();
 };
 
 

+ 1 - 1
CGameInfo.cpp

@@ -1,4 +1,4 @@
 #include "stdafx.h"
 #include "CGameInfo.h"
 
-CGameInfo * CGameInfo::mainObj;
+CGameInfo * CGI;

+ 4 - 11
CGameInfo.h

@@ -1,9 +1,10 @@
 #ifndef CGAMEINFO_H
 #define CGAMEINFO_H
+#include "global.h"
+
+
+
 
-#include "StartInfo.h"
-#include "SDL.h"
-#include "CPreGame.h"
 
 #include <vector>
 
@@ -40,7 +41,6 @@ class CDefHandler;
 class CGameInfo
 {
 public:
-	static CGameInfo * mainObj; //pointer to main CGameInfo object
 	CGameState * state;
 	CArtHandler * arth;
 	CHeroHandler * heroh;
@@ -48,7 +48,6 @@ public:
 	CAbilityHandler * abilh;
 	CSpellHandler * spellh;
 	CMapHandler * mh;
-	CAmbarCendamo * ac;
 	CPreGameTextHandler * preth;
 	CBuildingHandler * buildh;
 	CObjectHandler * objh;
@@ -63,12 +62,6 @@ public:
 	CPathfinder * pathf;
 	CCursorHandler * curh;
 	CScreenHandler * screenh;
-	int localPlayer;
-	std::vector<CGameInterface *> playerint;
-	std::vector<SDL_Color> playerColors;
-	std::vector<CDefHandler *> playerColorInfo; //gems from adventure map interface
-	SDL_Color neutralColor;
-	StartInfo scenarioOps;
 };
 
 #endif //CGAMEINFO_H

+ 0 - 2
CGameInterface.cpp

@@ -5,7 +5,6 @@
 #include "mapHandler.h"
 #include "SDL_Extensions.h"
 #include "SDL_framerate.h"
-#include "CScreenHandler.h"
 #include "CCursorHandler.h"
 #include "CCallback.h"
 #include "SDL_Extensions.h"
@@ -25,7 +24,6 @@ using namespace CSDL_Ext;
 
 CGlobalAI * CAIHandler::getNewAI(CCallback * cb, std::string dllname)
 {
-	std::cout << "Opening "<<dllname/*<<" for player "<< cb->player*/<<std::endl;
 	dllname = "AI/"+dllname;
 	CGlobalAI * ret=NULL;
 	CGlobalAI*(*getAI)();

+ 7 - 12
CGameInterface.h

@@ -3,6 +3,7 @@
 #include "global.h"
 #include <set>
 #include <vector>
+#include "lib/BattleAction.h"
 BOOST_TRIBOOL_THIRD_STATE(outOfRange)
 
 using namespace boost::logic;
@@ -10,6 +11,7 @@ class CCallback;
 class ICallback;
 class CGlobalAI;
 class CGHeroInstance;
+class Component;
 class CSelectableComponent;
 struct HeroMoveDetails;
 class CGHeroInstance;
@@ -17,21 +19,13 @@ class CGTownInstance;
 class CGObjectInstance;
 class CCreatureSet;
 class CArmedInstance;
-
+struct BattleResult;
 class CObstacle
 {
 	int ID;
 	int position;
 	//TODO: add some kind of the blockmap
 };
-struct BattleAction
-{
-	bool side; //who made this action: false - left, true - right player
-	int stackNumber;//stack ID, -1 left hero, -2 right hero,
-	int actionType; //    0 = Cancel BattleAction   1 = Hero cast a spell   2 = Walk   3 = Defend   4 = Retreat from the battle   5 = Surrender   6 = Walk and Attack   7 = Shoot    8 = Wait   9 = Catapult 10 = Monster casts a spell (i.e. Faerie Dragons)
-	int destinationTile;
-	int additionalInfo; // e.g. spell number if type is 1 || 10
-};
 
 struct StackState
 {
@@ -59,17 +53,18 @@ public:
 	virtual void tileRevealed(int3 pos){};
 	virtual void tileHidden(int3 pos){};
 	virtual void receivedResource(int type, int val){};
-	virtual void showSelDialog(std::string text, std::vector<CSelectableComponent*> & components, int askID){};
+	virtual void showInfoDialog(std::string text, std::vector<Component*> &components){};
+	virtual void showSelDialog(std::string text, std::vector<CSelectableComponent*> & components, int askID)=0;
 	virtual void garrisonChanged(const CGObjectInstance * obj){};
 	virtual void buildChanged(const CGTownInstance *town, int buildingID, int what){}; //what: 1 - built, 2 - demolished
 	//battle call-ins
-	virtual void battleStart(CCreatureSet * army1, CCreatureSet * army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, bool side){}; //called by engine when battle starts; side=0 - left, side=1 - right
+	virtual void battleStart(CCreatureSet *army1, CCreatureSet *army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, bool side){}; //called by engine when battle starts; side=0 - left, side=1 - right
 	virtual void battlefieldPrepared(int battlefieldType, std::vector<CObstacle*> obstacles){}; //called when battlefield is prepared, prior the battle beginning
 	virtual void battleNewRound(int round){}; //called at the beggining of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
 	virtual void actionStarted(BattleAction action){};//occurs BEFORE every action taken by any stack or by the hero
 	virtual void actionFinished(BattleAction action){};//occurs AFTER every action taken by any stack or by the hero
 	virtual BattleAction activeStack(int stackID)=0; //called when it's turn of that stack
-	virtual void battleEnd(CCreatureSet * army1, CCreatureSet * army2, CArmedInstance *hero1, CArmedInstance *hero2, std::vector<int> capturedArtifacts, int expForWinner, bool winner){};
+	virtual void battleEnd(BattleResult *br){};
 	virtual void battleStackMoved(int ID, int dest, bool startMoving, bool endMoving)=0;
 	virtual void battleStackAttacking(int ID, int dest)=0;
 	virtual void battleStackIsAttacked(int ID, int dmg, int killed, int IDby, bool byShooting)=0;

File diff suppressed because it is too large
+ 816 - 368
CGameState.cpp


+ 98 - 69
CGameState.h

@@ -1,8 +1,12 @@
 #ifndef CGAMESTATE_H
 #define CGAMESTATE_H
-
-#include "mapHandler.h"
+#include "global.h"
+#ifndef _MSC_VER
+#include "../hch/CCreatureHandler.h"
+#include "lib/VCMI_Lib.h"
+#endif
 #include <set>
+#include <vector>
 #ifdef _WIN32
 #include <tchar.h>
 #else
@@ -16,88 +20,117 @@ class CCPPObjectScript;
 class CCreatureSet;
 class CStack;
 class CGHeroInstance;
+class CGTownInstance;
 class CArmedInstance;
+class CGDefInfo;
+class CObjectScript;
+class CGObjectInstance;
+class CCreature;
+struct Mapa;
+struct StartInfo;
+struct SDL_Surface;
+class CMapHandler;
+class CPathfinder;
+struct IPack;
+
+namespace boost
+{
+	class shared_mutex;
+}
 
-struct PlayerState
+struct DLL_EXPORT PlayerState
 {
 public:
-	int color, serial;
-	//std::vector<std::vector<std::vector<char> > > fogOfWarMap; //true - visible, false - hidden
-	PseudoV< PseudoV< PseudoV<unsigned char> > >  fogOfWarMap; //true - visible, false - hidden
-	std::vector<int> resources;
+	ui8 color, serial;
+	std::vector<std::vector<std::vector<ui8> > >  fogOfWarMap; //true - visible, false - hidden
+	std::vector<si32> resources;
 	std::vector<CGHeroInstance *> heroes;
 	std::vector<CGTownInstance *> towns;
 	PlayerState():color(-1){};
 };
 
-struct BattleInfo
+struct DLL_EXPORT BattleInfo
 {
-	int side1, side2;
-	int round, activeStack;
-	int siege; //    = 0 ordinary battle    = 1 a siege with a Fort    = 2 a siege with a Citadel    = 3 a siege with a Castle
+	ui8 side1, side2;
+	si32 round, activeStack;
+	ui8 siege; //    = 0 ordinary battle    = 1 a siege with a Fort    = 2 a siege with a Citadel    = 3 a siege with a Castle
 	int3 tile; //for background and bonuses
-	CGHeroInstance *hero1, *hero2;
-	CCreatureSet * army1, * army2;
+	si32 hero1, hero2;
+	CCreatureSet army1, army2;
 	std::vector<CStack*> stacks;
-	bool stackActionPerformed; //true if current stack has been moved
+
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & side1 & side2 & round & activeStack & siege & tile & stacks & army1 & army2 & hero1 & hero2;
+	}
+	CStack * getStack(int stackID);
+	CStack * getStackT(int tileID);
+	void getAccessibilityMap(bool *accessibility); //send pointer to at least 187 allocated bytes
+	void getAccessibilityMapForTwoHex(bool *accessibility, bool atackerSide); //send pointer to at least 187 allocated bytes
+	void makeBFS(int start, bool*accessibility, int *predecessor, int *dists); //*accessibility must be prepared bool[187] array; last two pointers must point to the at least 187-elements int arrays - there is written result
+	std::vector<int> getPath(int start, int dest, bool*accessibility);
+	std::vector<int> getAccessibility(int stackID); //returns vector of accessible tiles (taking into account the creature range)
 };
 
-class CStack
+class DLL_EXPORT CStack
 {
 public:
-	int ID; //unique ID of stack
+	ui32 ID; //unique ID of stack
 	CCreature * creature;
-	int amount;
-	int firstHPleft; //HP of first creature in stack
-	unsigned char owner;
-	bool attackerOwned; //if true, this stack is owned by attakcer (this one from left hand side of battle)
-	int position; //position on battlefield
-	bool alive; //true if it is alive
-	CStack(CCreature * C, int A, unsigned char O, int I, bool AO):creature(C),amount(A),owner(O), alive(true), position(-1), ID(I), attackerOwned(AO), firstHPleft(C->hitPoints){};
+	ui32 amount;
+	ui32 firstHPleft; //HP of first creature in stack
+	ui8 owner;
+	ui8 attackerOwned; //if true, this stack is owned by attakcer (this one from left hand side of battle)
+	ui16 position; //position on battlefield
+	ui8 alive; //true if it is alive
+
+	CStack(CCreature * C, int A, int O, int I, bool AO);
 	CStack() : creature(NULL),amount(-1),owner(255), alive(true), position(-1), ID(-1), attackerOwned(true), firstHPleft(-1){};
+
+	template <typename Handler> void save(Handler &h, const int version)
+	{
+		h & creature->idNumber;
+	}
+	template <typename Handler> void load(Handler &h, const int version)
+	{
+		ui32 id;
+		h & id;
+		creature = &VLC->creh->creatures[id];
+	}
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & ID & amount & firstHPleft & owner & attackerOwned & position & alive;
+		if(h.saving)
+			save(h,version);
+		else
+			load(h,version);
+	}
 };
 
-class CGameState
+class DLL_EXPORT CGameState
 {
 private:
-	int currentPlayer;
+	StartInfo* scenarioOps;
+	ui32 seed;
+	ui8 currentPlayer; //ID of player currently having turn
 	BattleInfo *curB; //current battle
-	int day; //total number of days in game
-	std::map<int,PlayerState> players; //color <-> playerstate
-	std::set<CCPPObjectScript *> cppscripts;
-	std::map<int, std::map<std::string, CObjectScript*> > objscr; //custom user scripts (as for now only Lua)
+	ui32 day; //total number of days in game
+	Mapa * map;
+	std::map<ui8,PlayerState> players; //ID <-> playerstate
+	std::map<int, CGDefInfo*> villages, forts, capitols; //def-info for town graphics
 
+	boost::shared_mutex *mx;
+
+	CGameState();
+	~CGameState();
+	void init(StartInfo * si, Mapa * map, int Seed);
+	void apply(IPack * pack);
+	void randomizeObject(CGObjectInstance *cur);
+	std::pair<int,int> pickObject(CGObjectInstance *obj);
+	int pickHero(int owner);
+
+	CGHeroInstance *getHero(int objid);
 
-	bool checkFunc(int obid, std::string name)
-	{
-		if (objscr.find(obid)!=objscr.end())
-		{
-			if(objscr[obid].find(name)!=objscr[obid].end())
-			{
-				return true;
-			}
-		}
-		return false;
-	}
-	CGHeroInstance * getHero(int ID, int mode)
-	{
-		if (mode != 0)
-#ifndef __GNUC__
-			throw new std::exception("gs->getHero: This mode is not supported!");
-#else
-			throw new std::exception();
-#endif
-		for ( std::map<int, PlayerState>::iterator i=players.begin() ; i!=players.end();i++)
-		{
-			for (int j=0;j<(*i).second.heroes.size();j++)
-			{
-				if (i->second.heroes[j]->subID == ID)
-					return i->second.heroes[j];
-			}
-		}
-		return NULL;
-	}
-	void battle(CCreatureSet * army1, CCreatureSet * army2, int3 tile, CArmedInstance *hero1, CArmedInstance *hero2);
 	bool battleMoveCreatureStack(int ID, int dest);
 	bool battleAttackCreatureStack(int ID, int dest);
 	bool battleShootCreatureStack(int ID, int dest);
@@ -105,20 +138,16 @@ private:
 	static int calculateDmg(const CStack* attacker, const CStack* defender); //TODO: add additional conditions and require necessary data
 	std::vector<int> battleGetRange(int ID); //called by std::vector<int> CCallback::battleGetAvailableHexes(int ID);
 public:
+	int getDate(int mode=0) const; //mode=0 - total days in game, mode=1 - day of week, mode=2 - current week, mode=3 - current month
+	
 	friend class CCallback;
 	friend class CPathfinder;;
 	friend class CLuaCallback;
-#ifndef __GNUC__
-	friend int _tmain(int argc, _TCHAR* argv[]);
-#else
-	friend int main(int argc, _TCHAR* argv[]);
-#endif
-	friend void initGameState(CGameInfo * cgi);
+	friend class CClient;
+	friend void initGameState(Mapa * map, CGameInfo * cgi);
 	friend class CScriptCallback;
-	friend void handleCPPObjS(std::map<int,CCPPObjectScript*> * mapa, CCPPObjectScript * script);
-	//CCallback * cb; //for communication between PlayerInterface/AI and GameState
-
-	friend SDL_Surface * CMapHandler::terrainRect(int x, int y, int dx, int dy, int level, unsigned char anim, PseudoV< PseudoV< PseudoV<unsigned char> > > & visibilityMap, bool otherHeroAnim, unsigned char heroAnim, SDL_Surface * extSurf, SDL_Rect * extRect); //todo: wywalic koniecznie, tylko do flag obecnie!!!!
+	friend class CMapHandler;
+	friend class CGameHandler;
 };
 
 #endif //CGAMESTATE_H

+ 98 - 93
CHeroWindow.cpp

@@ -12,8 +12,12 @@
 #include "hch/CObjectHandler.h"
 #include "CMessage.h"
 #include "CCallback.h"
+#include "hch/CArtHandler.h"
+#include "hch/CAbilityHandler.h"
+#include "hch/CDefHandler.h"
+#include "client/CBitmapHandler.h"
 #include <sstream>
-
+#include "client/Graphics.h"
 extern SDL_Surface * screen;
 extern TTF_Font * GEOR16;
 
@@ -21,8 +25,8 @@ CHeroWindow::CHeroWindow(int playerColor):
 	backpackPos(0), player(playerColor)
 {
 	artWorn.resize(19);
-	background = CGI->bitmaph->loadBitmap("HEROSCR4.bmp");
-	CSDL_Ext::blueToPlayersAdv(background, playerColor);
+	background = BitmapHandler::loadBitmap("HEROSCR4.bmp");
+	graphics->blueToPlayersAdv(background, playerColor);
 	pos.x = 65;
 	pos.y = 8;
 	pos.h = background->h;
@@ -58,8 +62,8 @@ CHeroWindow::CHeroWindow(int playerColor):
 		heroListMi[g]->id = g;
 	}
 
-	skillpics = CGI->spriteh->giveDef("pskil42.def");
-	flags = CGI->spriteh->giveDef("CREST58.DEF");
+	skillpics = CDefHandler::giveDef("pskil42.def");
+	flags = CDefHandler::giveDef("CREST58.DEF");
 	//areas
 	portraitArea = new LRClickableAreaWText();
 	portraitArea->pos.x = 83;
@@ -181,8 +185,9 @@ void CHeroWindow::show(SDL_Surface *to)
 	}
 }
 
-void CHeroWindow::setHero(const CGHeroInstance *hero)
+void CHeroWindow::setHero(const CGHeroInstance *Hero)
 {
+	CGHeroInstance *hero = const_cast<CGHeroInstance*>(Hero); //but don't modify hero! - it's only for easy map reading
 	if(!hero) //something strange... no hero? it shouldn't happen
 	{
 		return;
@@ -256,210 +261,210 @@ void CHeroWindow::setHero(const CGHeroInstance *hero)
 	}
 	backpack.clear();
 
-	artWorn[8] = new CArtPlace(hero->artifWorn[8]);
+	artWorn[8] = new CArtPlace(hero->getArt(8));
 	artWorn[8]->pos.x = 515;
 	artWorn[8]->pos.y = 295;
 	artWorn[8]->pos.h = artWorn[8]->pos.w = 44;
-	if(hero->artifWorn[8])
-		artWorn[8]->text = hero->artifWorn[8]->description;
+	if(hero->getArt(8))
+		artWorn[8]->text = hero->getArt(8)->description;
 	else
 		artWorn[8]->text = std::string();
 	artWorn[8]->ourWindow = this;
 	artWorn[8]->feet = true;
 
-	artWorn[0] = new CArtPlace(hero->artifWorn[0]);
+	artWorn[0] = new CArtPlace(hero->getArt(0));
 	artWorn[0]->pos.x = 509;
 	artWorn[0]->pos.y = 30;
 	artWorn[0]->pos.h = artWorn[0]->pos.w = 44;
-	if(hero->artifWorn[0])
-		artWorn[0]->text = hero->artifWorn[0]->description;
+	if(hero->getArt(0))
+		artWorn[0]->text = hero->getArt(0)->description;
 	else
 		artWorn[0]->text = std::string();
 	artWorn[0]->ourWindow = this;
 	artWorn[0]->head = true;
 
-	artWorn[4] = new CArtPlace(hero->artifWorn[4]);
+	artWorn[4] = new CArtPlace(hero->getArt(4));
 	artWorn[4]->pos.x = 564;
 	artWorn[4]->pos.y = 183;
 	artWorn[4]->pos.h = artWorn[4]->pos.w = 44;
-	if(hero->artifWorn[4])
-		artWorn[4]->text = hero->artifWorn[4]->description;
+	if(hero->getArt(4))
+		artWorn[4]->text = hero->getArt(4)->description;
 	else
 		artWorn[4]->text = std::string();
 	artWorn[4]->ourWindow = this;
 	artWorn[4]->lHand = true;
 
-	artWorn[7] = new CArtPlace(hero->artifWorn[7]);
+	artWorn[7] = new CArtPlace(hero->getArt(7));
 	artWorn[7]->pos.x = 610;
 	artWorn[7]->pos.y = 183;
 	artWorn[7]->pos.h = artWorn[7]->pos.w = 44;
-	if(hero->artifWorn[7])
-		artWorn[7]->text = hero->artifWorn[7]->description;
+	if(hero->getArt(7))
+		artWorn[7]->text = hero->getArt(7)->description;
 	else
 		artWorn[7]->text = std::string();
 	artWorn[7]->ourWindow = this;
 	artWorn[7]->lRing = true;
 
-	artWorn[13] = new CArtPlace(hero->artifWorn[13]);
+	artWorn[13] = new CArtPlace(hero->getArt(13));
 	artWorn[13]->pos.x = 564;
 	artWorn[13]->pos.y = 30;
 	artWorn[13]->pos.h = artWorn[13]->pos.w = 44;
-	if(hero->artifWorn[13])
-		artWorn[13]->text = hero->artifWorn[13]->description;
+	if(hero->getArt(13))
+		artWorn[13]->text = hero->getArt(13)->description;
 	else
 		artWorn[13]->text = std::string();
 	artWorn[13]->ourWindow = this;
 	artWorn[13]->warMachine1 = true;
 
-	artWorn[14] = new CArtPlace(hero->artifWorn[14]);
+	artWorn[14] = new CArtPlace(hero->getArt(14));
 	artWorn[14]->pos.x = 610;
 	artWorn[14]->pos.y = 30;
 	artWorn[14]->pos.h = artWorn[14]->pos.w = 44;
-	if(hero->artifWorn[14])
-		artWorn[14]->text = hero->artifWorn[14]->description;
+	if(hero->getArt(14))
+		artWorn[14]->text = hero->getArt(14)->description;
 	else
 		artWorn[14]->text = std::string();
 	artWorn[14]->ourWindow = this;
 	artWorn[14]->warMachine2 = true;
 
-	artWorn[15] = new CArtPlace(hero->artifWorn[15]);
+	artWorn[15] = new CArtPlace(hero->getArt(15));
 	artWorn[15]->pos.x = 610;
 	artWorn[15]->pos.y = 76;
 	artWorn[15]->pos.h = artWorn[15]->pos.w = 44;
-	if(hero->artifWorn[15])
-		artWorn[15]->text = hero->artifWorn[15]->description;
+	if(hero->getArt(15))
+		artWorn[15]->text = hero->getArt(15)->description;
 	else
 		artWorn[15]->text = std::string();
 	artWorn[15]->ourWindow = this;
 	artWorn[15]->warMachine3 = true;
 
-	artWorn[16] = new CArtPlace(hero->artifWorn[16]);
+	artWorn[16] = new CArtPlace(hero->getArt(16));
 	artWorn[16]->pos.x = 610;
 	artWorn[16]->pos.y = 122;
 	artWorn[16]->pos.h = artWorn[16]->pos.w = 44;
-	if(hero->artifWorn[16])
-		artWorn[16]->text = hero->artifWorn[16]->description;
+	if(hero->getArt(16))
+		artWorn[16]->text = hero->getArt(16)->description;
 	else
 		artWorn[16]->text = std::string();
 	artWorn[16]->ourWindow = this;
 	artWorn[16]->warMachine4 = true;
 
-	artWorn[9] = new CArtPlace(hero->artifWorn[9]);
+	artWorn[9] = new CArtPlace(hero->getArt(9));
 	artWorn[9]->pos.x = 383;
 	artWorn[9]->pos.y = 143;
 	artWorn[9]->pos.h = artWorn[9]->pos.w = 44;
-	if(hero->artifWorn[9])
-		artWorn[9]->text = hero->artifWorn[9]->description;
+	if(hero->getArt(9))
+		artWorn[9]->text = hero->getArt(9)->description;
 	else
 		artWorn[9]->text = std::string();
 	artWorn[9]->ourWindow = this;
 	artWorn[9]->misc1 = true;
 
-	artWorn[10] = new CArtPlace(hero->artifWorn[10]);
+	artWorn[10] = new CArtPlace(hero->getArt(10));
 	artWorn[10]->pos.x = 399;
 	artWorn[10]->pos.y = 194;
 	artWorn[10]->pos.h = artWorn[10]->pos.w = 44;
-	if(hero->artifWorn[10])
-		artWorn[10]->text = hero->artifWorn[10]->description;
+	if(hero->getArt(10))
+		artWorn[10]->text = hero->getArt(10)->description;
 	else
 		artWorn[10]->text = std::string();
 	artWorn[10]->ourWindow = this;
 	artWorn[10]->misc1 = true;
 
-	artWorn[11] = new CArtPlace(hero->artifWorn[11]);
+	artWorn[11] = new CArtPlace(hero->getArt(11));
 	artWorn[11]->pos.x = 415;
 	artWorn[11]->pos.y = 245;
 	artWorn[11]->pos.h = artWorn[11]->pos.w = 44;
-	if(hero->artifWorn[11])
-		artWorn[11]->text = hero->artifWorn[11]->description;
+	if(hero->getArt(11))
+		artWorn[11]->text = hero->getArt(11)->description;
 	else
 		artWorn[11]->text = std::string();
 	artWorn[11]->ourWindow = this;
 	artWorn[11]->misc3 = true;
 
-	artWorn[12] = new CArtPlace(hero->artifWorn[12]);
+	artWorn[12] = new CArtPlace(hero->getArt(12));
 	artWorn[12]->pos.x = 431;
 	artWorn[12]->pos.y = 296;
 	artWorn[12]->pos.h = artWorn[12]->pos.w = 44;
-	if(hero->artifWorn[12])
-		artWorn[12]->text = hero->artifWorn[12]->description;
+	if(hero->getArt(12))
+		artWorn[12]->text = hero->getArt(12)->description;
 	else
 		artWorn[12]->text = std::string();
 	artWorn[12]->ourWindow = this;
 	artWorn[12]->misc4 = true;
 
-	artWorn[18] = new CArtPlace(hero->artifWorn[18]);
+	artWorn[18] = new CArtPlace(hero->getArt(18));
 	artWorn[18]->pos.x = 381;
 	artWorn[18]->pos.y = 296;
 	artWorn[18]->pos.h = artWorn[18]->pos.w = 44;
-	if(hero->artifWorn[18])
-		artWorn[18]->text = hero->artifWorn[18]->description;
+	if(hero->getArt(18))
+		artWorn[18]->text = hero->getArt(18)->description;
 	else
 		artWorn[18]->text = std::string();
 	artWorn[18]->ourWindow = this;
 	artWorn[18]->misc5 = true;
 
-	artWorn[2] = new CArtPlace(hero->artifWorn[2]);
+	artWorn[2] = new CArtPlace(hero->getArt(2));
 	artWorn[2]->pos.x = 508;
 	artWorn[2]->pos.y = 79;
 	artWorn[2]->pos.h = artWorn[2]->pos.w = 44;
-	if(hero->artifWorn[2])
-		artWorn[2]->text = hero->artifWorn[2]->description;
+	if(hero->getArt(2))
+		artWorn[2]->text = hero->getArt(2)->description;
 	else
 		artWorn[2]->text = std::string();
 	artWorn[2]->ourWindow = this;
 	artWorn[2]->neck = true;
 
-	artWorn[3] = new CArtPlace(hero->artifWorn[3]);
+	artWorn[3] = new CArtPlace(hero->getArt(3));
 	artWorn[3]->pos.x = 383;
 	artWorn[3]->pos.y = 68;
 	artWorn[3]->pos.h = artWorn[3]->pos.w = 44;
-	if(hero->artifWorn[3])
-		artWorn[3]->text = hero->artifWorn[3]->description;
+	if(hero->getArt(3))
+		artWorn[3]->text = hero->getArt(3)->description;
 	else
 		artWorn[3]->text = std::string();
 	artWorn[3]->ourWindow = this;
 	artWorn[3]->rHand = true;
 
-	artWorn[6] = new CArtPlace(hero->artifWorn[6]);
+	artWorn[6] = new CArtPlace(hero->getArt(6));
 	artWorn[6]->pos.x = 431;
 	artWorn[6]->pos.y = 68;
 	artWorn[6]->pos.h = artWorn[6]->pos.w = 44;
-	if(hero->artifWorn[6])
-		artWorn[6]->text = hero->artifWorn[6]->description;
+	if(hero->getArt(6))
+		artWorn[6]->text = hero->getArt(6)->description;
 	else
 		artWorn[6]->text = std::string();
 	artWorn[6]->ourWindow = this;
 	artWorn[6]->rRing = true;
 
-	artWorn[1] = new CArtPlace(hero->artifWorn[1]);
+	artWorn[1] = new CArtPlace(hero->getArt(1));
 	artWorn[1]->pos.x = 567;
 	artWorn[1]->pos.y = 240;
 	artWorn[1]->pos.h = artWorn[1]->pos.w = 44;
-	if(hero->artifWorn[1])
-		artWorn[1]->text = hero->artifWorn[1]->description;
+	if(hero->getArt(1))
+		artWorn[1]->text = hero->getArt(1)->description;
 	else
 		artWorn[1]->text = std::string();
 	artWorn[1]->ourWindow = this;
 	artWorn[1]->shoulders = true;
 
-	artWorn[17] = new CArtPlace(hero->artifWorn[17]);
+	artWorn[17] = new CArtPlace(hero->getArt(17));
 	artWorn[17]->pos.x = 610;
 	artWorn[17]->pos.y = 310;
 	artWorn[17]->pos.h = artWorn[17]->pos.w = 44;
-	if(hero->artifWorn[17])
-		artWorn[17]->text = hero->artifWorn[17]->description;
+	if(hero->getArt(17))
+		artWorn[17]->text = hero->getArt(17)->description;
 	else
 		artWorn[17]->text = std::string();
 	artWorn[17]->ourWindow = this;
 	artWorn[17]->spellBook = true;
 
-	artWorn[5] = new CArtPlace(hero->artifWorn[5]);
+	artWorn[5] = new CArtPlace(hero->getArt(5));
 	artWorn[5]->pos.x = 509;
 	artWorn[5]->pos.y = 130;
 	artWorn[5]->pos.h = artWorn[5]->pos.w = 44;
-	if(hero->artifWorn[5])
-		artWorn[5]->text = hero->artifWorn[5]->description;
+	if(hero->getArt(5))
+		artWorn[5]->text = hero->getArt(5)->description;
 	else
 		artWorn[5]->text = std::string();
 	artWorn[5]->ourWindow = this;
@@ -479,14 +484,14 @@ void CHeroWindow::setHero(const CGHeroInstance *hero)
 	{
 		CArtPlace * add;
 		if( s < curHero->artifacts.size() )
-			add = new CArtPlace(curHero->artifacts[(s+backpackPos) % curHero->artifacts.size() ]);
+			add = new CArtPlace(&CGI->arth->artifacts[curHero->artifacts[(s+backpackPos) % curHero->artifacts.size() ]]);
 		else
 			add = new CArtPlace(NULL);
 		add->pos.x = 403 + 46*s;
 		add->pos.y = 365;
 		add->pos.h = add->pos.w = 44;
 		if(s<hero->artifacts.size() && hero->artifacts[s])
-			add->text = hero->artifacts[s]->description;
+			add->text = hero->getArt(s)->description;
 		else
 			add->text = std::string();
 		add->ourWindow = this;
@@ -676,7 +681,7 @@ void CHeroWindow::leftArtRoller()
 
 		for(int s=0; s<5 && s<curHero->artifacts.size(); ++s) //set new data
 		{
-			backpack[s]->ourArt = curHero->artifacts[(s+backpackPos) % curHero->artifacts.size() ];
+			backpack[s]->ourArt = &CGI->arth->artifacts[curHero->artifacts[(s+backpackPos) % curHero->artifacts.size() ]];
 			if(backpack[s]->ourArt)
 				backpack[s]->text = backpack[s]->ourArt->description;
 			else
@@ -693,7 +698,7 @@ void CHeroWindow::rightArtRoller()
 
 		for(int s=0; s<5 && s<curHero->artifacts.size(); ++s) //set new data
 		{
-			backpack[s]->ourArt = curHero->artifacts[(s+backpackPos) % curHero->artifacts.size() ];
+			backpack[s]->ourArt = &CGI->arth->artifacts[curHero->artifacts[(s+backpackPos) % curHero->artifacts.size() ] ];
 			if(backpack[s]->ourArt)
 				backpack[s]->text = backpack[s]->ourArt->description;
 			else
@@ -731,7 +736,7 @@ void CHeroWindow::redrawCurBack()
 	blitAt(skillpics->ourImages[4].bitmap, 20, 230, curBack);
 	blitAt(skillpics->ourImages[3].bitmap, 162, 230, curBack);
 
-	blitAt(CGI->heroh->largePortraits[curHero->portrait], 19, 19, curBack);
+	blitAt(graphics->portraitLarge[curHero->portrait], 19, 19, curBack);
 
 	CSDL_Ext::printAtMiddle(curHero->name, 190, 40, GEORXX, tytulowy, curBack);
 
@@ -787,8 +792,8 @@ void CHeroWindow::redrawCurBack()
 	primarySkill4<<curHero->primSkills[3];
 	CSDL_Ext::printAtMiddle(primarySkill4.str(), 263, 165, TNRB16, zwykly, curBack);
 
-	blitAt(LOCPLINT->luck42->ourImages[curHero->getCurrentLuck()+3].bitmap, 239, 182, curBack);
-	blitAt(LOCPLINT->morale42->ourImages[curHero->getCurrentMorale()+3].bitmap, 181, 182, curBack);
+	blitAt(graphics->luck42->ourImages[curHero->getCurrentLuck()+3].bitmap, 239, 182, curBack);
+	blitAt(graphics->morale42->ourImages[curHero->getCurrentMorale()+3].bitmap, 181, 182, curBack);
 
 	blitAt(flags->ourImages[player].bitmap, 606, 8, curBack);
 
@@ -796,14 +801,14 @@ void CHeroWindow::redrawCurBack()
 	for(int g=0; g<LOCPLINT->cb->howManyHeroes(); ++g)
 	{
 		const CGHeroInstance * cur = LOCPLINT->cb->getHeroInfo(player, g, false);
-		blitAt(CGI->heroh->smallPortraits[cur->portrait], 611, 87+g*54, curBack);
+		blitAt(graphics->portraitSmall[cur->portrait], 611, 87+g*54, curBack);
 		//printing yellow border
 		if(cur->name == curHero->name)
 		{
-			for(int f=0; f<CGI->heroh->smallPortraits[cur->portrait]->w; ++f)
+			for(int f=0; f<graphics->portraitSmall[cur->portrait]->w; ++f)
 			{
-				for(int h=0; h<CGI->heroh->smallPortraits[cur->portrait]->h; ++h)
-					if(f==0 || h==0 || f==CGI->heroh->smallPortraits[cur->portrait]->w-1 || h==CGI->heroh->smallPortraits[cur->portrait]->h-1)
+				for(int h=0; h<graphics->portraitSmall[cur->portrait]->h; ++h)
+					if(f==0 || h==0 || f==graphics->portraitSmall[cur->portrait]->w-1 || h==graphics->portraitSmall[cur->portrait]->h-1)
 					{
 						CSDL_Ext::SDL_PutPixel(curBack, 611+f, 87+g*54+h, 240, 220, 120);
 					}
@@ -862,7 +867,7 @@ void CHeroWindow::redrawCurBack()
 	}
 
 	//printing special ability
-	blitAt(CGI->heroh->un44->ourImages[curHero->subID].bitmap, 18, 180, curBack);
+	blitAt(graphics->un44->ourImages[curHero->subID].bitmap, 18, 180, curBack);
 
 	//printing necessery texts
 	CSDL_Ext::printAt(CGI->generaltexth->jktexts[6].substr(1, CGI->generaltexth->jktexts[6].size()-2), 69, 231, GEOR13, tytulowy, curBack);
@@ -875,7 +880,7 @@ void CHeroWindow::redrawCurBack()
 	CSDL_Ext::printAt(manastr.str(), 212, 247, GEOR16, zwykly, curBack);
 }
 
-CArtPlace::CArtPlace(const CArtifact * const & art): ourArt(art), active(false), clicked(false),
+CArtPlace::CArtPlace(const CArtifact* Art): ourArt(Art), active(false), clicked(false),
 	spellBook(false), warMachine1(false), warMachine2(false), warMachine3(false),
 	warMachine4(false),misc1(false), misc2(false), misc3(false), misc4(false),
 	misc5(false), feet(false), lRing(false), rRing(false), torso(false),
@@ -978,7 +983,7 @@ void CArtPlace::show(SDL_Surface *to)
 {
 	if(ourArt)
 	{
-		blitAt(CGI->arth->artDefs->ourImages[ourArt->id].bitmap, pos.x, pos.y, to);
+		blitAt(graphics->artDefs->ourImages[ourArt->id].bitmap, pos.x, pos.y, to);
 	}
 	if(clicked && active)
 	{
@@ -1028,14 +1033,14 @@ void LClickableArea::deactivate()
 }
 void LClickableArea::clickLeft(boost::logic::tribool down)
 {
-	if(!down)
-	{
-		#if !defined(__amigaos4__) && !defined(__unix__)
-		LOCPLINT->showInfoDialog("TEST TEST AAA", std::vector<SComponent*>());
-		#else
-		#warning error here!
-		#endif
-	}
+	//if(!down)
+	//{
+	//	LOCPLINT->showInfoDialog("TEST TEST AAA", std::vector<SComponent*>());
+	//}
+
+
+
+
 }
 
 void RClickableArea::activate()
@@ -1048,14 +1053,14 @@ void RClickableArea::deactivate()
 }
 void RClickableArea::clickRight(boost::logic::tribool down)
 {
-	if(!down)
-	{
-		#if !defined(__amigaos4__) && !defined(__unix__)
-		LOCPLINT->showInfoDialog("TEST TEST AAA", std::vector<SComponent*>());
-		#else
-		#warning error here!
-		#endif
-	}
+	//if(!down)
+	//{
+	//	LOCPLINT->showInfoDialog("TEST TEST AAA", std::vector<SComponent*>());
+	//}
+
+
+
+
 }
 
 void LRClickableAreaWText::clickLeft(boost::logic::tribool down)

+ 2 - 2
CHeroWindow.h

@@ -70,7 +70,7 @@ public:
 	bool clicked;
 	CHeroWindow * ourWindow;
 	const CArtifact * ourArt;
-	CArtPlace(const CArtifact * const & art);
+	CArtPlace(const CArtifact * Art);
 	void clickLeft (tribool down);
 	void clickRight (tribool down);
 	void activate();
@@ -117,7 +117,7 @@ public:
 	int player;
 	CHeroWindow(int playerColor); //c-tor
 	~CHeroWindow(); //d-tor
-	void setHero(const CGHeroInstance * hero); //sets main displayed hero
+	void setHero(const CGHeroInstance * Hero); //sets main displayed hero
 	void activate(); //activates hero window;
 	void deactivate(); //activates hero window;
 	virtual void show(SDL_Surface * to = NULL); //shows hero window

+ 360 - 370
CLua.cpp

@@ -1,42 +1,33 @@
 #include "stdafx.h"
-#include "CLua.h"
-#include "CLuaHandler.h"
-#include "hch/CHeroHandler.h"
-
-#ifndef _MSC_VER
-extern "C" {
-#endif
-
-#include "lua.h"
-#include "lualib.h"
-#include "lauxlib.h"
-#include "lobject.h"
-#include "lgc.h"
-#include "lapi.h"
-
-#ifndef _MSC_VER
-}
-#endif
-
-#include "CGameInfo.h"
-#include "CGameState.h"
-#include <sstream>
-#include "hch/CObjectHandler.h"
-#include "hch/CTownHandler.h"
-#include "CCallback.h"
-#include "hch/CGeneralTextHandler.h"
 #include <sstream>
-#include "CPlayerInterface.h"
 #include <boost/algorithm/string.hpp>
 #include <boost/algorithm/string/replace.hpp>
+#include "hch/CHeroHandler.h"
+#include "hch/CObjectHandler.h"
+#include "hch/CTownHandler.h"
+#include "hch/CArtHandler.h"
 #include "hch/CDefObjInfoHandler.h"
+//#include "lua.h"
+//#include "lualib.h"
+//#include "lauxlib.h"
+//#include "lobject.h"
+//#include "lgc.h"
+//#include "lapi.h"
+#include "CLua.h"
+#include "CGameState.h"
+#include "lib/VCMI_Lib.h"
+#include "map.h"
+#include "server/CScriptCallback.h"
+#include "lib/NetPacks.h"
 #pragma warning (disable : 4311)
+#define DEFOS const CGObjectInstance *os = cb->getObj(objid)
 bool getGlobalFunc(lua_State * L, std::string fname)
 {
-	unsigned int hash = lua_calchash(fname.c_str(), fname.size());
-	lua_pushhstring(L, hash, fname.c_str(), fname.size());
-	lua_gettable(L, LUA_GLOBALSINDEX);
-	return lua_isfunction(L, -1);
+	//unsigned int hash = lua_calchash(fname.c_str(), fname.size());
+	//lua_pushhstring(L, hash, fname.c_str(), fname.size());
+	//lua_gettable(L, LUA_GLOBALSINDEX);
+	//return lua_isfunction(L, -1);
+	return false;
 }
 
 CObjectScript::CObjectScript()
@@ -72,24 +63,20 @@ CLua::CLua()
 }
 void CLua::open(std::string initpath)
 {
-	LST = lua_open();
-	opened = true;
-	LUA_OPEN_LIB(LST, luaopen_base);
-	LUA_OPEN_LIB(LST, luaopen_io);
-	if ((luaL_loadfile (LST, initpath.c_str())) == 0)
-	{
-		lua_pcall (LST, 0, LUA_MULTRET, 0);
-	}
-	else
-	{
-#ifndef __GNUC__
-		std::string temp = "Cannot open script ";
-		temp += initpath;
-		throw std::exception(temp.c_str());
-#else
-		throw std::exception();
-#endif
-	}
+	//LST = lua_open();
+	//opened = true;
+	//LUA_OPEN_LIB(LST, luaopen_base);
+	//LUA_OPEN_LIB(LST, luaopen_io);
+	//if ((luaL_loadfile (LST, initpath.c_str())) == 0)
+	//{
+	//	lua_pcall (LST, 0, LUA_MULTRET, 0);
+	//}
+	//else
+	//{
+	//	std::string temp = "Cannot open script ";
+	//	temp += initpath;
+	//	throw std::exception(temp.c_str());
+	//}
 }
 void CLua::registerCLuaCallback()
 {
@@ -97,35 +84,31 @@ void CLua::registerCLuaCallback()
 
 CLua::~CLua()
 {
-	//std::cout << "Usuwam obiekt clua "<<this<<std::endl;
-	if (opened)
-	{
-		std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"<<std::endl;
-		lua_close(LST);
-	}
+	////std::cout << "Usuwam obiekt clua "<<this<<std::endl;
+	//if (opened)
+	//{
+	//	std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!"<<std::endl;
+	//	lua_close(LST);
+	//}
 }
 
 void CLua::findF(std::string fname)
 {
-	 lua_getfield(is, LUA_GLOBALSINDEX, fname.c_str()); /* function to be called */
+	// lua_getfield(is, LUA_GLOBALSINDEX, fname.c_str()); /* function to be called */
 }
 void CLua::findF2(std::string fname)
 {
-	lua_pushstring (is, fname.c_str());
-	lua_gettable (is, LUA_GLOBALSINDEX);
+	//lua_pushstring (is, fname.c_str());
+	//lua_gettable (is, LUA_GLOBALSINDEX); 
 }
 void CLua::findFS(std::string fname)
 {
-	lua_settop(is, 0);
-	if (!getGlobalFunc(is,fname))
-	{
-		lua_settop(is, 0);
-#ifndef __GNUC__
-		throw new std::exception((fname + ": function not defined").c_str()); // the call is not defined
-#else
-		throw std::exception();
-#endif
-	}
+	//lua_settop(is, 0);
+	//if (!getGlobalFunc(is,fname)) 
+	//{
+	//	lua_settop(is, 0);
+	//	throw new std::exception((fname + ": function not defined").c_str()); // the call is not defined
+	//}
 }
 #undef LST
 
@@ -152,79 +135,102 @@ std::string CLuaObjectScript::genFN(std::string base, int ID)
 	return sts.str();
 }
 
-void CLuaObjectScript::newObject(CGObjectInstance *os)
+void CLuaObjectScript::newObject(int objid)
 {
-	findF(genFN("newObject",os->ID));
-	lua_pushinteger(is, (int)os);
-	if (lua_pcall (is, 1, 0, 0))
-	{
-		lua_settop(is, 0);
-#ifndef __GNUC__
-		throw new  std::exception(("Failed to call "+genFN("newObject",os->ID)+" function in lua script.").c_str());
-#else
-		throw std::exception();
-#endif
-	}
-	lua_settop(is, 0);
+	//findF(genFN("newObject",os->ID));
+	//lua_pushinteger(is, (int)os);
+	//if (lua_pcall (is, 1, 0, 0))
+	//{
+	//	lua_settop(is, 0);
+	//	throw new  std::exception(("Failed to call "+genFN("newObject",os->ID)+" function in lua script.").c_str());
+	//}
+	//lua_settop(is, 0);
 	return;
 }
-void CLuaObjectScript::onHeroVisit(CGObjectInstance *os, int heroID)
+void CLuaObjectScript::onHeroVisit(int objid, int heroID)
+{
+	//findF(genFN("heroVisit",os->ID));
+	//lua_pushinteger(is, (int)os);
+	//lua_pushinteger(is, heroID);
+	//if (lua_pcall (is, 2, 0, 0))
+	//{
+	//	lua_settop(is, 0);
+	//	throw new  std::exception(("Failed to call "+genFN("heroVisit",os->ID)+" function in lua script.").c_str());
+	//}
+	//lua_settop(is, 0);
+}
+//std::string CLuaObjectScript::hoverText(int objid)
+//{
+//	//findF(genFN("hoverText",os->ID));
+//	//lua_pushinteger(is, (int)os);
+//	//if (lua_pcall (is, 1, 1, 0))
+//	//{
+//	//	lua_settop(is, 0);
+//	//	throw new  std::exception(("Failed to call "+genFN("hoverText",os->ID)+" function in lua script.").c_str());
+//	//}
+//	//std::string ret = lua_tostring(is,1);
+//	//lua_settop(is, 0);
+//	return "";
+//}
+
+void CVisitableOPH::newObject(int objid)
 {
-	findF(genFN("heroVisit",os->ID));
-	lua_pushinteger(is, (int)os);
-	lua_pushinteger(is, heroID);
-	if (lua_pcall (is, 2, 0, 0))
-	{
-		lua_settop(is, 0);
-#ifndef __GNUC__
-		throw new  std::exception(("Failed to call "+genFN("heroVisit",os->ID)+" function in lua script.").c_str());
-#else
-		throw std::exception();
-#endif
-	}
-	lua_settop(is, 0);
-}
-std::string CLuaObjectScript::hoverText(CGObjectInstance *os)
-{
-	findF(genFN("hoverText",os->ID));
-	lua_pushinteger(is, (int)os);
-	if (lua_pcall (is, 1, 1, 0))
+	visitors.insert
+		(std::pair<int,std::set<int> >(objid,std::set<int>()));
+
+	DEFOS;
+	MetaString hovername;
+	int pom;
+	switch(os->ID)
 	{
-		lua_settop(is, 0);
+	case 51:
+		pom = 8; 
+		break;
+	case 23:
+		pom = 7;
+		break;
+	case 61:
+		pom = 11; 
+		break;
+	case 32:
+		pom = 4; 
+		break;
+	case 100:
+		pom = 5; 
+		break;
+	default:
 #ifndef __GNUC__
-		throw new  std::exception(("Failed to call "+genFN("hoverText",os->ID)+" function in lua script.").c_str());
+		throw new std::exception("Unsupported ID in CVisitableOPH::hoverText");
 #else
-		throw std::exception();
+		throw new std::exception();
 #endif
 	}
-	std::string ret = lua_tostring(is,1);
-	lua_settop(is, 0);
-	return ret;
-}
-
-std::string CCPPObjectScript::hoverText(CGObjectInstance *os)
-{
-	return CGI->objh->objects[os->defInfo->id].name;
-}
-
-void CVisitableOPH::newObject(CGObjectInstance *os)
-{
-	visitors.insert
-		(std::pair<CGObjectInstance*,std::set<int> >(os,std::set<int>()));
+	hovername << std::pair<ui8,ui32>(3,os->ID) << " " << std::pair<ui8,ui32>(2,pom);
+	cb->setHoverName(objid,&hovername);
+
+	//int heroID = cb->getSelectedHero();
+	//if (heroID>=0)
+	//{
+		//add += ( (visitors[os].find(heroID) == visitors[os].end()) 
+		//		? 
+		//	(VLC->generaltexth->allTexts[353])  //not visited
+		//		: 
+		//	( VLC->generaltexth->allTexts[352]) ); //visited
+	//}
 };
 
-void CVisitableOPH::onHeroVisit(CGObjectInstance *os, int heroID)
+void CVisitableOPH::onHeroVisit(int objid, int heroID)
 {
-	if (visitors.find(os)!=visitors.end())
+	if (visitors.find(objid)!=visitors.end())
 	{
-		if(visitors[os].find(heroID)==visitors[os].end())
+		if(visitors[objid].find(heroID)==visitors[objid].end())
 		{
-			onNAHeroVisit(os,heroID, false);
-			visitors[os].insert(heroID);
+			onNAHeroVisit(objid,heroID, false);
+			visitors[objid].insert(heroID);
 		}
 		else
 		{
-			onNAHeroVisit(os,heroID, true);
+			onNAHeroVisit(objid,heroID, true);
 		}
 	}
 	else
@@ -232,12 +238,13 @@ void CVisitableOPH::onHeroVisit(CGObjectInstance *os, int heroID)
 #ifndef __GNUC__
 		throw new std::exception("Skrypt nie zainicjalizowal instancji tego obiektu. :(");
 #else
-		throw std::exception();
+		throw new std::exception();
 #endif
 	}
 };
-void CVisitableOPH::onNAHeroVisit(CGObjectInstance *os, int heroID, bool alreadyVisited)
+void CVisitableOPH::onNAHeroVisit(int objid, int heroID, bool alreadyVisited)
 {
+	const CGObjectInstance *os = cb->getObj(objid);
 	int w=0, ot=0, vvv=1;
 	switch(os->ID)
 	{
@@ -273,21 +280,21 @@ void CVisitableOPH::onNAHeroVisit(CGObjectInstance *os, int heroID, bool already
 		case 32:
 			{
 				cb->changePrimSkill(heroID,w,vvv);
-				std::vector<SComponent*> weko;
-				weko.push_back(new SComponent(SComponent::primskill,w,vvv));
-				cb->showInfoDialog(cb->getHeroOwner(heroID),CGI->objh->advobtxt[ot],&weko);
-				//for (int ii=0; ii<weko.size();ii++)
-				//	delete weko[ii];
+				InfoWindow iw;
+				iw.components.push_back(Component(0,w,vvv,0));
+				iw.text << std::pair<ui8,ui32>(11,ot);
+				iw.player = cb->getHeroOwner(heroID);
+				cb->showInfoDialog(&iw);
 				break;
 			}
-		case 100:
+		case 100: //give 1000 exp
 			{
 				cb->changePrimSkill(heroID,w,vvv);
-				std::vector<SComponent*> weko;
-				weko.push_back(new SComponent(SComponent::experience,0,vvv));
-				cb->showInfoDialog(cb->getHeroOwner(heroID),CGI->objh->advobtxt[ot],&weko);
-				//for (int ii=0; ii<weko.size();ii++)
-				//	delete weko[ii];
+				InfoWindow iw;
+				iw.components.push_back(Component(0,4,vvv,0));
+				iw.player = cb->getHeroOwner(heroID);
+				iw.text << std::pair<ui8,ui32>(11,ot);
+				cb->showInfoDialog(&iw);
 				break;
 			}
 		}
@@ -295,7 +302,10 @@ void CVisitableOPH::onNAHeroVisit(CGObjectInstance *os, int heroID, bool already
 	else
 	{
 		ot++;
-		cb->showInfoDialog(cb->getHeroOwner(heroID),CGI->objh->advobtxt[ot],&std::vector<SComponent*>());
+		InfoWindow iw;
+		iw.player = cb->getHeroOwner(heroID);
+		iw.text << std::pair<ui8,ui32>(11,ot);
+		cb->showInfoDialog(&iw);
 	}
 }
 
@@ -310,49 +320,9 @@ std::vector<int> CVisitableOPH::yourObjects()
 	return ret;
 }
 
-std::string CVisitableOPH::hoverText(CGObjectInstance *os)
-{
-	std::string add;
-	int pom;
-	switch(os->ID)
-	{
-	case 51:
-		pom = 8;
-		break;
-	case 23:
-		pom = 7;
-		break;
-	case 61:
-		pom = 11;
-		break;
-	case 32:
-		pom = 4;
-		break;
-	case 100:
-		pom = 5;
-		break;
-	default:
-#ifndef __GNUC__
-		throw new std::exception("Unsupported ID in CVisitableOPH::hoverText");
-#else
-		throw std::exception();
-#endif
-	}
-	add = " " + CGI->objh->xtrainfo[pom] + " ";
-	int heroID = cb->getSelectedHero();
-	if (heroID>=0)
-	{
-		add += ( (visitors[os].find(heroID) == visitors[os].end())
-				?
-			(CGI->generaltexth->allTexts[353])  //not visited
-				:
-			( CGI->generaltexth->allTexts[352]) ); //visited
-	}
-	return CGI->objh->objects[os->defInfo->id].name + add;
-}
-
-void CVisitableOPW::onNAHeroVisit(CGObjectInstance *os, int heroID, bool alreadyVisited)
+void CVisitableOPW::onNAHeroVisit(int objid, int heroID, bool alreadyVisited)
 {
+	DEFOS;
 	int mid;
 	switch (os->ID)
 	{
@@ -370,14 +340,18 @@ void CVisitableOPW::onNAHeroVisit(CGObjectInstance *os, int heroID, bool already
 	{
 		if (os->ID!=112)
 			mid++;
-		else
+		else 
 			mid--;
-		cb->showInfoDialog(cb->getHeroOwner(heroID),CGI->objh->advobtxt[mid],&std::vector<SComponent*>()); //TODO: maybe we have memory leak with these windows
+
+		InfoWindow iw;
+		iw.player = cb->getHero(heroID)->tempOwner;
+		iw.text << std::pair<ui8,ui32>(11,mid);
+		cb->showInfoDialog(&iw);
 	}
 	else
 	{
 		int type, sub, val;
-		type = SComponent::resource;
+		type = 2;
 		switch (os->ID)
 		{
 		case 55:
@@ -405,35 +379,48 @@ void CVisitableOPW::onNAHeroVisit(CGObjectInstance *os, int heroID, bool already
 			else
 				val = 1000;
 		}
-		SComponent * com = new SComponent((SComponent::Etype)type,sub,val);
-		std::vector<SComponent*> weko;
-		weko.push_back(com);
-		cb->giveResource(cb->getHeroOwner(heroID),sub,val);
-		cb->showInfoDialog(cb->getHeroOwner(heroID),CGI->objh->advobtxt[mid],&weko);
-		visited[os] = true;
+		int player = cb->getHeroOwner(heroID);
+		cb->giveResource(player,sub,val);
+		InfoWindow iw;
+		iw.player = player;
+		iw.components.push_back(Component(type,sub,val,0));
+		iw.text << std::pair<ui8,ui32>(11,mid);
+		cb->showInfoDialog(&iw);
+		visited[objid] = true;
+		MetaString ms; //set text to "visited"
+		ms << std::pair<ui8,ui32>(3,os->ID) << " " << std::pair<ui8,ui32>(1,352);
+		cb->setHoverName(objid,&ms);
 	}
 }
 void CVisitableOPW::newTurn ()
 {
-	if (cb->getDate(1)==1)
+	if (cb->getDate(1)==1) //first day of week
 	{
-		for (std::map<CGObjectInstance*,bool>::iterator i = visited.begin(); i != visited.end(); i++)
+		for (std::map<int,bool>::iterator i = visited.begin(); i != visited.end(); i++)
 		{
 			(*i).second = false;
+			MetaString ms; //set text to "not visited"
+			ms << std::pair<ui8,ui32>(3,cb->getObj(i->first)->ID) << " " << std::pair<ui8,ui32>(1,353);
+			cb->setHoverName(i->first,&ms);
 		}
+
 	}
-}
-void CVisitableOPW::newObject(CGObjectInstance *os)
+} 
+void CVisitableOPW::newObject(int objid)
 {
-	visited.insert(std::pair<CGObjectInstance*,bool>(os,false));
+	visited.insert(std::pair<int,bool>(objid,false));
+	DEFOS;
+	MetaString ms;
+	ms << std::pair<ui8,ui32>(3,os->ID) << " " << std::pair<ui8,ui32>(1,visited[objid] ? 352 : 353);
+	cb->setHoverName(objid,&ms);
 }
 
-void CVisitableOPW::onHeroVisit(CGObjectInstance *os, int heroID)
+void CVisitableOPW::onHeroVisit(int objid, int heroID)
 {
-	if(visited[os])
-		onNAHeroVisit(os,heroID,true);
-	else
-		onNAHeroVisit(os,heroID,false);
+	if(visited[objid])
+		onNAHeroVisit(objid,heroID,true);
+	else 
+		onNAHeroVisit(objid,heroID,false);
 }
 
 std::vector<int> CVisitableOPW::yourObjects() //returns IDs of objects which are handled by script
@@ -445,75 +432,88 @@ std::vector<int> CVisitableOPW::yourObjects() //returns IDs of objects which are
 	return ret;
 }
 
-std::string CVisitableOPW::hoverText(CGObjectInstance *os)
+void CMines::newObject(int objid)
 {
-	return CGI->objh->objects[os->defInfo->id].name + " " + ( (visited[os]) ? (CGI->generaltexth->allTexts[352]) : (CGI->generaltexth->allTexts[353]))  ;
+	ourObjs.push_back(objid);
+	cb->setOwner(objid,NEUTRAL_PLAYER);
+	DEFOS;
+	MetaString ms;
+	ms << std::pair<ui8,ui32>(3,os->ID);
+	cb->setHoverName(objid,&ms);
 }
-
-void CMines::newObject(CGObjectInstance *os)
+void CMines::onHeroVisit(int objid, int heroID)
 {
-	ourObjs.push_back(os);
-	os->tempOwner = NEUTRAL_PLAYER;
-}
-void CMines::onHeroVisit(CGObjectInstance *os, int heroID)
-{
-	int vv = 1;
+	//TODO: this is code for standard mines, no support for abandoned mine (subId==7)
+	DEFOS;
+	const CGHeroInstance *h = cb->getHero(heroID);
+	if(h->tempOwner == os->tempOwner)
+		return; //TODO: leaving garrison
+	cb->setOwner(objid,h->tempOwner);
+	MetaString ms;
+	ms << std::pair<ui8,ui32>(9,os->subID) << " " << std::pair<ui8,ui32>(6,23+h->tempOwner);
+	cb->setHoverName(objid,&ms);
+	ms.clear();
+
+	int vv=1; //amount of resource per turn	
 	if (os->subID==0 || os->subID==2)
 		vv++;
 	else if (os->subID==6)
 		vv = 1000;
-	if (os->tempOwner == cb->getHeroOwner(heroID))
-	{
-		//TODO: garrison
-	}
-	else
-	{
-		if (os->subID==7)
-			return; //TODO: support for abandoned mine
-		os->tempOwner = cb->getHeroOwner(heroID);
-		SComponent * com = new SComponent(SComponent::resource,os->subID,vv);
-		com->subtitle+=CGI->generaltexth->allTexts[3].substr(2,CGI->generaltexth->allTexts[3].length()-2);
-		std::vector<SComponent*> weko;
-		weko.push_back(com);
-		cb->showInfoDialog(cb->getHeroOwner(heroID),CGI->objh->mines[os->subID].second,&weko);
-	}
+
+	InfoWindow iw;
+	iw.text << std::pair<ui8,ui32>(10,os->subID);
+	iw.player = h->tempOwner;
+	iw.components.push_back(Component(2,os->subID,vv,-1));
+	cb->showInfoDialog(&iw);
 }
 std::vector<int> CMines::yourObjects()
 {
-	std::vector<int> ret(1);
+	std::vector<int> ret;
 	ret.push_back(53);
 	return ret;
 }
-std::string CMines::hoverText(CGObjectInstance *os)
-{
-	if (os->tempOwner == NEUTRAL_PLAYER)
-		return CGI->objh->mines[os->subID].first;
-	else
-		return CGI->objh->mines[os->subID].first + " " + CGI->generaltexth->arraytxt[23+os->tempOwner];
-
-}
 void CMines::newTurn ()
 {
-	for (int i=0;i<ourObjs.size();i++)
+	const CGObjectInstance * obj;
+	for (unsigned i=0;i<ourObjs.size();i++)
 	{
-		if (ourObjs[i]->tempOwner == NEUTRAL_PLAYER)
+		obj = cb->getObj(ourObjs[i]);
+		if (obj->tempOwner == NEUTRAL_PLAYER)
 			continue;
 		int vv = 1;
-		if (ourObjs[i]->subID==0 || ourObjs[i]->subID==2)
+		if (obj->subID==0 || obj->subID==2)
 			vv++;
-		else if (ourObjs[i]->subID==6)
+		else if (obj->subID==6)
 			vv = 1000;
-		cb->giveResource(ourObjs[i]->tempOwner,ourObjs[i]->subID,vv);
+		cb->giveResource(obj->tempOwner,obj->subID,vv);
 	}
 }
 
 
-void CPickable::newObject(CGObjectInstance *os)
+void CPickable::newObject(int objid)
 {
-	os->blockVisit = true;
+	cb->setBlockVis(objid,true);
+
+	MetaString ms;
+	DEFOS;
+	switch (os->ID)
+	{
+	case 79:
+		ms << std::pair<ui8,ui32>(4,os->subID);
+		break;
+	case 5:
+		ms << std::pair<ui8,ui32>(5,os->subID);
+		break;
+	default:
+		ms << std::pair<ui8,ui32>(3,os->ID);
+		break;
+	}
+
+	cb->setHoverName(objid,&ms);
 }
-void CPickable::onHeroVisit(CGObjectInstance *os, int heroID)
+void CPickable::onHeroVisit(int objid, int heroID)
 {
+	DEFOS;
 	switch(os->ID)
 	{
 	case 5:
@@ -544,92 +544,81 @@ void CPickable::onHeroVisit(CGObjectInstance *os, int heroID)
 				}
 			}
 			if(t2->message.length())
-				cb->showInfoDialog(cb->getHeroOwner(heroID),t2->message,&std::vector<SComponent*>());
-			SComponent ccc(SComponent::resource,os->subID,val);
-			ccc.description = CGI->objh->advobtxt[113];
-			boost::algorithm::replace_first(ccc.description,"%s",CGI->objh->restypes[os->subID]);
+			{
+				InfoWindow iw;
+				iw.player = cb->getHero(heroID)->tempOwner;
+				iw.text << t2->message;
+				cb->showInfoDialog(&iw);
+			}
+
 			cb->giveResource(cb->getHeroOwner(heroID),os->subID,val);
-			cb->showCompInfo(cb->getHeroOwner(heroID),&ccc);
+
+			ShowInInfobox sii;
+			sii.player = cb->getHeroOwner(heroID);
+			sii.c = Component(2,os->subID,val,0);
+			sii.text << std::pair<ui8,ui32>(11,113);
+			sii.text.replacements.push_back(VLC->objh->restypes[os->subID]);
+			cb->showCompInfo(&sii);
 			break;
 		}
 	case 101:
 		{
-			if (os->subID)
-				break; //not OH3 treasure chest
-			int wyn = rand()%100;
-			if (wyn<32)
-			{
-				tempStore.push_back(new CSelectableComponent(SComponent::resource,6,1000));
-				tempStore.push_back(new CSelectableComponent(SComponent::experience,0,500));
-			}//1k/0.5k
-			else if(wyn<64)
-			{
-				tempStore.push_back(new CSelectableComponent(SComponent::resource,6,1500));
-				tempStore.push_back(new CSelectableComponent(SComponent::experience,0,1000));
-			}//1.5k/1k
-			else if(wyn<95)
-			{
-				tempStore.push_back(new CSelectableComponent(SComponent::resource,6,2000));
-				tempStore.push_back(new CSelectableComponent(SComponent::experience,0,1500));
-			}//2k/1.5k
-			else
-			{
-				if (1/*TODO: backpack is full*/)
-				{
-					tempStore.push_back(new CSelectableComponent(SComponent::resource,6,1000));
-					tempStore.push_back(new CSelectableComponent(SComponent::experience,0,500));
-				}
-				else
-				{
-					//TODO: give treasure artifact
-					break;
-				}
-			}//random treasure artifact, or (if backapack is full) 1k/0.5k
-			tempStore[1]->ID = heroID;
-			player = cb->getHeroOwner(heroID);
-			cb->showSelDialog(player,CGI->objh->advobtxt[146],&tempStore,this);
+			//if (os->subID)
+			//	break; //not OH3 treasure chest
+			//int wyn = rand()%100;
+			//if (wyn<32)
+			//{
+			//	tempStore.push_back(new CSelectableComponent(SComponent::resource,6,1000));
+			//	tempStore.push_back(new CSelectableComponent(SComponent::experience,0,500));
+			//}//1k/0.5k
+			//else if(wyn<64)
+			//{
+			//	tempStore.push_back(new CSelectableComponent(SComponent::resource,6,1500));
+			//	tempStore.push_back(new CSelectableComponent(SComponent::experience,0,1000));
+			//}//1.5k/1k
+			//else if(wyn<95)
+			//{
+			//	tempStore.push_back(new CSelectableComponent(SComponent::resource,6,2000));
+			//	tempStore.push_back(new CSelectableComponent(SComponent::experience,0,1500));
+			//}//2k/1.5k
+			//else
+			//{
+			//	if (1/*TODO: backpack is full*/)
+			//	{
+			//		tempStore.push_back(new CSelectableComponent(SComponent::resource,6,1000));
+			//		tempStore.push_back(new CSelectableComponent(SComponent::experience,0,500));
+			//	}
+			//	else
+			//	{
+			//		//TODO: give treasure artifact
+			//		break;
+			//	}
+			//}//random treasure artifact, or (if backapack is full) 1k/0.5k
+			//tempStore[1]->ID = heroID;
+			//player = cb->getHeroOwner(heroID);
+			//cb->showSelDialog(player,VLC->objh->advobtxt[146],&tempStore,this);
 			break;
 		}
 	}
-	CGI->mh->removeObject(os);
+	//VLC->mh->removeObject(os);
 }
 void CPickable::chosen(int which)
 {
-	switch(tempStore[which]->type)
-	{
-	case SComponent::resource:
-		cb->giveResource(player,tempStore[which]->subtype,tempStore[which]->val);
-		break;
-	case SComponent::experience:
-		cb->changePrimSkill(tempStore[which]->ID,4,tempStore[which]->val);
-		break;
-	default:
-#ifndef __GNUC__
-		throw new std::exception("Unhandled choice");
-#else
-		throw std::exception();
-#endif
-
-	}
-	for (int i=0;i<tempStore.size();i++)
-		delete tempStore[i];
-	tempStore.clear();
-}
-
-std::string CPickable::hoverText(CGObjectInstance *os)
-{
-	switch (os->ID)
-	{
-	case 79:
-		return CGI->objh->restypes[os->subID];
-		break;
-	case 5:
-		return CGI->arth->artifacts[os->subID].name;
-		break;
-	default:
-		return CGI->objh->objects[os->defInfo->id].name;
-		break;
-	}
+	//switch(tempStore[which]->type)
+	//{
+	//case SComponent::resource:
+	//	cb->giveResource(player,tempStore[which]->subtype,tempStore[which]->val);
+	//	break;
+	//case SComponent::experience:
+	//	cb->changePrimSkill(tempStore[which]->ID,4,tempStore[which]->val);
+	//	break;
+	//default:
+	//	throw new std::exception("Unhandled choice");
+	//	
+	//}
+	//for (int i=0;i<tempStore.size();i++)
+	//	delete tempStore[i];
+	//tempStore.clear();
 }
 
 std::vector<int> CPickable::yourObjects() //returns IDs of objects which are handled by script
@@ -641,20 +630,22 @@ std::vector<int> CPickable::yourObjects() //returns IDs of objects which are han
 	return ret;
 }
 
-void CTownScript::onHeroVisit(CGObjectInstance *os, int heroID)
+void CTownScript::onHeroVisit(int objid, int heroID)
 {
-	cb->heroVisitCastle(os,heroID);
+	cb->heroVisitCastle(objid,heroID);
 }
-void CTownScript::onHeroLeave(CGObjectInstance *os, int heroID)
+
+void CTownScript::newObject(int objid)
 {
-	cb->stopHeroVisitCastle(os,heroID);
+	MetaString ms;
+	const CGTownInstance * n = cb->getTown(objid);
+	ms << n->name << ", " << n->town->name;
+	cb->setHoverName(objid,&ms);
 }
-std::string CTownScript::hoverText(CGObjectInstance *os)
+
+void CTownScript::onHeroLeave(int objid, int heroID)
 {
-	CGTownInstance * n;
-	if(n = dynamic_cast<CGTownInstance*>(os))
-		return n->name + ", " + n->town->name;
-	else return "";
+	cb->stopHeroVisitCastle(objid,heroID);
 }
 
 std::vector<int> CTownScript::yourObjects() //returns IDs of objects which are handled by script
@@ -664,27 +655,33 @@ std::vector<int> CTownScript::yourObjects() //returns IDs of objects which are h
 	return ret;
 }
 
-void CHeroScript::newObject(CGObjectInstance *os)
+void CHeroScript::newObject(int objid)
 {
-	os->blockVisit = true;
-	heroes.insert(std::pair<int,CGObjectInstance*>(os->subID,os));
+	cb->setBlockVis(objid,true);
+	MetaString ms;
+	ms << std::pair<ui8,ui32>(1,15);
+	ms.replacements.push_back(cb->getHero(objid)->name);
+	ms.replacements.push_back(cb->getHero(objid)->type->heroClass->name);
+	cb->setHoverName(objid,&ms);
 }
 
-void CHeroScript::onHeroVisit(CGObjectInstance *os, int heroID)
+void CHeroScript::onHeroVisit(int objid, int heroID)
 {
 	//TODO: check for allies
-	if(static_cast<CGHeroInstance*>(heroes[heroID])->tempOwner == static_cast<CGHeroInstance*>(os)->tempOwner) //one of allied cases
+	const CGHeroInstance *my = cb->getHero(objid), 
+		*vis = cb->getHero(objid);
+	if(my->tempOwner == vis->tempOwner) //one of allied cases
 	{
 		//exchange
 	}
 	else
 	{
 		cb->startBattle(
-			&(static_cast<CGHeroInstance*>(heroes[heroID]))->army,
-			&(static_cast<CGHeroInstance*>(os))->army,
-			os->pos,
-			static_cast<CGHeroInstance*>(heroes[heroID]),
-			static_cast<CGHeroInstance*>(os));
+			&my->army,
+			&vis->army,
+			my->pos,
+			my,
+			vis);
 	}
 }
 std::vector<int> CHeroScript::yourObjects() //returns IDs of objects which are handled by script
@@ -693,65 +690,58 @@ std::vector<int> CHeroScript::yourObjects() //returns IDs of objects which are h
 	ret.push_back(34); //hero
 	return ret;
 }
-std::string CHeroScript::hoverText(CGObjectInstance *os)
-{
-	CGHeroInstance* h = static_cast<CGHeroInstance*>(os);
-	std::string ret = CGI->generaltexth->allTexts[15];
-	boost::algorithm::replace_first(ret,"%s",h->name);
-	boost::algorithm::replace_first(ret,"%s",h->type->heroClass->name);
-	return ret;
-}
-void CMonsterS::newObject(CGObjectInstance *os)
+void CMonsterS::newObject(int objid)
 {
 	//os->blockVisit = true;
-	switch(CGI->creh->creatures[os->subID].level)
+	DEFOS;
+	switch(VLC->creh->creatures[os->subID].level)
 	{
 	case 1:
-		((CCreatureObjInfo*)os->info)->number = rand()%31+20;
+		amounts[objid] = rand()%31+20;
 		break;
 	case 2:
-		((CCreatureObjInfo*)os->info)->number = rand()%16+15;
+		amounts[objid] = rand()%16+15;
 		break;
 	case 3:
-		((CCreatureObjInfo*)os->info)->number = rand()%16+10;
+		amounts[objid] = rand()%16+10;
 		break;
 	case 4:
-		((CCreatureObjInfo*)os->info)->number = rand()%11+10;
+		amounts[objid] = rand()%11+10;
 		break;
 	case 5:
-		((CCreatureObjInfo*)os->info)->number = rand()%9+8;
+		amounts[objid] = rand()%9+8;
 		break;
 	case 6:
-		((CCreatureObjInfo*)os->info)->number = rand()%8+5;
+		amounts[objid] = rand()%8+5;
 		break;
 	case 7:
-		((CCreatureObjInfo*)os->info)->number = rand()%7+3;
+		amounts[objid] = rand()%7+3;
 		break;
 	case 8:
-		((CCreatureObjInfo*)os->info)->number = rand()%4+2;
+		amounts[objid] = rand()%4+2;
 		break;
 	case 9:
-		((CCreatureObjInfo*)os->info)->number = rand()%3+2;
+		amounts[objid] = rand()%3+2;
 		break;
 	case 10:
-		((CCreatureObjInfo*)os->info)->number = rand()%3+1;
+		amounts[objid] = rand()%3+1;
 		break;
 
 	}
 
-}
-std::string CMonsterS::hoverText(CGObjectInstance *os)
-{
-	int pom = CCreature::getQuantityID(((CCreatureObjInfo*)os->info)->number);
+	MetaString ms;
+	int pom = CCreature::getQuantityID(amounts[objid]);
 	pom = 174 + 3*pom + 1;
-	return CGI->generaltexth->arraytxt[pom] + " " + CGI->creh->creatures[os->subID].namePl;
+	ms << std::pair<ui8,ui32>(6,pom) << " " << std::pair<ui8,ui32>(7,os->subID);
+	cb->setHoverName(objid,&ms);
 }
-void CMonsterS::onHeroVisit(CGObjectInstance *os, int heroID)
+void CMonsterS::onHeroVisit(int objid, int heroID)
 {
+	DEFOS;
 	CCreatureSet set;
 	//TODO: zrobic secik w sposob wyrafinowany
-	set.slots[0] = std::pair<CCreature*,int>(&CGI->creh->creatures[os->subID],((CCreatureObjInfo*)os->info)->number);
-	cb->startBattle(heroID,&set,os->pos);
+	set.slots[0] = std::pair<ui32,si32>(os->subID,amounts[objid]);
+	cb->startBattle(heroID,set,os->pos);
 }
 std::vector<int> CMonsterS::yourObjects() //returns IDs of objects which are handled by script
 {
@@ -761,15 +751,15 @@ std::vector<int> CMonsterS::yourObjects() //returns IDs of objects which are han
 }
 
 
-void CCreatureGen::newObject(CGObjectInstance *os)
-{
-	amount[os] = CGI->creh->creatures[CGI->objh->cregens[os->subID]].growth;
-}
-std::string CCreatureGen::hoverText(CGObjectInstance *os)
+void CCreatureGen::newObject(int objid)
 {
-	return CGI->objh->creGens[os->subID];
+	DEFOS;
+	amount[objid] = VLC->creh->creatures[VLC->objh->cregens[os->subID]].growth;
+	MetaString ms;
+	ms << std::pair<ui8,ui32>(8,os->subID);
+	cb->setHoverName(objid,&ms);
 }
-void CCreatureGen::onHeroVisit(CGObjectInstance *os, int heroID)
+void CCreatureGen::onHeroVisit(int objid, int heroID)
 {
 }
 std::vector<int> CCreatureGen::yourObjects() //returns IDs of objects which are handled by script

+ 44 - 63
CLua.h

@@ -1,12 +1,11 @@
 #pragma once
 #include "global.h"
 
-
 #ifndef _MSC_VER
 extern "C" {
 #endif
 
-#include "lstate.h"
+//#include "lstate.h"
 
 #ifndef _MSC_VER
 }
@@ -22,6 +21,9 @@ class CGHeroInstance;
 class CScriptCallback;
 class SComponent;
 class CSelectableComponent;
+class CGameState;
+struct Mapa;
+struct lua_State;
 enum ESLan{UNDEF=-1,CPP,ERM,LUA};
 class CObjectScript
 {
@@ -36,10 +38,10 @@ public:
 
 	//functions to be called in script
 	//virtual void init(){};
-	virtual void newObject(CGObjectInstance *os){};
-	virtual void onHeroVisit(CGObjectInstance *os, int heroID){};
-	virtual void onHeroLeave(CGObjectInstance *os, int heroID){};
-	virtual std::string hoverText(CGObjectInstance *os){return "";};
+	virtual void newObject(int objid){};
+	virtual void onHeroVisit(int objid, int heroID){};
+	virtual void onHeroLeave(int objid, int heroID){};
+	virtual std::string hoverText(int objid){return "";};
 	virtual void newTurn (){};
 
 
@@ -80,7 +82,7 @@ public:
 	void findFS(std::string fname);
 
 
-	friend void initGameState(CGameInfo * cgi);
+	friend class CGameState;
 };
 
 class CLuaObjectScript : public CLua, public CObjectScript
@@ -91,122 +93,101 @@ public:
 	static std::string genFN(std::string base, int ID);
 
 	void init();
-	void newObject(CGObjectInstance *os);
-	void onHeroVisit(CGObjectInstance *os, int heroID);
-	std::string hoverText(CGObjectInstance *os);
-
-	friend void initGameState(CGameInfo * cgi);
+	void newObject(int objid);
+	void onHeroVisit(int objid, int heroID);
 };
 class CCPPObjectScript: public CObjectScript
 {
-protected:
+public:
 	CScriptCallback * cb;
 	CCPPObjectScript(CScriptCallback * CB){cb=CB;};
-public:
 	virtual std::vector<int> yourObjects()=0; //returns IDs of objects which are handled by script
-	virtual std::string hoverText(CGObjectInstance *os);
 };
 class CVisitableOPH : public CCPPObjectScript  //once per hero
 {
+public:
 	CVisitableOPH(CScriptCallback * CB):CCPPObjectScript(CB){};
-	std::map<CGObjectInstance*,std::set<int> > visitors;
+	std::map<int,std::set<int> > visitors;
 
-	void onNAHeroVisit(CGObjectInstance *os, int heroID, bool alreadyVisited);
-	void newObject(CGObjectInstance *os);
-	void onHeroVisit(CGObjectInstance *os, int heroID);
+	void onNAHeroVisit(int objid, int heroID, bool alreadyVisited);
+	void newObject(int objid);
+	void onHeroVisit(int objid, int heroID);
 	std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
-	std::string hoverText(CGObjectInstance *os);
-
-	friend void initGameState(CGameInfo * cgi);
 };
 
 class CVisitableOPW : public CCPPObjectScript  //once per week
 {
+public:
 	CVisitableOPW(CScriptCallback * CB):CCPPObjectScript(CB){};
-	std::map<CGObjectInstance*,bool> visited;
-	void onNAHeroVisit(CGObjectInstance *os, int heroID, bool alreadyVisited);
-	void newObject(CGObjectInstance *os);
-	void onHeroVisit(CGObjectInstance *os, int heroID);
+	std::map<int,bool> visited;
+	void onNAHeroVisit(int objid, int heroID, bool alreadyVisited);
+	void newObject(int objid);
+	void onHeroVisit(int objid, int heroID);
 	std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
-	std::string hoverText(CGObjectInstance *os);
 	void newTurn ();
-
-	friend void initGameState(CGameInfo * cgi);
 };
 
 class CMines : public CCPPObjectScript  //flaggable, and giving resource at each day
 {
+public:
 	CMines(CScriptCallback * CB):CCPPObjectScript(CB){};
 
-	std::vector<CGObjectInstance*> ourObjs;
+	std::vector<int> ourObjs;
 
-	void newObject(CGObjectInstance *os);
-	void onHeroVisit(CGObjectInstance *os, int heroID);
+	void newObject(int objid);
+	void onHeroVisit(int objid, int heroID);
 	std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
-	std::string hoverText(CGObjectInstance *os);
 	void newTurn ();
-
-	friend void initGameState(CGameInfo * cgi);
 };
 
 class CPickable : public CCPPObjectScript, public IChosen  //pickable - resources, artifacts, etc
 {
+public:
 	std::vector<CSelectableComponent*> tempStore;
 	int player;
 
 	CPickable(CScriptCallback * CB):CCPPObjectScript(CB){};
 	void chosen(int which);
-	void newObject(CGObjectInstance *os);
-	void onHeroVisit(CGObjectInstance *os, int heroID);
-	std::string hoverText(CGObjectInstance *os);
+	void newObject(int objid);
+	void onHeroVisit(int objid, int heroID);
 	std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
-
-	friend void initGameState(CGameInfo * cgi);
 };
 
 class CTownScript : public CCPPObjectScript  //pickable - resources, artifacts, etc
 {
+public:
 	CTownScript(CScriptCallback * CB):CCPPObjectScript(CB){};
-	void onHeroVisit(CGObjectInstance *os, int heroID);
-	void onHeroLeave(CGObjectInstance *os, int heroID);
-	std::string hoverText(CGObjectInstance *os);
+	void onHeroVisit(int objid, int heroID);
+	void onHeroLeave(int objid, int heroID);
+	void newObject(int objid);
 	std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
-
-	friend void initGameState(CGameInfo * cgi);
 };
 
 class CHeroScript : public CCPPObjectScript
 {
-	std::map<int, CGObjectInstance*> heroes;
+public:
 	CHeroScript(CScriptCallback * CB):CCPPObjectScript(CB){};
-	void newObject(CGObjectInstance *os);
-	void onHeroVisit(CGObjectInstance *os, int heroID);
+	void newObject(int objid);
+	void onHeroVisit(int objid, int heroID);
 	std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
-	std::string hoverText(CGObjectInstance *os);
-
-	friend void initGameState(CGameInfo * cgi);
 };
 
 class CMonsterS : public CCPPObjectScript
 {
-	std::map<int, CGObjectInstance*> heroes;
+public:
+	std::map<int, int> amounts; //monster id -> stack quantity
 	CMonsterS(CScriptCallback * CB):CCPPObjectScript(CB){};
-	void newObject(CGObjectInstance *os);
-	std::string hoverText(CGObjectInstance *os);
-	void onHeroVisit(CGObjectInstance *os, int heroID);
+	void newObject(int objid);
+	void onHeroVisit(int objid, int heroID);
 	std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
-
-	friend void initGameState(CGameInfo * cgi);
 };
 
 class CCreatureGen : public CCPPObjectScript
 {
-	std::map<CGObjectInstance*, int> amount; //amount of creatures in each dwelling
+public:
+	std::map<int, int> amount; //amount of creatures in each dwelling
 	CCreatureGen(CScriptCallback * CB):CCPPObjectScript(CB){};
-	void newObject(CGObjectInstance *os);
-	std::string hoverText(CGObjectInstance *os);
-	void onHeroVisit(CGObjectInstance *os, int heroID);
+	void newObject(int objid);
+	void onHeroVisit(int objid, int heroID);
 	std::vector<int> yourObjects(); //returns IDs of objects which are handled by script
-
-	friend void initGameState(CGameInfo * cgi);
 };

+ 41 - 41
CLuaHandler.cpp

@@ -32,45 +32,45 @@ CLuaHandler::~CLuaHandler()
 }
 void CLuaHandler::test()
 {
-	int iErr = 0;
-	lua_State *lua = lua_open ();  // Open Lua
-	LUA_OPEN_LIB(lua, luaopen_base);
-	LUA_OPEN_LIB(lua, luaopen_io);
-
-	//luabind::open(lua);
-	//luabind::module(lua)
-	//[
-	//	luabind::class_<int3>("int3")
-	//		//.def(luabind::constructor<>())
-	//		//.def(luabind::constructor<const int&,const int&,const int&>())
-	//		.def_readwrite("x", &int3::x)
-	//		.def_readwrite("y", &int3::y)
-	//		.def_readwrite("z", &int3::z)
-	//];
-	//luabind::module(lua)
-	//[
-	//	luabind::def("powitanie",&piszpowitanie2)
-	//];
-
-
-	if ((iErr = luaL_loadfile (lua, "scripts/lua/objects/0023_marletto_tower.lua")) == 0)
-	{
-	   // Call main...
-	   if ((iErr = lua_pcall (lua, 0, LUA_MULTRET, 0)) == 0)
-	   {
-
-			//int ret = luabind::call_function<int>(lua, "helloWorld2");
-			//lua_pushstring (lua, "helloWorld2");
-			//lua_gettable (lua, LUA_GLOBALSINDEX);
-			//lua_pcall (lua, 0, 0, 0);
-
-			// Push the function name onto the stack
-			lua_pushstring (lua, "rightText");
-			lua_gettable (lua, LUA_GLOBALSINDEX);
-			lua_pcall (lua, 0, 0, 0);
-		}
-	}
-	lua_close (lua);
+	//int iErr = 0;
+	//lua_State *lua = lua_open ();  // Open Lua
+	//LUA_OPEN_LIB(lua, luaopen_base);
+	//LUA_OPEN_LIB(lua, luaopen_io);
+	//if ((iErr = luaL_loadfile (lua, "scripts/lua/objects/0023_marletto_tower.lua")) == 0)
+	//{
+	//   // Call main...
+	//   if ((iErr = lua_pcall (lua, 0, LUA_MULTRET, 0)) == 0)
+	//   {    
+	//		lua_pushstring (lua, "rightText");
+	//		lua_gettable (lua, LUA_GLOBALSINDEX);  
+	//		lua_pcall (lua, 0, 0, 0);
+	//	}
+	//}
+	//lua_close (lua);
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
 }
 
 
@@ -82,10 +82,10 @@ std::vector<std::string> * CLuaHandler::searchForScripts(std::string fol)
 #ifndef __GNUC__
 		throw new std::exception("No such folder!");
 #else
-		throw std::exception();
+		throw new std::exception();
 #endif
 	boost::filesystem::directory_iterator end_itr;
-	for
+	for 
 	  (
 	  boost::filesystem::directory_iterator it(folder);
 	  it!=end_itr;

+ 131 - 877
CMT.cpp

@@ -1,45 +1,22 @@
 // CMT.cpp : Defines the entry point for the console application.
 //
 #include "stdafx.h"
-#include "SDL.h"
-#include "SDL_ttf.h"
-#include "hch/CVideoHandler.h"
-#include "SDL_mixer.h"
-#include "hch/CBuildingHandler.h"
-#include "SDL_Extensions.h"
-#include "SDL_framerate.h"
 #include <cmath>
-#include <stdio.h>
-#include <string.h>
 #include <string>
-#include <assert.h>
 #include <vector>
-#include "zlib.h"
+#include <queue>
 #include <cmath>
-#include <ctime>
-#include "hch/CArtHandler.h"
-#include "hch/CHeroHandler.h"
-#include "hch/CCreatureHandler.h"
-#include "hch/CAbilityHandler.h"
-#include "hch/CSpellHandler.h"
-#include "hch/CBuildingHandler.h"
-#include "hch/CObjectHandler.h"
+#include <boost/thread.hpp>
+#include "SDL_ttf.h"
+#include "SDL_mixer.h"
+#include "SDL_Extensions.h"
+#include "SDL_framerate.h"
 #include "CGameInfo.h"
-#include "hch/CMusicHandler.h"
-#include "hch/CSemiLodHandler.h"
-#include "hch/CLodHandler.h"
-#include "hch/CDefHandler.h"
-#include "hch/CSndHandler.h"
-#include "hch/CTownHandler.h"
-#include "hch/CDefObjInfoHandler.h"
-#include "hch/CAmbarCendamo.h"
 #include "mapHandler.h"
 #include "global.h"
 #include "CPreGame.h"
-#include "hch/CGeneralTextHandler.h"
 #include "CConsoleHandler.h"
 #include "CCursorHandler.h"
-#include "CScreenHandler.h"
 #include "CPathfinder.h"
 #include "CGameState.h"
 #include "CCallback.h"
@@ -47,899 +24,176 @@
 #include "CLuaHandler.h"
 #include "CLua.h"
 #include "CAdvmapInterface.h"
-#include "CCastleInterface.h"
-#include "boost/filesystem/operations.hpp"
-#include <boost/algorithm/string.hpp>
-#include <boost/algorithm/string/replace.hpp>
-#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__)
-#  include <fcntl.h>
-#  include <io.h>
-#  define SET_BINARY_MODE(file) setmode(fileno(file), O_BINARY)
-#else
-#  define SET_BINARY_MODE(file)
-#endif
-#ifdef _DEBUG
-CGameInfo* CGI;
-#endif
-#define CHUNK 16384
-const char * NAME = "VCMI 0.62";
-
-SDL_Color playerColorPalette[256]; //palette to make interface colors good
-
+#include "hch/CBuildingHandler.h"
+#include "hch/CVideoHandler.h"
+#include "hch/CAbilityHandler.h"
+#include "hch/CHeroHandler.h"
+#include "hch/CCreatureHandler.h"
+#include "hch/CSpellHandler.h"
+#include "hch/CMusicHandler.h"
+#include "hch/CLodHandler.h"
+#include "hch/CDefHandler.h"
+#include "hch/CAmbarCendamo.h"
+#include "hch/CGeneralTextHandler.h"
+#include "client/Graphics.h"
+#include "client/Client.h"
+#include "lib/Connection.h"
+#include "lib/VCMI_Lib.h"
+std::string NAME = NAME_VER + std::string(" (client)");
+DLL_EXPORT void initDLL(CLodHandler *b);
 SDL_Surface * screen, * screen2;
 extern SDL_Surface * CSDL_Ext::std32bppSurface;
+std::queue<SDL_Event> events;
+boost::mutex eventsM;
 TTF_Font * TNRB16, *TNR, *GEOR13, *GEORXX, *GEORM, *GEOR16;
-void handleCPPObjS(std::map<int,CCPPObjectScript*> * mapa, CCPPObjectScript * script)
-{
-	std::vector<int> tempv = script->yourObjects();
-	for (int i=0;i<tempv.size();i++)
-	{
-		(*mapa)[tempv[i]]=script;
-	}
-	CGI->state->cppscripts.insert(script);
-}
-void initGameState(CGameInfo * cgi)
-{
-	cgi->state->day=0;
-	/*********creating players entries in gs****************************************/
-	for (int i=0; i<cgi->scenarioOps.playerInfos.size();i++)
-	{
-		std::pair<int,PlayerState> ins(cgi->scenarioOps.playerInfos[i].color,PlayerState());
-		ins.second.color=ins.first;
-		ins.second.serial=i;
-		cgi->state->players.insert(ins);
-	}
-	/******************RESOURCES****************************************************/
-	//TODO: zeby komputer dostawal inaczej niz gracz
-	std::vector<int> startres;
-	std::ifstream tis("config/startres.txt");
-	int k;
-	for (int j=0;j<cgi->scenarioOps.difficulty;j++)
-	{
-		tis >> k;
-		for (int z=0;z<RESOURCE_QUANTITY;z++)
-			tis>>k;
-	}
-	tis >> k;
-	for (int i=0;i<RESOURCE_QUANTITY;i++)
-	{
-		tis >> k;
-		startres.push_back(k);
-	}
-	tis.close();
-	for (std::map<int,PlayerState>::iterator i = cgi->state->players.begin(); i!=cgi->state->players.end(); i++)
-	{
-		(*i).second.resources.resize(RESOURCE_QUANTITY);
-		for (int x=0;x<RESOURCE_QUANTITY;x++)
-			(*i).second.resources[x] = startres[x];
-
-	}
-
-	/*************************HEROES************************************************/
-	for (int i=0; i<cgi->heroh->heroInstances.size();i++) //heroes instances
-	{
-		if (!cgi->heroh->heroInstances[i]->type || cgi->heroh->heroInstances[i]->getOwner()<0)
-			continue;
-		//CGHeroInstance * vhi = new CGHeroInstance();
-		//*vhi=*(cgi->heroh->heroInstances[i]);
-		CGHeroInstance * vhi = (cgi->heroh->heroInstances[i]);
-		vhi->subID = vhi->type->ID;
-		if (vhi->level<1)
-		{
-			vhi->exp=40+rand()%50;
-			vhi->level = 1;
-		}
-		if (vhi->level>1) ;//TODO dodac um dr, ale potrzebne los
-		if ((!vhi->primSkills.size()) || (vhi->primSkills[0]<0))
-		{
-			if (vhi->primSkills.size()<PRIMARY_SKILLS)
-				vhi->primSkills.resize(PRIMARY_SKILLS);
-			vhi->primSkills[0] = vhi->type->heroClass->initialAttack;
-			vhi->primSkills[1] = vhi->type->heroClass->initialDefence;
-			vhi->primSkills[2] = vhi->type->heroClass->initialPower;
-			vhi->primSkills[3] = vhi->type->heroClass->initialKnowledge;
-			vhi->mana = vhi->primSkills[3]*10;
-		}
-		if (!vhi->name.length())
-		{
-			vhi->name = vhi->type->name;
-		}
-		if (!vhi->biography.length())
-		{
-			vhi->biography = vhi->type->biography;
-		}
-		if (vhi->portrait < 0)
-			vhi->portrait = vhi->type->ID;
-
-		//initial army
-		if (!vhi->army.slots.size()) //standard army
-		{
-			int pom, pom2=0;
-			for(int x=0;x<3;x++)
-			{
-				pom = (cgi->creh->nameToID[vhi->type->refTypeStack[x]]);
-				if(pom>=145 && pom<=149) //war machine
-				{
-					pom2++;
-					switch (pom)
-					{
-					case 145: //catapult
-						vhi->artifWorn[16] = &CGI->arth->artifacts[3];
-						break;
-					default:
-						pom-=145;
-						vhi->artifWorn[13+pom] = &CGI->arth->artifacts[4+pom];
-						break;
-					}
-					continue;
-				}
-				vhi->army.slots[x-pom2].first = &(cgi->creh->creatures[pom]);
-				if((pom = (vhi->type->highStack[x]-vhi->type->lowStack[x])) > 0)
-					vhi->army.slots[x-pom2].second = (rand()%pom)+vhi->type->lowStack[x];
-				else
-					vhi->army.slots[x-pom2].second = +vhi->type->lowStack[x];
-			}
-		}
-
-		cgi->state->players[vhi->getOwner()].heroes.push_back(vhi);
-
-	}
-	/*************************FOG**OF**WAR******************************************/
-	for(std::map<int, PlayerState>::iterator k=cgi->state->players.begin(); k!=cgi->state->players.end(); ++k)
-	{
-		k->second.fogOfWarMap.resize(cgi->ac->map.width, Woff);
-		for(int g=-Woff; g<cgi->ac->map.width+Woff; ++g)
-			k->second.fogOfWarMap[g].resize(cgi->ac->map.height, Hoff);
-
-		for(int g=-Woff; g<cgi->ac->map.width+Woff; ++g)
-			for(int h=-Hoff; h<cgi->ac->map.height+Hoff; ++h)
-				k->second.fogOfWarMap[g][h].resize(cgi->ac->map.twoLevel+1, 0);
-
-		for(int g=-Woff; g<cgi->ac->map.width+Woff; ++g)
-			for(int h=-Hoff; h<cgi->ac->map.height+Hoff; ++h)
-				for(int v=0; v<cgi->ac->map.twoLevel+1; ++v)
-					k->second.fogOfWarMap[g][h][v] = 0;
-		for(int xd=0; xd<cgi->ac->map.width; ++xd) //revealing part of map around heroes
-		{
-			for(int yd=0; yd<cgi->ac->map.height; ++yd)
-			{
-				for(int ch=0; ch<k->second.heroes.size(); ++ch)
-				{
-					int deltaX = (k->second.heroes[ch]->getPosition(false).x-xd)*(k->second.heroes[ch]->getPosition(false).x-xd);
-					int deltaY = (k->second.heroes[ch]->getPosition(false).y-yd)*(k->second.heroes[ch]->getPosition(false).y-yd);
-					if(deltaX+deltaY<k->second.heroes[ch]->getSightDistance()*k->second.heroes[ch]->getSightDistance())
-						k->second.fogOfWarMap[xd][yd][k->second.heroes[ch]->getPosition(false).z] = 1;
-				}
-			}
-		}
-	}
-	/****************************TOWNS************************************************/
-	for (int i=0;i<cgi->townh->townInstances.size();i++)
-	{
-		//CGTownInstance * vti = new CGTownInstance();
-		//(*vti)=*(cgi->townh->townInstances[i]);
-		CGTownInstance * vti =(cgi->townh->townInstances[i]);
-		//vti->creatureIncome.resize(CREATURES_PER_TOWN);
-		//vti->creaturesLeft.resize(CREATURES_PER_TOWN);
-		if (vti->name.length()==0) // if town hasn't name we draw it
-			vti->name=vti->town->names[rand()%vti->town->names.size()];
-
-		cgi->state->players[vti->getOwner()].towns.push_back(vti);
-	}
-
-	for(std::map<int, PlayerState>::iterator k=cgi->state->players.begin(); k!=cgi->state->players.end(); ++k)
-	{
-		if(k->first==-1 || k->first==255)
-			continue;
-		for(int xd=0; xd<cgi->ac->map.width; ++xd) //revealing part of map around towns
-		{
-			for(int yd=0; yd<cgi->ac->map.height; ++yd)
-			{
-				for(int ch=0; ch<k->second.towns.size(); ++ch)
-				{
-					int deltaX = (k->second.towns[ch]->pos.x-xd)*(k->second.towns[ch]->pos.x-xd);
-					int deltaY = (k->second.towns[ch]->pos.y-yd)*(k->second.towns[ch]->pos.y-yd);
-					if(deltaX+deltaY<k->second.towns[ch]->getSightDistance()*k->second.towns[ch]->getSightDistance())
-						k->second.fogOfWarMap[xd][yd][k->second.towns[ch]->pos.z] = 1;
-				}
-			}
-		}
-
-		//init visiting heroes
-		for(int l=0; l<k->second.heroes.size();l++)
-		{
-			for(int m=0; m<k->second.towns.size();m++)
-			{
-				int3 vistile = k->second.towns[m]->pos; vistile.x--; //tile next to the entrance
-				if(vistile == k->second.heroes[l]->pos)
-				{
-					k->second.towns[m]->visitingHero = k->second.heroes[l];
-					break;
-				}
-			}
-		}
-	}
-
-	/****************************SCRIPTS************************************************/
-	std::map<int, std::map<std::string, CObjectScript*> > * skrypty = &cgi->state->objscr; //alias for easier access
-	/****************************C++ OBJECT SCRIPTS************************************************/
-	std::map<int,CCPPObjectScript*> scripts;
-	CScriptCallback * csc = new CScriptCallback();
-	csc->gs = cgi->state;
-	handleCPPObjS(&scripts,new CVisitableOPH(csc));
-	handleCPPObjS(&scripts,new CVisitableOPW(csc));
-	handleCPPObjS(&scripts,new CPickable(csc));
-	handleCPPObjS(&scripts,new CMines(csc));
-	handleCPPObjS(&scripts,new CTownScript(csc));
-	handleCPPObjS(&scripts,new CHeroScript(csc));
-	handleCPPObjS(&scripts,new CMonsterS(csc));
-	handleCPPObjS(&scripts,new CCreatureGen(csc));
-	//created map
-
-	/****************************LUA OBJECT SCRIPTS************************************************/
-	std::vector<std::string> * lf = CLuaHandler::searchForScripts("scripts/lua/objects"); //files
-	for (int i=0; i<lf->size(); i++)
-	{
-		try
-		{
-			std::vector<std::string> * temp =  CLuaHandler::functionList((*lf)[i]);
-			CLuaObjectScript * objs = new CLuaObjectScript((*lf)[i]);
-			CLuaCallback::registerFuncs(objs->is);
-			//objs
-			for (int j=0; j<temp->size(); j++)
-			{
-				int obid ; //obj ID
-				int dspos = (*temp)[j].find_first_of('_');
-				obid = atoi((*temp)[j].substr(dspos+1,(*temp)[j].size()-dspos-1).c_str());
-				std::string fname = (*temp)[j].substr(0,dspos);
-				if (skrypty->find(obid)==skrypty->end())
-					skrypty->insert(std::pair<int, std::map<std::string, CObjectScript*> >(obid,std::map<std::string,CObjectScript*>()));
-				(*skrypty)[obid].insert(std::pair<std::string, CObjectScript*>(fname,objs));
-			}
-			delete temp;
-		}HANDLE_EXCEPTION
-	}
-	/****************************INITIALIZING OBJECT SCRIPTS************************************************/
-	std::string temps("newObject");
-	for (int i=0; i<CGI->objh->objInstances.size(); i++)
-	{
-		//c++ scripts
-		if (scripts.find(CGI->objh->objInstances[i]->ID) != scripts.end())
-		{
-			CGI->objh->objInstances[i]->state = scripts[CGI->objh->objInstances[i]->ID];
-			CGI->objh->objInstances[i]->state->newObject(CGI->objh->objInstances[i]);
-		}
-		else
-		{
-			CGI->objh->objInstances[i]->state = NULL;
-		}
-
-		// lua scripts
-		if(cgi->state->checkFunc(CGI->objh->objInstances[i]->ID,temps))
-			(*skrypty)[CGI->objh->objInstances[i]->ID][temps]->newObject(CGI->objh->objInstances[i]);
-	}
-
-	delete lf;
-}
-
 #ifndef __GNUC__
 int _tmain(int argc, _TCHAR* argv[])
 #else
 int main(int argc, _TCHAR* argv[])
 #endif
-{
-	//std::ios_base::sync_with_stdio(0);
+{ 
+	std::cout.flags(ios::unitbuf);
+	std::cout << NAME << std::endl;
+	srand ( time(NULL) );
+	CPG=NULL;
+	atexit(SDL_Quit);
+	CGameInfo * cgi = CGI = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler itp.)
 	//CLuaHandler luatest;
-	//luatest.test();
-
+	//luatest.test(); 
 		//CBIKHandler cb;
 		//cb.open("CSECRET.BIK");
-	THC timeHandler tmh;
-	THC tmh.getDif();
-	timeHandler pomtime;pomtime.getDif();
-	int xx=0, yy=0, zz=0;
-	srand ( time(NULL) );
-	std::vector<SDL_Surface*> Sprites;
+	std::cout << "Starting... " << std::endl;
+	THC timeHandler tmh, total, pomtime;
 	if(SDL_Init(SDL_INIT_VIDEO|SDL_INIT_TIMER|SDL_INIT_AUDIO/*|SDL_INIT_EVENTTHREAD*/)==0)
 	{
-		screen = SDL_SetVideoMode(800,600,24,SDL_SWSURFACE|SDL_DOUBLEBUF/*|SDL_FULLSCREEN*/);
-
-		//initializing important global surface
-#if SDL_BYTEORDER == SDL_BIG_ENDIAN
-		int rmask = 0xff000000;
-		int gmask = 0x00ff0000;
-		int bmask = 0x0000ff00;
-		int amask = 0x000000ff;
-#else
-		int rmask = 0x000000ff;
-		int gmask = 0x0000ff00;
-		int bmask = 0x00ff0000;
-		int amask = 0xff000000;
-#endif
+		screen = SDL_SetVideoMode(800,600,24,SDL_SWSURFACE|SDL_DOUBLEBUF/*|SDL_FULLSCREEN*/);  //initializing important global surface
+		THC std::cout<<"\tInitializing screen: "<<pomtime.getDif()<<std::endl;
+		SDL_WM_SetCaption(NAME.c_str(),""); //set window title
+		#if SDL_BYTEORDER == SDL_BIG_ENDIAN
+			int rmask = 0xff000000;int gmask = 0x00ff0000;int bmask = 0x0000ff00;int amask = 0x000000ff;
+		#else
+			int rmask = 0x000000ff;	int gmask = 0x0000ff00;	int bmask = 0x00ff0000;	int amask = 0xff000000;
+		#endif
 		CSDL_Ext::std32bppSurface = SDL_CreateRGBSurface(SDL_SWSURFACE, 1, 1, 32, rmask, gmask, bmask, amask);
-
-		CPG=NULL;
+		THC std::cout<<"\tInitializing minors: "<<pomtime.getDif()<<std::endl;
 		TTF_Init();
+		TNRB16 = TTF_OpenFont("Fonts\\tnrb.ttf",16);
+		GEOR13 = TTF_OpenFont("Fonts\\georgia.ttf",13);
+		GEOR16 = TTF_OpenFont("Fonts\\georgia.ttf",16);
+		GEORXX = TTF_OpenFont("Fonts\\tnrb.ttf",22);
+		GEORM = TTF_OpenFont("Fonts\\georgia.ttf",10);
 		atexit(TTF_Quit);
-		atexit(SDL_Quit);
-		//TNRB = TTF_OpenFont(DATADIR "Fonts" PATHSEPARATOR "tnrb.ttf",16);
-		TNRB16 = TTF_OpenFont(DATADIR "Fonts" PATHSEPARATOR "tnrb.ttf",16);
-		//TNR = TTF_OpenFont(DATADIR "Fonts" PATHSEPARATOR "tnr.ttf",10);
-		GEOR13 = TTF_OpenFont(DATADIR "Fonts" PATHSEPARATOR "georgia.ttf",13);
-		GEOR16 = TTF_OpenFont(DATADIR "Fonts" PATHSEPARATOR "georgia.ttf",16);
-		GEORXX = TTF_OpenFont(DATADIR "Fonts" PATHSEPARATOR "tnrb.ttf",22);
-		GEORM = TTF_OpenFont(DATADIR "Fonts" PATHSEPARATOR "georgia.ttf",10);
-
+		THC std::cout<<"\tInitializing fonts: "<<pomtime.getDif()<<std::endl;
 		CMusicHandler * mush = new CMusicHandler;  //initializing audio
 		mush->initMusics();
-
-		//audio initialized
-		/*if(Mix_PlayMusic(mush->mainMenuWoG, -1)==-1) //uncomment this fragment to have music
-		{
-			printf("Mix_PlayMusic: %s\n", Mix_GetError());
-			// well, there's no music, but most games don't break without music...
-		}*/
-
-		//screen2 = SDL_SetVideoMode(800,600,24,SDL_SWSURFACE|SDL_DOUBLEBUF/*|SDL_FULLSCREEN*/);
-		//screen = SDL_ConvertSurface(screen2, screen2->format, SDL_SWSURFACE);
-
-		SDL_WM_SetCaption(NAME,""); //set window title
-		CGameInfo * cgi = new CGameInfo; //contains all global informations about game (texts, lodHandlers, map handler itp.)
-		CGameInfo::mainObj = cgi;
-		#ifdef _DEBUG
-		CGI = cgi;
-		#endif
+		//audio initialized 
 		cgi->consoleh = new CConsoleHandler;
 		cgi->mush = mush;
-		cgi->curh = new CCursorHandler;
-
+		THC std::cout<<"\tInitializing sound: "<<pomtime.getDif()<<std::endl;
 		THC std::cout<<"Initializing screen, fonts and sound handling: "<<tmh.getDif()<<std::endl;
-		cgi->spriteh = new CLodHandler;
-		cgi->spriteh->init(std::string(DATADIR "Data" PATHSEPARATOR "H3sprite.lod"));
-		cgi->bitmaph = new CLodHandler;
-		cgi->bitmaph->init(std::string(DATADIR "Data" PATHSEPARATOR "H3bitmap.lod"));
+		CDefHandler::Spriteh = cgi->spriteh = new CLodHandler();
+		cgi->spriteh->init("Data\\H3sprite.lod","Sprites");
+		BitmapHandler::bitmaph = cgi->bitmaph = new CLodHandler;
+		cgi->bitmaph->init("Data\\H3bitmap.lod","Data");
 		THC std::cout<<"Loading .lod files: "<<tmh.getDif()<<std::endl;
-
-		boost::filesystem::directory_iterator enddir;
-		for (boost::filesystem::directory_iterator dir("Data");dir!=enddir;dir++)
-		{
-			if(boost::filesystem::is_regular(dir->status()))
-			{
-				std::string name = dir->path().leaf();
-				std::transform(name.begin(), name.end(), name.begin(), (int(*)(int))toupper);
-				boost::algorithm::replace_all(name,".BMP",".PCX");
-				Entry * e = cgi->bitmaph->entries.znajdz(name);
-				if(e)
-				{
-					e->offset = -1;
-					e->realSize = e->size = boost::filesystem::file_size(dir->path());
-				}
-			}
-		}
-
-		if(boost::filesystem::exists("Sprites"))
-		{
-			for (boost::filesystem::directory_iterator dir("Sprites");dir!=enddir;dir++)
-			{
-				if(boost::filesystem::is_regular(dir->status()))
-				{
-					std::string name = dir->path().leaf();
-					std::transform(name.begin(), name.end(), name.begin(), (int(*)(int))toupper);
-					boost::algorithm::replace_all(name,".BMP",".PCX");
-					Entry * e = cgi->spriteh->entries.znajdz(name);
-					if(e)
-					{
-						e->offset = -1;
-						e->realSize = e->size = boost::filesystem::file_size(dir->path());
-					}
-				}
-			}
-		}
-		else
-			std::cout<<"Warning: No sprites/ folder!"<<std::endl;
-		THC std::cout<<"Scanning Data/ and Sprites/ folders: "<<tmh.getDif()<<std::endl;
+		initDLL(cgi->bitmaph);
+		CGI->arth = VLC->arth;
+		CGI->creh = VLC->creh;
+		CGI->townh = VLC->townh;
+		CGI->heroh = VLC->heroh;
+		CGI->objh = VLC->objh;
+		CGI->dobjinfo = VLC->dobjinfo;
+		CGI->buildh = VLC->buildh;
+		THC std::cout<<"Initializing VCMI_Lib: "<<tmh.getDif()<<std::endl;
+		//cgi->curh->initCursor();
+		//cgi->curh->showGraphicCursor();
+		pomtime.getDif();
+		cgi->curh = new CCursorHandler; 
 		cgi->curh->initCursor();
-		cgi->curh->showGraphicCursor();
-
-		cgi->screenh = new CScreenHandler;
-		cgi->screenh->initScreen();
-
-		THC std::cout<<"Preparing first handlers: "<<tmh.getDif()<<std::endl;
-
-		//colors initialization
-		SDL_Color p;
-		p.unused = 0;
-		p.r = 0xff; p.g = 0x0; p.b = 0x0; //red
-		cgi->playerColors.push_back(p); //red
-		p.r = 0x31; p.g = 0x52; p.b = 0xff; //blue
-		cgi->playerColors.push_back(p); //blue
-		p.r = 0x9c; p.g = 0x73; p.b = 0x52;//tan
-		cgi->playerColors.push_back(p);//tan
-		p.r = 0x42; p.g = 0x94; p.b = 0x29; //green
-		cgi->playerColors.push_back(p); //green
-		p.r = 0xff; p.g = 0x84; p.b = 0x0; //orange
-		cgi->playerColors.push_back(p); //orange
-		p.r = 0x8c; p.g = 0x29; p.b = 0xa5; //purple
-		cgi->playerColors.push_back(p); //purple
-		p.r = 0x09; p.g = 0x9c; p.b = 0xa5;//teal
-		cgi->playerColors.push_back(p);//teal
-		p.r = 0xc6; p.g = 0x7b; p.b = 0x8c;//pink
-		cgi->playerColors.push_back(p);//pink
-		p.r = 0x84; p.g = 0x84; p.b = 0x84;//gray
-		cgi->neutralColor = p;//gray
-		//colors initialized
-		//palette initialization
-		std::string pals = cgi->bitmaph->getTextFile("PLAYERS.PAL");
-		int startPoint = 24; //beginning byte; used to read
-		for(int i=0; i<256; ++i)
-		{
-			SDL_Color col;
-			col.r = pals[startPoint++];
-			col.g = pals[startPoint++];
-			col.b = pals[startPoint++];
-			col.unused = pals[startPoint++];
-			playerColorPalette[i] = col;
-		}
-		//palette initialized
-		THC std::cout<<"Preparing players' colours: "<<tmh.getDif()<<std::endl;
-
-		CMessage::init();
-		cgi->townh = new CTownHandler;
-		cgi->townh->loadNames();
+		//cgi->screenh = new CScreenHandler;
+		//cgi->screenh->initScreen();
+		THC std::cout<<"\tScreen handler: "<<pomtime.getDif()<<std::endl;
 		CAbilityHandler * abilh = new CAbilityHandler;
 		abilh->loadAbilities();
 		cgi->abilh = abilh;
-		CHeroHandler * heroh = new CHeroHandler;
-		heroh->loadHeroes();
-		heroh->loadPortraits();
-		cgi->heroh = heroh;
+		THC std::cout<<"\tAbility handler: "<<pomtime.getDif()<<std::endl;
+		THC std::cout<<"Preparing first handlers: "<<tmh.getDif()<<std::endl;
+		pomtime.getDif();
+		graphics = new Graphics();
+		THC std::cout<<"\tMain graphics: "<<tmh.getDif()<<std::endl;
+		std::vector<CDefHandler **> animacje;
+		for(std::vector<CHeroClass *>::iterator i = cgi->heroh->heroClasses.begin();i!=cgi->heroh->heroClasses.end();i++)
+			animacje.push_back(&((*i)->*(&CHeroClass::moveAnim)));
+		graphics->loadHeroAnim(animacje);
+		THC std::cout<<"\tHero animations: "<<tmh.getDif()<<std::endl;
+		THC std::cout<<"Initializing game graphics: "<<tmh.getDif()<<std::endl;
+		CMessage::init();
 		cgi->generaltexth = new CGeneralTextHandler;
 		cgi->generaltexth->load();
 		THC std::cout<<"Preparing more handlers: "<<tmh.getDif()<<std::endl;
-
-		//initializing hero flags
-
-		cgi->heroh->flags1.push_back(cgi->spriteh->giveDef("ABF01L.DEF")); //red
-		cgi->heroh->flags1.push_back(cgi->spriteh->giveDef("ABF01G.DEF")); //blue
-		cgi->heroh->flags1.push_back(cgi->spriteh->giveDef("ABF01R.DEF")); //tan
-		cgi->heroh->flags1.push_back(cgi->spriteh->giveDef("ABF01D.DEF")); //green
-		cgi->heroh->flags1.push_back(cgi->spriteh->giveDef("ABF01B.DEF")); //orange
-		cgi->heroh->flags1.push_back(cgi->spriteh->giveDef("ABF01P.DEF")); //purple
-		cgi->heroh->flags1.push_back(cgi->spriteh->giveDef("ABF01W.DEF")); //teal
-		cgi->heroh->flags1.push_back(cgi->spriteh->giveDef("ABF01K.DEF")); //pink
-
-		for(int q=0; q<8; ++q)
-		{
-			for(int o=0; o<cgi->heroh->flags1[q]->ourImages.size(); ++o)
-			{
-				if(cgi->heroh->flags1[q]->ourImages[o].groupNumber==6)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags1[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 10;
-						nci.imName = std::string();
-						cgi->heroh->flags1[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-				if(cgi->heroh->flags1[q]->ourImages[o].groupNumber==7)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags1[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 11;
-						nci.imName = std::string();
-						cgi->heroh->flags1[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-				if(cgi->heroh->flags1[q]->ourImages[o].groupNumber==8)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags1[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 12;
-						nci.imName = std::string();
-						cgi->heroh->flags1[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-			}
-
-			for(int ff=0; ff<cgi->heroh->flags1[q]->ourImages.size(); ++ff)
-			{
-				SDL_SetColorKey(cgi->heroh->flags1[q]->ourImages[ff].bitmap, SDL_SRCCOLORKEY,
-					SDL_MapRGB(cgi->heroh->flags1[q]->ourImages[ff].bitmap->format, 0, 255, 255)
-					);
-			}
-			cgi->heroh->flags1[q]->alphaTransformed = true;
-		}
-
-		cgi->heroh->flags2.push_back(cgi->spriteh->giveDef("ABF02L.DEF")); //red
-		cgi->heroh->flags2.push_back(cgi->spriteh->giveDef("ABF02G.DEF")); //blue
-		cgi->heroh->flags2.push_back(cgi->spriteh->giveDef("ABF02R.DEF")); //tan
-		cgi->heroh->flags2.push_back(cgi->spriteh->giveDef("ABF02D.DEF")); //green
-		cgi->heroh->flags2.push_back(cgi->spriteh->giveDef("ABF02B.DEF")); //orange
-		cgi->heroh->flags2.push_back(cgi->spriteh->giveDef("ABF02P.DEF")); //purple
-		cgi->heroh->flags2.push_back(cgi->spriteh->giveDef("ABF02W.DEF")); //teal
-		cgi->heroh->flags2.push_back(cgi->spriteh->giveDef("ABF02K.DEF")); //pink
-
-		for(int q=0; q<8; ++q)
-		{
-			for(int o=0; o<cgi->heroh->flags2[q]->ourImages.size(); ++o)
-			{
-				if(cgi->heroh->flags2[q]->ourImages[o].groupNumber==6)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags2[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 10;
-						nci.imName = std::string();
-						cgi->heroh->flags2[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-				if(cgi->heroh->flags2[q]->ourImages[o].groupNumber==7)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags2[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 11;
-						nci.imName = std::string();
-						cgi->heroh->flags2[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-				if(cgi->heroh->flags2[q]->ourImages[o].groupNumber==8)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags2[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 12;
-						nci.imName = std::string();
-						cgi->heroh->flags2[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-			}
-
-			for(int ff=0; ff<cgi->heroh->flags2[q]->ourImages.size(); ++ff)
-			{
-				SDL_SetColorKey(cgi->heroh->flags2[q]->ourImages[ff].bitmap, SDL_SRCCOLORKEY,
-					SDL_MapRGB(cgi->heroh->flags2[q]->ourImages[ff].bitmap->format, 0, 255, 255)
-					);
-			}
-			cgi->heroh->flags2[q]->alphaTransformed = true;
-		}
-
-		cgi->heroh->flags3.push_back(cgi->spriteh->giveDef("ABF03L.DEF")); //red
-		cgi->heroh->flags3.push_back(cgi->spriteh->giveDef("ABF03G.DEF")); //blue
-		cgi->heroh->flags3.push_back(cgi->spriteh->giveDef("ABF03R.DEF")); //tan
-		cgi->heroh->flags3.push_back(cgi->spriteh->giveDef("ABF03D.DEF")); //green
-		cgi->heroh->flags3.push_back(cgi->spriteh->giveDef("ABF03B.DEF")); //orange
-		cgi->heroh->flags3.push_back(cgi->spriteh->giveDef("ABF03P.DEF")); //purple
-		cgi->heroh->flags3.push_back(cgi->spriteh->giveDef("ABF03W.DEF")); //teal
-		cgi->heroh->flags3.push_back(cgi->spriteh->giveDef("ABF03K.DEF")); //pink
-
-		for(int q=0; q<8; ++q)
-		{
-			for(int o=0; o<cgi->heroh->flags3[q]->ourImages.size(); ++o)
-			{
-				if(cgi->heroh->flags3[q]->ourImages[o].groupNumber==6)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags3[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 10;
-						nci.imName = std::string();
-						cgi->heroh->flags3[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-				if(cgi->heroh->flags3[q]->ourImages[o].groupNumber==7)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags3[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 11;
-						nci.imName = std::string();
-						cgi->heroh->flags3[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-				if(cgi->heroh->flags3[q]->ourImages[o].groupNumber==8)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags3[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 12;
-						nci.imName = std::string();
-						cgi->heroh->flags3[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-			}
-
-			for(int ff=0; ff<cgi->heroh->flags3[q]->ourImages.size(); ++ff)
-			{
-				SDL_SetColorKey(cgi->heroh->flags3[q]->ourImages[ff].bitmap, SDL_SRCCOLORKEY,
-					SDL_MapRGB(cgi->heroh->flags3[q]->ourImages[ff].bitmap->format, 0, 255, 255)
-					);
-			}
-			cgi->heroh->flags3[q]->alphaTransformed = true;
-		}
-
-		cgi->heroh->flags4.push_back(cgi->spriteh->giveDef("AF00.DEF")); //red
-		cgi->heroh->flags4.push_back(cgi->spriteh->giveDef("AF01.DEF")); //blue
-		cgi->heroh->flags4.push_back(cgi->spriteh->giveDef("AF02.DEF")); //tan
-		cgi->heroh->flags4.push_back(cgi->spriteh->giveDef("AF03.DEF")); //green
-		cgi->heroh->flags4.push_back(cgi->spriteh->giveDef("AF04.DEF")); //orange
-		cgi->heroh->flags4.push_back(cgi->spriteh->giveDef("AF05.DEF")); //purple
-		cgi->heroh->flags4.push_back(cgi->spriteh->giveDef("AF06.DEF")); //teal
-		cgi->heroh->flags4.push_back(cgi->spriteh->giveDef("AF07.DEF")); //pink
-
-		for(int q=0; q<8; ++q)
-		{
-			for(int o=0; o<cgi->heroh->flags4[q]->ourImages.size(); ++o)
-			{
-				if(cgi->heroh->flags4[q]->ourImages[o].groupNumber==6)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags4[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 10;
-						nci.imName = std::string();
-						cgi->heroh->flags4[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-				if(cgi->heroh->flags4[q]->ourImages[o].groupNumber==7)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags4[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 10;
-						nci.groupNumber = 11;
-						nci.imName = std::string();
-						cgi->heroh->flags4[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-				if(cgi->heroh->flags4[q]->ourImages[o].groupNumber==8)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags4[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 10;
-						nci.groupNumber = 12;
-						nci.imName = std::string();
-						cgi->heroh->flags4[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-			}
-
-			for(int o=0; o<cgi->heroh->flags4[q]->ourImages.size(); ++o)
-			{
-				if(cgi->heroh->flags4[q]->ourImages[o].groupNumber==1)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags4[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 10;
-						nci.groupNumber = 13;
-						nci.imName = std::string();
-						cgi->heroh->flags4[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-				if(cgi->heroh->flags4[q]->ourImages[o].groupNumber==2)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags4[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 10;
-						nci.groupNumber = 14;
-						nci.imName = std::string();
-						cgi->heroh->flags4[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-				if(cgi->heroh->flags4[q]->ourImages[o].groupNumber==3)
-				{
-					for(int e=0; e<8; ++e)
-					{
-						Cimage nci;
-						nci.bitmap = CSDL_Ext::rotate01(cgi->heroh->flags4[q]->ourImages[o+e].bitmap);
-						nci.groupNumber = 10;
-						nci.groupNumber = 15;
-						nci.imName = std::string();
-						cgi->heroh->flags4[q]->ourImages.push_back(nci);
-					}
-					o+=8;
-				}
-			}
-
-			for(int ff=0; ff<cgi->heroh->flags4[q]->ourImages.size(); ++ff)
-			{
-				SDL_SetColorKey(cgi->heroh->flags4[q]->ourImages[ff].bitmap, SDL_SRCCOLORKEY,
-					SDL_MapRGB(cgi->heroh->flags4[q]->ourImages[ff].bitmap->format, 0, 255, 255)
-					);
-			}
-			cgi->heroh->flags4[q]->alphaTransformed = true;
-		}
-
-		//hero flags initialized
-
-		THC std::cout<<"Initializing colours and flags: "<<tmh.getDif()<<std::endl;
 		CPreGame * cpg = new CPreGame(); //main menu and submenus
 		THC std::cout<<"Initialization CPreGame (together): "<<tmh.getDif()<<std::endl;
+		THC std::cout<<"Initialization of VCMI (togeter): "<<total.getDif()<<std::endl;
 		cpg->mush = mush;
-		cgi->scenarioOps = cpg->runLoop();
-		THC tmh.getDif();
-
-		CArtHandler * arth = new CArtHandler;
-		arth->loadArtifacts();
-		cgi->arth = arth;
-		THC std::cout<<"\tArtifact handler: "<<pomtime.getDif()<<std::endl;
-
-		CCreatureHandler * creh = new CCreatureHandler;
-		creh->loadCreatures();
-		cgi->creh = creh;
-		THC std::cout<<"\tCreature handler: "<<pomtime.getDif()<<std::endl;
-
+		StartInfo *options = new StartInfo(cpg->runLoop());
+///////////////////////////////////////////////////////////////////////////////////////
+		boost::thread servthr(boost::bind(system,"VCMI_server.exe > server_log.txt")); //runs server executable; 
+												//TODO: will it work on non-windows platforms?
+		THC tmh.getDif();pomtime.getDif();//reset timers
 		CSpellHandler * spellh = new CSpellHandler;
 		spellh->loadSpells();
-		cgi->spellh = spellh;
+		cgi->spellh = spellh;		
 		THC std::cout<<"\tSpell handler: "<<pomtime.getDif()<<std::endl;
-
-		CBuildingHandler * buildh = new CBuildingHandler;
-		buildh->loadBuildings();
-		cgi->buildh = buildh;
-		THC std::cout<<"\tBuilding handler: "<<pomtime.getDif()<<std::endl;
-
-		CObjectHandler * objh = new CObjectHandler;
-		objh->loadObjects();
-		cgi->objh = objh;
-		THC std::cout<<"\tObject handler: "<<pomtime.getDif()<<std::endl;
-
-		cgi->dobjinfo = new CDefObjInfoHandler;
-		cgi->dobjinfo->load();
-		THC std::cout<<"\tDef information handler: "<<pomtime.getDif()<<std::endl;
-
-		cgi->state = new CGameState();
-		cgi->state->players = std::map<int, PlayerState>();
-		THC std::cout<<"\tGamestate: "<<pomtime.getDif()<<std::endl;
-
 		cgi->pathf = new CPathfinder();
 		THC std::cout<<"\tPathfinder: "<<pomtime.getDif()<<std::endl;
-		cgi->consoleh->cb = new CCallback(cgi->state,-1);
 		cgi->consoleh->runConsole();
 		THC std::cout<<"\tCallback and console: "<<pomtime.getDif()<<std::endl;
-		THC std::cout<<"Handlers initailization (together): "<<tmh.getDif()<<std::endl;
-
-		std::string mapname;
-		//if(CPG->ourScenSel->mapsel.selected==0)
-		//	CPG->ourScenSel->mapsel.selected = 1; //only for tests
-		if (CPG)
-			mapname = CPG->ourScenSel->mapsel.ourMaps[CPG->ourScenSel->mapsel.selected].filename;
-		else
+		THC std::cout<<"Handlers initialization (together): "<<tmh.getDif()<<std::endl;
+		std::ofstream lll("client_log.txt");
+		CConnection *c = new CConnection("localhost","3030",NAME,lll);
+		THC std::cout<<"\tConnecting to the server: "<<tmh.getDif()<<std::endl;
+		CClient cl(c,options);
+		boost::thread t(boost::bind(&CClient::run,&cl));
+		SDL_Event ev;
+		while(1) //main SDL events loop
 		{
-			std::cout<<"Critical error: CPG==NULL"<<std::endl;
-		}
-		std::cout<<"Opening map file: "<<mapname<<"\t\t"<<std::flush;
-		gzFile map = gzopen(mapname.c_str(),"rb");
-		std::vector<unsigned char> mapstr; int pom;
-		while((pom=gzgetc(map))>=0)
-		{
-			mapstr.push_back(pom);
-		}
-		gzclose(map);
-		unsigned char *initTable = new unsigned char[mapstr.size()];
-		for(int ss=0; ss<mapstr.size(); ++ss)
-		{
-			initTable[ss] = mapstr[ss];
-		}
-		std::cout<<"done."<<std::endl;
-
-		CAmbarCendamo * ac = new CAmbarCendamo(initTable); //4gryf
-		cgi->ac = ac;
-		THC std::cout<<"Reading file: "<<tmh.getDif()<<std::endl;
-		ac->deh3m();
-		THC std::cout<<"Detecting file (together): "<<tmh.getDif()<<std::endl;
-		ac->loadDefs();
-		THC std::cout<<"Reading terrain defs: "<<tmh.getDif()<<std::endl;
-		CMapHandler * mh = new CMapHandler();
-		cgi->mh = mh;
-		mh->reader = ac;
-		THC std::cout<<"Creating mapHandler: "<<tmh.getDif()<<std::endl;
-		mh->init();
-		THC std::cout<<"Initializing mapHandler (together): "<<tmh.getDif()<<std::endl;
-
-		initGameState(cgi);
-		THC std::cout<<"Initializing GameState (together): "<<tmh.getDif()<<std::endl;
-
-		/*for(int d=0; d<PLAYER_LIMIT; ++d)
-		{
-			cgi->playerint.push_back(NULL);
-		}*/
-		for (int i=0; i<cgi->scenarioOps.playerInfos.size();i++) //initializing interfaces
-		{
-			if(!cgi->scenarioOps.playerInfos[i].human)
+			SDL_WaitEvent(&ev);
+			if(ev.type==SDL_QUIT) 
 			{
-#ifdef _WIN32
-				cgi->playerint.push_back(static_cast<CGameInterface*>(CAIHandler::getNewAI(new CCallback(cgi->state,cgi->scenarioOps.playerInfos[i].color),"EmptyAI.dll")));
-#else
-				cgi->playerint.push_back(static_cast<CGameInterface*>(CAIHandler::getNewAI(new CCallback(cgi->state,cgi->scenarioOps.playerInfos[i].color),"libemptyai.so")));
-#endif
-			}
-			else
-			{
-				cgi->state->currentPlayer=cgi->scenarioOps.playerInfos[i].color;
-				cgi->playerint.push_back(new CPlayerInterface(cgi->scenarioOps.playerInfos[i].color,i));
-				((CPlayerInterface*)(cgi->playerint[i]))->init(new CCallback(cgi->state,cgi->scenarioOps.playerInfos[i].color));
+				t.interrupt();
+				exit(0);
 			}
+			eventsM.lock();
+			events.push(ev);
+			eventsM.unlock();
 		}
 		///claculating FoWs for minimap
 		/****************************Minimaps' FoW******************************************/
-		for(int g=0; g<cgi->playerint.size(); ++g)
-		{
-			if(!cgi->playerint[g]->human)
-				continue;
-			CMinimap & mm = ((CPlayerInterface*)cgi->playerint[g])->adventureInt->minimap;
-
-			int mw = mm.map[0]->w, mh = mm.map[0]->h,
-				wo = mw/CGI->mh->sizes.x, ho = mh/CGI->mh->sizes.y;
-
-			for(int d=0; d<cgi->mh->reader->map.twoLevel+1; ++d)
-			{
-				SDL_Surface * pt = CSDL_Ext::newSurface(mm.pos.w, mm.pos.h, CSDL_Ext::std32bppSurface);
-
-				for (int i=0; i<mw; i++)
-				{
-					for (int j=0; j<mh; j++)
-					{
-						int3 pp( ((i*CGI->mh->sizes.x)/mw), ((j*CGI->mh->sizes.y)/mh), d );
-
-						if ( !((CPlayerInterface*)cgi->playerint[g])->cb->isVisible(pp) )
-						{
-							CSDL_Ext::SDL_PutPixelWithoutRefresh(pt,i,j,0,0,0);
-						}
-					}
-				}
-				CSDL_Ext::update(pt);
-				mm.FoW.push_back(pt);
-			}
-
-		}
-
-		while(1) //main game loop, one execution per turn
-		{
-			cgi->consoleh->cb->newTurn();
-			for (int i=0;i<cgi->playerint.size();i++)
-			{
-				cgi->state->currentPlayer=cgi->playerint[i]->playerID;
-				try
-				{
-					cgi->playerint[i]->yourTurn();
-				}HANDLE_EXCEPTION
-			}
-		}
+		//for(int g=0; g<cgi->playerint.size(); ++g)
+		//{
+		//	if(!cgi->playerint[g]->human)
+		//		continue;
+		//	CMinimap & mm = ((CPlayerInterface*)cgi->playerint[g])->adventureInt->minimap;
+		//	int mw = mm.map[0]->w, mh = mm.map[0]->h,
+		//		wo = mw/CGI->mh->sizes.x, ho = mh/CGI->mh->sizes.y;
+		//	for(int d=0; d<cgi->mh->map->twoLevel+1; ++d)
+		//	{
+		//		SDL_Surface * pt = CSDL_Ext::newSurface(mm.pos.w, mm.pos.h, CSDL_Ext::std32bppSurface);
+		//		for (int i=0; i<mw; i++)
+		//		{
+		//			for (int j=0; j<mh; j++)
+		//			{
+		//				int3 pp( ((i*CGI->mh->sizes.x)/mw), ((j*CGI->mh->sizes.y)/mh), d );
+		//				if ( !((CPlayerInterface*)cgi->playerint[g])->cb->isVisible(pp) )
+		//				{
+		//					CSDL_Ext::SDL_PutPixelWithoutRefresh(pt,i,j,0,0,0);
+		//				}
+		//			}
+		//		}
+		//		CSDL_Ext::update(pt);
+		//		mm.FoW.push_back(pt);
+		//	}
+		//}
 	}
 	else
 	{

+ 6 - 7
CMessage.cpp

@@ -1,7 +1,6 @@
 #include "stdafx.h"
 #include "CMessage.h"
 #include "SDL_ttf.h"
-#include "hch/CSemiDefHandler.h"
 #include "hch/CDefHandler.h"
 #include "CGameInfo.h"
 #include "SDL_Extensions.h"
@@ -10,12 +9,12 @@
 #include <boost/algorithm/string/replace.hpp>
 #include "CPlayerInterface.h"
 #include "hch/CDefHandler.h"
-#include "hch/CSemiDefHandler.h"
 #include "CGameInfo.h"
 #include "SDL_Extensions.h"
 #include <sstream>
 #include "CLua.h"
 #include "hch/CGeneralTextHandler.h"
+#include "client/Graphics.h"
 SDL_Color tytulowy, tlo, zwykly ;
 SDL_Rect genRect(int hh, int ww, int xx, int yy);
 
@@ -51,7 +50,7 @@ void CMessage::init()
 	{
 		for (int i=0;i<PLAYER_LIMIT;i++)
 		{
-			CDefHandler * bluePieces = CGI->spriteh->giveDef("DIALGBOX.DEF");
+			CDefHandler * bluePieces = CDefHandler::giveDef("DIALGBOX.DEF");
 			std::vector<SDL_Surface *> n;
 			piecesOfBox.push_back(n);
 			if (i==1)
@@ -63,15 +62,15 @@ void CMessage::init()
 			}
 			for (int j=0;j<bluePieces->ourImages.size();j++)
 			{
-				CSDL_Ext::blueToPlayersAdv(bluePieces->ourImages[j].bitmap,i);
+				graphics->blueToPlayersAdv(bluePieces->ourImages[j].bitmap,i);
 				piecesOfBox[i].push_back(bluePieces->ourImages[j].bitmap);
 			}
 		}
-		NMessage::background = CGI->bitmaph->loadBitmap("DIBOXBCK.BMP");
+		NMessage::background = BitmapHandler::loadBitmap("DIBOXBCK.BMP");
 		SDL_SetColorKey(background,SDL_SRCCOLORKEY,SDL_MapRGB(background->format,0,255,255));
 	}
-	ok = CGI->spriteh->giveDef("IOKAY.DEF");
-	cancel = CGI->spriteh->giveDef("ICANCEL.DEF");
+	ok = CDefHandler::giveDef("IOKAY.DEF");
+	cancel = CDefHandler::giveDef("ICANCEL.DEF");
 }
 
 

+ 12 - 11
CPathfinder.cpp

@@ -5,6 +5,7 @@
 #include "hch/CAmbarCendamo.h"
 #include "mapHandler.h"
 #include "CGameState.h"
+#include "hch/CObjectHandler.h"
 
 using namespace std;
 
@@ -41,14 +42,14 @@ vector<Coordinate>* CPathfinder::GetPath(const CGHeroInstance* hero)
 	int3 hpos = Hero->getPosition(false);
 	if (!Hero->canWalkOnSea())
 	{
-		if (CGI->mh->ttiles[hpos.x][hpos.y][hpos.z].terType==water)
+		if (CGI->mh->ttiles[hpos.x][hpos.y][hpos.z].tileInfo->tertype==water)
 			blockLandSea=false;
 		else
 			blockLandSea=true;
 	}
 	else
 	{
-		blockLandSea = indeterminate;
+		blockLandSea = boost::logic::indeterminate;
 	}
 
 	CalcG(&Start);
@@ -191,11 +192,11 @@ void CPathfinder::CalcH(Coordinate* node)
 	 * If there is fog of war on the node.
 	 *  => Impossible to move there.
 	 */
-	if( (CGI->mh->ttiles[node->x][node->y][node->z].blocked && !(node->x==End.x && node->y==End.y && CGI->mh->ttiles[node->x][node->y][node->z].visitable)) ||
-		(CGI->mh->ttiles[node->x][node->y][node->z].terType==rock) ||
-		((blockLandSea) && (CGI->mh->ttiles[node->x][node->y][node->z].terType==water)) ||
+	if( (CGI->mh->ttiles[node->x][node->y][node->z].tileInfo->blocked && !(node->x==End.x && node->y==End.y && CGI->mh->ttiles[node->x][node->y][node->z].tileInfo->visitable)) ||
+		(CGI->mh->ttiles[node->x][node->y][node->z].tileInfo->tertype==rock) ||
+		((blockLandSea) && (CGI->mh->ttiles[node->x][node->y][node->z].tileInfo->tertype==water)) ||
 		(!CGI->state->players[Hero->tempOwner].fogOfWarMap[node->x][node->y][node->z]) ||
-		((!blockLandSea) && (CGI->mh->ttiles[node->x][node->y][node->z].terType!=water)))
+		((!blockLandSea) && (CGI->mh->ttiles[node->x][node->y][node->z].tileInfo->tertype!=water)))
 	{
 		//Impossible.
 
@@ -206,13 +207,13 @@ void CPathfinder::CalcH(Coordinate* node)
 	int ret=-1;
 	int x = node->x;
 	int y = node->y;
-	if(node->x>=CGI->mh->reader->map.width)
-		x = CGI->mh->reader->map.width-1;
-	if(node->y>=CGI->mh->reader->map.height)
-		y = CGI->mh->reader->map.height-1;
+	if(node->x>=CGI->mh->map->width)
+		x = CGI->mh->map->width-1;
+	if(node->y>=CGI->mh->map->height)
+		y = CGI->mh->map->height-1;
 
 	//Get the movement cost.
-	ret = Hero->getTileCost(CGI->mh->ttiles[x][y][node->z].terType, CGI->mh->reader->map.terrain[x][y].malle,CGI->mh->reader->map.terrain[x][y].nuine);
+	ret = Hero->getTileCost(CGI->mh->ttiles[x][y][node->z].tileInfo->tertype, CGI->mh->map->terrain[x][y][node->z].malle,CGI->mh->map->terrain[x][y][node->z].nuine);
 
 	node->h = ret;
 }

+ 163 - 203
CPlayerInterface.cpp

@@ -1,17 +1,18 @@
 #include "stdafx.h"
+#include <queue>
 #include "CPlayerInterface.h"
 #include "CAdvmapInterface.h"
 #include "CMessage.h"
 #include "mapHandler.h"
 #include "SDL_Extensions.h"
 #include "SDL_framerate.h"
-#include "CScreenHandler.h"
 #include "CCursorHandler.h"
 #include "CCallback.h"
 #include "SDL_Extensions.h"
 #include "hch/CLodHandler.h"
 #include "CPathfinder.h"
 #include <sstream>
+#include "hch/CAbilityHandler.h"
 #include "hch/CHeroHandler.h"
 #include "hch/CTownHandler.h"
 #include "SDL_framerate.h"
@@ -19,21 +20,33 @@
 #include "CCastleInterface.h"
 #include "CHeroWindow.h"
 #include "timeHandler.h"
+#include <boost/thread.hpp>
 #include <boost/algorithm/string.hpp>
 #include <boost/algorithm/string/replace.hpp>
 #include "hch/CPreGameTextHandler.h"
+#include "hch/CObjectHandler.h"
 #include "CBattleInterface.h"
+#include "CGameInfo.h"
 #include "CLua.h"
 #include <cmath>
+#include "client/CCreatureAnimation.h"
+#include "client/Graphics.h"
+#include "map.h"
+#include "lib/NetPacks.h"
+#include "lib/CondSh.h"
 using namespace CSDL_Ext;
 
 extern TTF_Font * GEOR16;
 extern bool continueReadingConsole;
+CPlayerInterface * LOCPLINT;
+extern std::queue<SDL_Event> events;
+extern boost::mutex eventsM;
+
 
 class OCM_HLP_CGIN
 {
 public:
-	bool operator ()(const std::pair<CGObjectInstance*,SDL_Rect>  & a, const std::pair<CGObjectInstance*,SDL_Rect> & b) const
+	bool operator ()(const std::pair<const CGObjectInstance*,SDL_Rect>  & a, const std::pair<const CGObjectInstance*,SDL_Rect> & b) const
 	{
 		return (*a.first)<(*b.first);
 	}
@@ -228,10 +241,10 @@ void CGarrisonSlot::show()
 	{
 		char* buf = new char[15];
 		SDL_itoa(count,buf,10);
-		blitAt(CGI->creh->bigImgs[creature->idNumber],pos);
+		blitAt(graphics->bigImgs[creature->idNumber],pos);
 		printTo(buf,pos.x+56,pos.y+62,GEOR16,zwykly);
 		if(owner->highlighted==this)
-			blitAt(CGI->creh->bigImgs[-1],pos);
+			blitAt(graphics->bigImgs[-1],pos);
 		if(owner->update)
 			updateRect(&pos,screen);
 		delete [] buf;
@@ -241,7 +254,7 @@ void CGarrisonSlot::show()
 		SDL_Rect jakis1 = genRect(pos.h,pos.w,owner->offx+ID*(pos.w+owner->interx),owner->offy+upg*(pos.h+owner->intery)), jakis2 = pos;
 		SDL_BlitSurface(owner->sur,&jakis1,screen,&jakis2);
 		if(owner->splitting)
-			blitAt(CGI->creh->bigImgs[-1],pos);
+			blitAt(graphics->bigImgs[-1],pos);
 		if(owner->update)
 			SDL_UpdateRect(screen,pos.x,pos.y,pos.w,pos.h);
 	}
@@ -329,11 +342,11 @@ void CGarrisonInt::createSlots()
 	{
 		sup = new std::vector<CGarrisonSlot*>(7,(CGarrisonSlot *)(NULL));
 		for
-			(std::map<int,std::pair<CCreature*,int> >::const_iterator i=set1->slots.begin();
+			(std::map<si32,std::pair<ui32,si32> >::const_iterator i=set1->slots.begin();
 			i!=set1->slots.end(); i++)
 		{
 			(*sup)[i->first] =
-				new CGarrisonSlot(this, pos.x + (i->first*(58+interx)), pos.y,i->first, 0, i->second.first,i->second.second);
+				new CGarrisonSlot(this, pos.x + (i->first*(58+interx)), pos.y,i->first, 0, &CGI->creh->creatures[i->second.first],i->second.second);
 		}
 		for(int i=0; i<sup->size(); i++)
 			if((*sup)[i] == NULL)
@@ -343,11 +356,11 @@ void CGarrisonInt::createSlots()
 	{
 		sdown = new std::vector<CGarrisonSlot*>(7,(CGarrisonSlot *)(NULL));
 		for
-			(std::map<int,std::pair<CCreature*,int> >::const_iterator i=set2->slots.begin();
+			(std::map<si32,std::pair<ui32,si32> >::const_iterator i=set2->slots.begin();
 			i!=set2->slots.end(); i++)
 		{
 			(*sdown)[i->first] =
-				new CGarrisonSlot(this, pos.x + (i->first*(58+interx)), pos.y + 64 + intery,i->first,1, i->second.first,i->second.second);
+				new CGarrisonSlot(this, pos.x + (i->first*(58+interx)), pos.y + 64 + intery,i->first,1, &CGI->creh->creatures[i->second.first],i->second.second);
 		}
 		for(int i=0; i<sup->size(); i++)
 			if((*sdown)[i] == NULL)
@@ -517,7 +530,7 @@ void CInfoPopup::show(SDL_Surface * to)
 	blitAt(bitmap,pos.x,pos.y,(to)?(to):(screen));
 }
 
-SComponent::SComponent(Etype Type, int Subtype, int Val)
+void SComponent::init(Etype Type, int Subtype, int Val)
 {
 	std::ostringstream oss;
 	switch (Type)
@@ -545,22 +558,40 @@ SComponent::SComponent(Etype Type, int Subtype, int Val)
 	pos.w = temp->w;
 	pos.h = temp->h;
 }
+SComponent::SComponent(Etype Type, int Subtype, int Val)
+{
+	init(Type,Subtype,Val);
+}
 
+SComponent::SComponent(const Component &c)
+{
+	if(c.id==0 && c.subtype==4)
+		init(experience,0,c.val);
+	else
+		init((Etype)c.id,c.subtype,c.val);
+	switch(c.id)
+	{
+	case resource:
+		if(c.when == -1)
+			subtitle += CGI->generaltexth->allTexts[3].substr(2,CGI->generaltexth->allTexts[3].length()-2);
+		break;
+	}
+}
 SDL_Surface * SComponent::getImg()
 {
 	switch (type)
 	{
 	case primskill:
-		return CGI->heroh->pskillsb->ourImages[subtype].bitmap;
+		return graphics->pskillsb->ourImages[subtype].bitmap;
 		break;
 	case secskill:
 		return CGI->abilh->abils82->ourImages[subtype*3 + 3 + val].bitmap;
 		break;
 	case resource:
-		return CGI->heroh->resources->ourImages[subtype].bitmap;
+		return graphics->resources->ourImages[subtype].bitmap;
 		break;
 	case experience:
-		return CGI->heroh->pskillsb->ourImages[4].bitmap;
+		return graphics->pskillsb->ourImages[4].bitmap;
 		break;
 	}
 	return NULL;
@@ -888,58 +919,38 @@ void TimeInterested::deactivate()
 }
 CPlayerInterface::CPlayerInterface(int Player, int serial)
 {
+	LOCPLINT = this;
 	playerID=Player;
 	serialID=serial;
-	CGI->localPlayer = playerID;
 	human=true;
-	hInfo = CGI->bitmaph->loadBitmap("HEROQVBK.bmp");
-	SDL_SetColorKey(hInfo,SDL_SRCCOLORKEY,SDL_MapRGB(hInfo->format,0,255,255));
-	tInfo = CGI->bitmaph->loadBitmap("TOWNQVBK.bmp");
-	SDL_SetColorKey(tInfo,SDL_SRCCOLORKEY,SDL_MapRGB(tInfo->format,0,255,255));
-	slotsPos.push_back(std::pair<int,int>(44,82));
-	slotsPos.push_back(std::pair<int,int>(80,82));
-	slotsPos.push_back(std::pair<int,int>(116,82));
-	slotsPos.push_back(std::pair<int,int>(26,131));
-	slotsPos.push_back(std::pair<int,int>(62,131));
-	slotsPos.push_back(std::pair<int,int>(98,131));
-	slotsPos.push_back(std::pair<int,int>(134,131));
-
-	luck22 = CGI->spriteh->giveDefEss("ILCK22.DEF");
-	luck30 = CGI->spriteh->giveDefEss("ILCK30.DEF");
-	luck42 = CGI->spriteh->giveDefEss("ILCK42.DEF");
-	luck82 = CGI->spriteh->giveDefEss("ILCK82.DEF");
-	morale22 = CGI->spriteh->giveDefEss("IMRL22.DEF");
-	morale30 = CGI->spriteh->giveDefEss("IMRL30.DEF");
-	morale42 = CGI->spriteh->giveDefEss("IMRL42.DEF");
-	morale82 = CGI->spriteh->giveDefEss("IMRL82.DEF");
-	halls = CGI->spriteh->giveDefEss("ITMTLS.DEF");
-	forts = CGI->spriteh->giveDefEss("ITMCLS.DEF");
-	bigTownPic =  CGI->spriteh->giveDefEss("ITPT.DEF");
-
+	pim = new boost::mutex;
+}
+CPlayerInterface::~CPlayerInterface()
+{
+	delete pim;
 }
 void CPlayerInterface::init(ICallback * CB)
 {
 	cb = dynamic_cast<CCallback*>(CB);
-	CGI->localPlayer = serialID;
 	adventureInt = new CAdvMapInt(playerID);
 	castleInt = NULL;
 	std::vector <const CGHeroInstance *> hh = cb->getHeroesInfo(false);
 	for(int i=0;i<hh.size();i++)
 	{
 		SDL_Surface * pom = infoWin(hh[i]);
-		heroWins.insert(std::pair<int,SDL_Surface*>(hh[i]->subID,pom));
+		graphics->heroWins.insert(std::pair<int,SDL_Surface*>(hh[i]->subID,pom));
 	}
 	std::vector<const CGTownInstance*> tt = cb->getTownsInfo(false);
 	for(int i=0;i<tt.size();i++)
 	{
 		SDL_Surface * pom = infoWin(tt[i]);
-		townWins.insert(std::pair<int,SDL_Surface*>(tt[i]->identifier,pom));
+		graphics->townWins.insert(std::pair<int,SDL_Surface*>(tt[i]->identifier,pom));
 	}
 }
 void CPlayerInterface::yourTurn()
 {
+	LOCPLINT = this;
 	makingTurn = true;
-	CGI->localPlayer = serialID;
 	unsigned char & animVal = LOCPLINT->adventureInt->anim; //for animations handling
 	unsigned char & heroAnimVal = LOCPLINT->adventureInt->heroAnim;
 	adventureInt->infoBar.newDay(cb->getDate(1));
@@ -949,7 +960,7 @@ void CPlayerInterface::yourTurn()
 	//initializing framerate keeper
 	mainFPSmng = new FPSmanager;
 	SDL_initFramerate(mainFPSmng);
-	SDL_setFramerate(mainFPSmng, 24);
+	SDL_setFramerate(mainFPSmng, 48);
 	SDL_Event sEvent;
 	//framerate keeper initialized
 	timeHandler th;
@@ -985,7 +996,10 @@ void CPlayerInterface::yourTurn()
 		//	}
 		//}
 		//water tiles updated
-		CGI->screenh->updateScreen();
+		//CGI->screenh->updateScreen();
+
+		pim->lock();
+
 		int tv = th.getDif();
 		for (int i=0;i<timeinterested.size();i++)
 		{
@@ -995,14 +1009,17 @@ void CPlayerInterface::yourTurn()
 				timeinterested[i]->tick();
 		}
 		LOCPLINT->adventureInt->updateScreen = false;
-		while (SDL_PollEvent(&sEvent))  //wait for event...
+		eventsM.lock();
+		while(!events.empty())
 		{
-			handleEvent(&sEvent);
+			handleEvent(&events.front());
+			events.pop();
 		}
+		eventsM.unlock();
 		if (!castleInt) //stuff for advMapInt
 		{
 			++LOCPLINT->adventureInt->animValHitCount; //for animations
-			if(LOCPLINT->adventureInt->animValHitCount == 4)
+			if(LOCPLINT->adventureInt->animValHitCount == 8)
 			{
 				LOCPLINT->adventureInt->animValHitCount = 0;
 				++animVal;
@@ -1021,7 +1038,7 @@ void CPlayerInterface::yourTurn()
 			}
 			if(LOCPLINT->adventureInt->scrollingRight)
 			{
-				if(LOCPLINT->adventureInt->position.x<CGI->ac->map.width-19+4)
+				if(LOCPLINT->adventureInt->position.x<CGI->mh->map->width-19+4)
 				{
 					LOCPLINT->adventureInt->position.x++;
 					LOCPLINT->adventureInt->updateScreen = true;
@@ -1039,7 +1056,7 @@ void CPlayerInterface::yourTurn()
 			}
 			if(LOCPLINT->adventureInt->scrollingDown)
 			{
-				if(LOCPLINT->adventureInt->position.y<CGI->ac->map.height-18+4)
+				if(LOCPLINT->adventureInt->position.y<CGI->mh->map->height-18+4)
 				{
 					LOCPLINT->adventureInt->position.y++;
 					LOCPLINT->adventureInt->updateScreen = true;
@@ -1059,12 +1076,14 @@ void CPlayerInterface::yourTurn()
 		}
 		for(int i=0;i<objsToBlit.size();i++)
 			objsToBlit[i]->show();
-		//SDL_Flip(screen);
+		pim->unlock();
+		CGI->curh->draw1();
 		CSDL_Ext::update(screen);
-		SDL_Delay(5); //give time for other apps
+		CGI->curh->draw2();
 		SDL_framerateDelay(mainFPSmng);
 	}
 	adventureInt->hide();
+	cb->endTurn();
 }
 
 inline void subRect(const int & x, const int & y, const int & z, const SDL_Rect & r, const int & hid)
@@ -1127,6 +1146,7 @@ int getDir(int3 src, int3 dst)
 }
 void CPlayerInterface::heroMoved(const HeroMoveDetails & details)
 {
+	boost::unique_lock<boost::mutex> un(*pim);
 	//initializing objects and performing first step of move
 	CGHeroInstance * ho = details.ho; //object representing this hero
 	int3 hp = details.src;
@@ -1469,10 +1489,10 @@ void CPlayerInterface::heroMoved(const HeroMoveDetails & details)
 		}
 		LOCPLINT->adventureInt->update(); //updating screen
 		CSDL_Ext::update(screen);
-		CGI->screenh->updateScreen();
+		//CGI->screenh->updateScreen();
 
 		++LOCPLINT->adventureInt->animValHitCount; //for animations
-		if(LOCPLINT->adventureInt->animValHitCount == 4)
+		if(LOCPLINT->adventureInt->animValHitCount == 8)
 		{
 			LOCPLINT->adventureInt->animValHitCount = 0;
 			++LOCPLINT->adventureInt->anim;
@@ -1553,83 +1573,15 @@ void CPlayerInterface::heroMoved(const HeroMoveDetails & details)
 }
 void CPlayerInterface::heroKilled(const CGHeroInstance* hero)
 {
-	heroWins.erase(hero->ID);
+	boost::unique_lock<boost::mutex> un(*pim);
+	graphics->heroWins.erase(hero->ID);
+	adventureInt->heroList.updateHList();
 }
 void CPlayerInterface::heroCreated(const CGHeroInstance * hero)
 {
-	if(heroWins.find(hero->subID)==heroWins.end())
-		heroWins.insert(std::pair<int,SDL_Surface*>(hero->subID,infoWin(hero)));
-}
-
-SDL_Surface * CPlayerInterface::drawPrimarySkill(const CGHeroInstance *curh, SDL_Surface *ret, int from, int to)
-{
-	char * buf = new char[10];
-	for (int i=from;i<to;i++)
-	{
-		SDL_itoa(curh->primSkills[i],buf,10);
-		printAtMiddle(buf,84+28*i,68,GEOR13,zwykly,ret);
-	}
-	delete[] buf;
-	return ret;
-}
-SDL_Surface * CPlayerInterface::drawHeroInfoWin(const CGHeroInstance * curh)
-{
-	char * buf = new char[10];
-	blueToPlayersAdv(hInfo,playerID,1);
-	SDL_Surface * ret = SDL_DisplayFormat(hInfo);
-	SDL_SetColorKey(ret,SDL_SRCCOLORKEY,SDL_MapRGB(ret->format,0,255,255));
-	printAt(curh->name,75,15,GEOR13,zwykly,ret);
-	drawPrimarySkill(curh, ret);
-	for (std::map<int,std::pair<CCreature*,int> >::const_iterator i=curh->army.slots.begin(); i!=curh->army.slots.end();i++)
-	{
-		blitAt(CGI->creh->smallImgs[(*i).second.first->idNumber],slotsPos[(*i).first].first+1,slotsPos[(*i).first].second+1,ret);
-		SDL_itoa((*i).second.second,buf,10);
-		printAtMiddle(buf,slotsPos[(*i).first].first+17,slotsPos[(*i).first].second+39,GEORM,zwykly,ret);
-	}
-	blitAt(CGI->heroh->largePortraits[curh->portrait],11,12,ret);
-	SDL_itoa(curh->mana,buf,10);
-	printAtMiddle(buf,166,109,GEORM,zwykly,ret); //mana points
-	delete[] buf;
-	blitAt(morale22->ourImages[curh->getCurrentMorale()+3].bitmap,14,84,ret);
-	blitAt(luck22->ourImages[curh->getCurrentLuck()+3].bitmap,14,101,ret);
-	//SDL_SaveBMP(ret,"inf1.bmp");
-	return ret;
-}
-
-SDL_Surface * CPlayerInterface::drawTownInfoWin(const CGTownInstance * curh)
-{
-	char * buf = new char[10];
-	blueToPlayersAdv(tInfo,playerID,1);
-	SDL_Surface * ret = SDL_DisplayFormat(tInfo);
-	SDL_SetColorKey(ret,SDL_SRCCOLORKEY,SDL_MapRGB(ret->format,0,255,255));
-	printAt(curh->name,75,15,GEOR13,zwykly,ret);
-
-	int pom = curh->fortLevel() - 1; if(pom<0) pom = 3;
-	blitAt(forts->ourImages[pom].bitmap,115,42,ret);
-	if((pom=curh->hallLevel())>=0)
-		blitAt(halls->ourImages[pom].bitmap,77,42,ret);
-	SDL_itoa(curh->dailyIncome(),buf,10);
-	printAtMiddle(buf,167,70,GEORM,zwykly,ret);
-	for (std::map<int,std::pair<CCreature*,int> >::const_iterator i=curh->army.slots.begin(); i!=curh->army.slots.end();i++)
-	{
-		if(!i->second.first)
-			continue;
-		blitAt(CGI->creh->smallImgs[(*i).second.first->idNumber],slotsPos[(*i).first].first+1,slotsPos[(*i).first].second+1,ret);
-		SDL_itoa((*i).second.second,buf,10);
-		printAtMiddle(buf,slotsPos[(*i).first].first+17,slotsPos[(*i).first].second+39,GEORM,zwykly,ret);
-	}
-
-	//blit town icon
-	pom = curh->subID*2;
-	if (!curh->hasFort())
-		pom += F_NUMBER*2;
-	if(curh->builded >= MAX_BUILDING_PER_TURN)
-		pom++;
-	blitAt(bigTownPic->ourImages[pom].bitmap,13,13,ret);
-	delete[] buf;
-	return ret;
+	if(graphics->heroWins.find(hero->subID)==graphics->heroWins.end())
+		graphics->heroWins.insert(std::pair<int,SDL_Surface*>(hero->subID,infoWin(hero)));
 }
-
 void CPlayerInterface::openTownWindow(const CGTownInstance * town)
 {
 	adventureInt->hide();
@@ -1646,10 +1598,10 @@ SDL_Surface * CPlayerInterface::infoWin(const CGObjectInstance * specific) //spe
 		switch (specific->ID)
 		{
 		case 34:
-			return drawHeroInfoWin(dynamic_cast<const CGHeroInstance*>(specific));
+			return graphics->drawHeroInfoWin(dynamic_cast<const CGHeroInstance*>(specific));
 			break;
 		case 98:
-			return drawTownInfoWin(dynamic_cast<const CGTownInstance*>(specific));
+			return graphics->drawTownInfoWin(dynamic_cast<const CGTownInstance*>(specific));
 			break;
 		default:
 			return NULL;
@@ -1663,11 +1615,11 @@ SDL_Surface * CPlayerInterface::infoWin(const CGObjectInstance * specific) //spe
 		case HEROI_TYPE:
 			{
 				const CGHeroInstance * curh = (const CGHeroInstance *)adventureInt->selection.selected;
-				return drawHeroInfoWin(curh);
+				return graphics->drawHeroInfoWin(curh);
 			}
 		case TOWNI_TYPE:
 			{
-				return drawTownInfoWin((const CGTownInstance *)adventureInt->selection.selected);
+				return graphics->drawTownInfoWin((const CGTownInstance *)adventureInt->selection.selected);
 			}
 		default:
 			return NULL;
@@ -1844,7 +1796,6 @@ void CPlayerInterface::handleEvent(SDL_Event *sEvent)
 
 	else if ((sEvent->type==SDL_MOUSEBUTTONDOWN) && (sEvent->button.button == SDL_BUTTON_LEFT))
 	{
-		LOGE("Left mouse button down1");
 		for(int i=0; i<lclickable.size();i++)
 		{
 			if (isItIn(&lclickable[i]->pos,sEvent->motion.x,sEvent->motion.y))
@@ -1897,16 +1848,17 @@ int3 CPlayerInterface::repairScreenPos(int3 pos)
 		pos.x = -Woff+1;
 	if(pos.y<=-Hoff)
 		pos.y = -Hoff+1;
-	if(pos.x>CGI->mh->reader->map.width - this->adventureInt->terrain.tilesw + Woff)
-		pos.x = CGI->mh->reader->map.width - this->adventureInt->terrain.tilesw + Woff;
-	if(pos.y>CGI->mh->reader->map.height - this->adventureInt->terrain.tilesh + Hoff)
-		pos.y = CGI->mh->reader->map.height - this->adventureInt->terrain.tilesh + Hoff;
+	if(pos.x>CGI->mh->map->width - this->adventureInt->terrain.tilesw + Woff)
+		pos.x = CGI->mh->map->width - this->adventureInt->terrain.tilesw + Woff;
+	if(pos.y>CGI->mh->map->height - this->adventureInt->terrain.tilesh + Hoff)
+		pos.y = CGI->mh->map->height - this->adventureInt->terrain.tilesh + Hoff;
 	return pos;
 }
 void CPlayerInterface::heroPrimarySkillChanged(const CGHeroInstance * hero, int which, int val)
 {
-	SDL_FreeSurface(heroWins[hero->subID]);//TODO: moznaby zmieniac jedynie fragment bitmapy zwiazany z dana umiejetnoscia
-	heroWins[hero->subID] = infoWin(hero); //a nie przerysowywac calosc. Troche roboty, obecnie chyba nie wartej swieczki.
+	boost::unique_lock<boost::mutex> un(*pim);
+	SDL_FreeSurface(graphics->heroWins[hero->subID]);//TODO: moznaby zmieniac jedynie fragment bitmapy zwiazany z dana umiejetnoscia
+	graphics->heroWins[hero->subID] = infoWin(hero); //a nie przerysowywac calosc. Troche roboty, obecnie chyba nie wartej swieczki.
 	if (adventureInt->selection.selected == hero)
 		adventureInt->infoBar.draw();
 	return;
@@ -1942,13 +1894,14 @@ void CPlayerInterface::heroVisitsTown(const CGHeroInstance* hero, const CGTownIn
 }
 void CPlayerInterface::garrisonChanged(const CGObjectInstance * obj)
 {
+	boost::unique_lock<boost::mutex> un(*pim);
 	if(obj->ID == 34) //hero
 	{
 		const CGHeroInstance * hh;
 		if(hh = dynamic_cast<const CGHeroInstance*>(obj))
 		{
-			SDL_FreeSurface(heroWins[hh->subID]);
-			heroWins[hh->subID] = infoWin(hh);
+			SDL_FreeSurface(graphics->heroWins[hh->subID]);
+			graphics->heroWins[hh->subID] = infoWin(hh);
 		}
 		CHeroWindow * hw = dynamic_cast<CHeroWindow *>(curint);
 		if(hw)
@@ -1968,8 +1921,8 @@ void CPlayerInterface::garrisonChanged(const CGObjectInstance * obj)
 		const CGTownInstance * tt;
 		if(tt = dynamic_cast<const CGTownInstance*>(obj))
 		{
-			SDL_FreeSurface(townWins[tt->identifier]);
-			townWins[tt->identifier] = infoWin(tt);
+			SDL_FreeSurface(graphics->townWins[tt->identifier]);
+			graphics->townWins[tt->identifier] = infoWin(tt);
 		}
 
 		const CCastleInterface *ci = dynamic_cast<CCastleInterface*>(curint);
@@ -1986,6 +1939,7 @@ void CPlayerInterface::buildChanged(const CGTownInstance *town, int buildingID,
 		return;
 	if(castleInt->town!=town)
 		return;
+	boost::unique_lock<boost::mutex> un(*pim);
 	switch(what)
 	{
 	case 1:
@@ -1997,8 +1951,9 @@ void CPlayerInterface::buildChanged(const CGTownInstance *town, int buildingID,
 	}
 }
 
-void CPlayerInterface::battleStart(CCreatureSet * army1, CCreatureSet * army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, tribool side) //called by engine when battle starts; side=0 - left, side=1 - right
+void CPlayerInterface::battleStart(CCreatureSet *army1, CCreatureSet *army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, bool side) //called by engine when battle starts; side=0 - left, side=1 - right
 {
+	boost::unique_lock<boost::mutex> un(*pim);
 	curint->deactivate();
 	curint = new CBattleInterface(army1,army2,hero1,hero2);
 	curint->activate();
@@ -2025,45 +1980,28 @@ void CPlayerInterface::actionFinished(BattleAction action)//occurs AFTER every a
 
 BattleAction CPlayerInterface::activeStack(int stackID) //called when it's turn of that stack
 {
-	unsigned char showCount = 0;
-	dynamic_cast<CBattleInterface*>(curint)->stackActivated(stackID);
-	while(!dynamic_cast<CBattleInterface*>(curint)->givenCommand) //while current unit can perform an action
+	CBattleInterface *b = dynamic_cast<CBattleInterface*>(curint);
 	{
-		++showCount;
-		SDL_Event sEvent;
-		while (SDL_PollEvent(&sEvent))  //wait for event...
-		{
-			LOCPLINT->handleEvent(&sEvent);
-		}
-		if(showCount%2==0)
-			for(int i=0;i<objsToBlit.size();i++)
-				objsToBlit[i]->show();
-		//SDL_Flip(screen);
-		CSDL_Ext::update(screen);
+		boost::unique_lock<boost::mutex> un(*pim);
+		b->stackActivated(stackID);
+	}
+	//wait till BattleInterface sets its command
+	boost::unique_lock<boost::mutex> lock(b->givenCommand->mx);
+	while(!b->givenCommand->data)
+		b->givenCommand->cond.wait(lock);
 
-		/*timeHandler th;
-		th.getDif();
-		int tv = th.getDif();
-		for (int i=0;i<((CBattleInterface*)this->curint)->timeinterested.size();i++)
-		{
-			if (timeinterested[i]->toNextTick>=0)
-				timeinterested[i]->toNextTick-=tv;
-			if (timeinterested[i]->toNextTick<0)
-				timeinterested[i]->tick();
-		}*/
+	//tidy up
+	BattleAction ret = *(b->givenCommand->data);
+	delete b->givenCommand->data;
+	b->givenCommand->data = NULL;
 
-		SDL_Delay(1); //give time for other apps
-		SDL_framerateDelay(mainFPSmng);
-	}
-	BattleAction ret = *(dynamic_cast<CBattleInterface*>(curint)->givenCommand);
-	delete dynamic_cast<CBattleInterface*>(curint)->givenCommand;
-	dynamic_cast<CBattleInterface*>(curint)->givenCommand = NULL;
-	dynamic_cast<CBattleInterface*>(curint)->myTurn = false;
+	//return command
 	return ret;
 }
 
-void CPlayerInterface::battleEnd(CCreatureSet * army1, CCreatureSet * army2, CArmedInstance *hero1, CArmedInstance *hero2, std::vector<int> capturedArtifacts, int expForWinner, bool winner)
+void CPlayerInterface::battleEnd(BattleResult *br)
 {
+	boost::unique_lock<boost::mutex> un(*pim);
 	dynamic_cast<CBattleInterface*>(curint)->deactivate();
 	LOCPLINT->objsToBlit.erase(std::find(LOCPLINT->objsToBlit.begin(),LOCPLINT->objsToBlit.end(),dynamic_cast<IShowable*>(curint)));
 	delete dynamic_cast<CBattleInterface*>(curint);
@@ -2073,6 +2011,7 @@ void CPlayerInterface::battleEnd(CCreatureSet * army1, CCreatureSet * army2, CAr
 
 void CPlayerInterface::battleStackMoved(int ID, int dest, bool startMoving, bool endMoving)
 {
+	boost::unique_lock<boost::mutex> un(*pim);
 	dynamic_cast<CBattleInterface*>(curint)->stackMoved(ID, dest, startMoving, endMoving);
 }
 
@@ -2098,9 +2037,30 @@ void CPlayerInterface::battleStackIsShooting(int ID, int dest)
 
 void CPlayerInterface::showComp(SComponent comp)
 {
+	boost::unique_lock<boost::mutex> un(*pim);
 	adventureInt->infoBar.showComp(&comp,4000);
 }
 
+void CPlayerInterface::showInfoDialog(std::string text, std::vector<Component*> &components)
+{
+	curint->deactivate(); //dezaktywacja starego interfejsu
+	std::vector<SComponent*> intComps;
+	for(int i=0;i<components.size();i++)
+		intComps.push_back(new SComponent(*components[i]));
+	CInfoWindow * temp = CMessage::genIWindow(text,LOCPLINT->playerID,32,intComps);
+	LOCPLINT->objsToBlit.push_back(temp);
+	temp->pos.x=300-(temp->pos.w/2);
+	temp->pos.y=300-(temp->pos.h/2);
+	temp->okb.pos.x = temp->okb.posr.x + temp->pos.x;
+	temp->okb.pos.y = temp->okb.posr.y + temp->pos.y;
+	temp->okb.activate();
+	for (int i=0;i<temp->components.size();i++)
+	{
+		temp->components[i]->activate();
+		temp->components[i]->pos.x += temp->pos.x;
+		temp->components[i]->pos.y += temp->pos.y;
+	}
+}
 void CPlayerInterface::showInfoDialog(std::string text, std::vector<SComponent*> & components)
 {
 	curint->deactivate(); //dezaktywacja starego interfejsu
@@ -2141,12 +2101,12 @@ void CPlayerInterface::openHeroWindow(const CGHeroInstance *hero)
 }
 CStatusBar::CStatusBar(int x, int y, std::string name, int maxw)
 {
-	bg=CGI->bitmaph->loadBitmap(name);
+	bg=BitmapHandler::loadBitmap(name);
 	SDL_SetColorKey(bg,SDL_SRCCOLORKEY,SDL_MapRGB(bg->format,0,255,255));
 	pos.x=x;
 	pos.y=y;
 	if(maxw >= 0)
-		pos.w = std::min(bg->w,maxw);
+		pos.w = min(bg->w,maxw);
 	else
 		pos.w=bg->w;
 	pos.h=bg->h;
@@ -2218,12 +2178,12 @@ CHeroList::CHeroList(int Size)
 	posmanx = 666;
 	posmany = 213;
 
-	arrup = CGI->spriteh->giveDef("IAM012.DEF");
-	arrdo = CGI->spriteh->giveDef("IAM013.DEF");
-	mobile = CGI->spriteh->giveDef("IMOBIL.DEF");
-	mana = CGI->spriteh->giveDef("IMANA.DEF");
-	empty = CGI->bitmaph->loadBitmap("HPSXXX.bmp");
-	selection = CGI->bitmaph->loadBitmap("HPSYYY.bmp");
+	arrup = CDefHandler::giveDef("IAM012.DEF");
+	arrdo = CDefHandler::giveDef("IAM013.DEF");
+	mobile = CDefHandler::giveDef("IMOBIL.DEF");
+	mana = CDefHandler::giveDef("IMANA.DEF");
+	empty = BitmapHandler::loadBitmap("HPSXXX.bmp");
+	selection = BitmapHandler::loadBitmap("HPSYYY.bmp");
 	SDL_SetColorKey(selection,SDL_SRCCOLORKEY,SDL_MapRGB(selection->format,0,255,255));
 	from = 0;
 	pressed = indeterminate;
@@ -2382,7 +2342,7 @@ void CHeroList::clickRight(tribool down)
 		}
 
 		//show popup
-		CInfoPopup * ip = new CInfoPopup(LOCPLINT->heroWins[items[from+ny].first->subID],LOCPLINT->current->motion.x-LOCPLINT->heroWins[items[from+ny].first->subID]->w,LOCPLINT->current->motion.y-LOCPLINT->heroWins[items[from+ny].first->subID]->h,false);
+		CInfoPopup * ip = new CInfoPopup(graphics->heroWins[items[from+ny].first->subID],LOCPLINT->current->motion.x-graphics->heroWins[items[from+ny].first->subID]->w,LOCPLINT->current->motion.y-graphics->heroWins[items[from+ny].first->subID]->h,false);
 		ip->activate();
 	}
 	else
@@ -2435,7 +2395,7 @@ void CHeroList::draw()
 		if (pom>25) pom=25;
 		if (pom<0) pom=0;
 		blitAt(mana->ourImages[pom].bitmap,posmanx,posmany+i*32); //mana
-		SDL_Surface * temp = CGI->heroh->smallPortraits[LOCPLINT->cb->getHeroInfo(LOCPLINT->playerID,iT,0)->portrait];
+		SDL_Surface * temp = graphics->portraitSmall[LOCPLINT->cb->getHeroInfo(LOCPLINT->playerID,iT,0)->portrait];
 		blitAt(temp,posporx,pospory+i*32);
 		if ((selected == iT) && (LOCPLINT->adventureInt->selection.type == HEROI_TYPE))
 		{
@@ -2466,8 +2426,8 @@ CTownList::CTownList(int Size, SDL_Rect * Pos, int arupx, int arupy, int ardox,
 :CList(Size)
 {
 	pos = *Pos;
-	arrup = CGI->spriteh->giveDef("IAM014.DEF");
-	arrdo = CGI->spriteh->giveDef("IAM015.DEF");
+	arrup = CDefHandler::giveDef("IAM014.DEF");
+	arrdo = CDefHandler::giveDef("IAM015.DEF");
 
 	arrupp.x=arupx;
 	arrupp.y=arupy;
@@ -2532,7 +2492,7 @@ void CTownList::mouseMoved (SDL_MouseMotionEvent & sEvent)
 		LOCPLINT->statusbar->clear();
 		return;
 	};
-	LOCPLINT->statusbar->print(items[from+ny]->state->hoverText(const_cast<CGTownInstance*>(items[from+ny])));
+	LOCPLINT->statusbar->print(items[from+ny]->name);
 }
 
 void CTownList::clickLeft(tribool down)
@@ -2622,7 +2582,7 @@ void CTownList::clickRight(tribool down)
 		}
 
 		//show popup
-		CInfoPopup * ip = new CInfoPopup(LOCPLINT->townWins[items[from+ny]->identifier],LOCPLINT->current->motion.x-LOCPLINT->townWins[items[from+ny]->identifier]->w,LOCPLINT->current->motion.y-LOCPLINT->townWins[items[from+ny]->identifier]->h,false);
+		CInfoPopup * ip = new CInfoPopup(graphics->townWins[items[from+ny]->identifier],LOCPLINT->current->motion.x-graphics->townWins[items[from+ny]->identifier]->w,LOCPLINT->current->motion.y-graphics->townWins[items[from+ny]->identifier]->h,false);
 		ip->activate();
 	}
 	else
@@ -2647,15 +2607,15 @@ void CTownList::draw()
 		int i = iT-from;
 		if (iT>=items.size())
 		{
-			blitAt(CGI->townh->getPic(-1),posporx,pospory+i*32);
+			blitAt(graphics->getPic(-1),posporx,pospory+i*32);
 			continue;
 		}
 
-		blitAt(CGI->townh->getPic(items[iT]->subID,items[iT]->hasFort(),items[iT]->builded),posporx,pospory+i*32);
+		blitAt(graphics->getPic(items[iT]->subID,items[iT]->hasFort(),items[iT]->builded),posporx,pospory+i*32);
 
 		if ((selected == iT) && (LOCPLINT->adventureInt->selection.type == TOWNI_TYPE))
 		{
-			blitAt(CGI->townh->getPic(-2),posporx,pospory+i*32);
+			blitAt(graphics->getPic(-2),posporx,pospory+i*32);
 		}
 	}
 	if (from>0)
@@ -2681,7 +2641,7 @@ CCreaturePic::~CCreaturePic()
 }
 int CCreaturePic::blitPic(SDL_Surface *to, int x, int y, bool nextFrame)
 {
-	blitAt(CGI->creh->backgrounds[c->faction],x,y);//curx-50,pos.y+130-65);
+	blitAt(graphics->backgrounds[c->faction],x,y);//curx-50,pos.y+130-65);
 	SDL_Rect dst = genRect(130,100,x,y);
 	if(c->isDoubleWide())
 		x-=15;
@@ -2725,7 +2685,7 @@ void CRecrutationWindow::clickLeft(tribool down)
 		if(isItIn(&genRect(132,102,pos.x+curx,pos.y+64),LOCPLINT->current->motion.x,LOCPLINT->current->motion.y))
 		{
 			which = i;
-			int newAmount = std::min(amounts[i],creatures[i].amount);
+			int newAmount = min(amounts[i],creatures[i].amount);
 			slider->amount = newAmount;
 			if(slider->value > newAmount)
 				slider->moveTo(newAmount);
@@ -2780,8 +2740,8 @@ void CRecrutationWindow::show(SDL_Surface * to)
 	int curx = pos.x+115-creatures[which].res.size()*16;
 	for(int i=0;i<creatures[which].res.size();i++)
 	{
-		blitAt(CGI->townh->resources->ourImages[creatures[which].res[i].first].bitmap,curx,pos.y+243,screen);
-		blitAt(CGI->townh->resources->ourImages[creatures[which].res[i].first].bitmap,curx+258,pos.y+243,screen);
+		blitAt(graphics->resources32->ourImages[creatures[which].res[i].first].bitmap,curx,pos.y+243,screen);
+		blitAt(graphics->resources32->ourImages[creatures[which].res[i].first].bitmap,curx+258,pos.y+243,screen);
 		SDL_itoa(creatures[which].res[i].second,pom,10);
 		printAtMiddle(pom,curx+12,pos.y+286,GEOR13,zwykly,screen);
 		SDL_itoa(creatures[which].res[i].second * slider->value,pom,10);
@@ -2813,8 +2773,8 @@ CRecrutationWindow::CRecrutationWindow(const std::vector<std::pair<int,int> > &C
 		creatures[i].pic = new CCreaturePic(&CGI->creh->creatures[Creatures[i].first]);
 		amounts[i] = CGI->creh->creatures[Creatures[i].first].maxAmount(LOCPLINT->cb->getResourceAmount());
 	}
-	SDL_Surface *hhlp = CGI->bitmaph->loadBitmap("TPRCRT.bmp");
-	blueToPlayersAdv(hhlp,LOCPLINT->playerID);
+	SDL_Surface *hhlp = BitmapHandler::loadBitmap("TPRCRT.bmp");
+	graphics->blueToPlayersAdv(hhlp,LOCPLINT->playerID);
 	bitmap = SDL_ConvertSurface(hhlp,screen->format,0); //na 8bitowej mapie by sie psulo
 	SDL_SetColorKey(bitmap,SDL_SRCCOLORKEY,SDL_MapRGB(bitmap->format,0,255,255));
 	SDL_FreeSurface(hhlp);
@@ -2822,7 +2782,7 @@ CRecrutationWindow::CRecrutationWindow(const std::vector<std::pair<int,int> > &C
 	pos.y = screen->h/2 - bitmap->h/2;
 	pos.w = bitmap->w;
 	pos.h = bitmap->h;
-	slider = new CSlider(pos.x+176,pos.y+279,135,boost::bind(&CRecrutationWindow::sliderMoved,this, _1),1,std::min(amounts[0],creatures[0].amount),0,true);
+	slider = new CSlider(pos.x+176,pos.y+279,135,boost::bind(&CRecrutationWindow::sliderMoved,this, _1),1,min(amounts[0],creatures[0].amount),0,true);
 	std::string pom;
 	printAtMiddle(CGI->generaltexth->allTexts[346],113,231,GEOR13,zwykly,bitmap); //cost per troop t
 	printAtMiddle(CGI->generaltexth->allTexts[465],205,231,GEOR13,zwykly,bitmap); //available t
@@ -2876,7 +2836,7 @@ CSplitWindow::CSplitWindow(int cid, int max, CGarrisonInt *Owner)
 	c=cid;
 	slider = NULL;
 	gar = Owner;
-	bitmap = CGI->bitmaph->loadBitmap("GPUCRDIV.bmp");
+	bitmap = BitmapHandler::loadBitmap("GPUCRDIV.bmp");
 	SDL_SetColorKey(bitmap,SDL_SRCCOLORKEY,SDL_MapRGB(bitmap->format,0,255,255));
 	pos.x = screen->w/2 - bitmap->w/2;
 	pos.y = screen->h/2 - bitmap->h/2;
@@ -2976,12 +2936,12 @@ CCreInfoWindow::CCreInfoWindow
 :ok(0),dismiss(0),upgrade(0),type(Type),dsm(Dsm)
 {
 	c = &CGI->creh->creatures[Cid];
-	bitmap = CGI->bitmaph->loadBitmap("CRSTKPU.bmp");
+	bitmap = BitmapHandler::loadBitmap("CRSTKPU.bmp");
 	pos.x = screen->w/2 - bitmap->w/2;
 	pos.y = screen->h/2 - bitmap->h/2;
 	pos.w = bitmap->w;
 	pos.h = bitmap->h;
-	blueToPlayersAdv(bitmap,LOCPLINT->playerID);
+	graphics->blueToPlayersAdv(bitmap,LOCPLINT->playerID);
 	SDL_SetColorKey(bitmap,SDL_SRCCOLORKEY,SDL_MapRGB(bitmap->format,0,255,255));
 	anim = new CCreaturePic(c);
 	if(!type) anim->anim->setType(1);
@@ -3045,8 +3005,8 @@ CCreInfoWindow::CCreInfoWindow
 
 
 	//luck and morale
-	blitAt(LOCPLINT->morale42->ourImages[(State)?(State->morale+3):(3)].bitmap,24,189,bitmap);
-	blitAt(LOCPLINT->luck42->ourImages[(State)?(State->luck+3):(3)].bitmap,77,189,bitmap);
+	blitAt(graphics->morale42->ourImages[(State)?(State->morale+3):(3)].bitmap,24,189,bitmap);
+	blitAt(graphics->luck42->ourImages[(State)?(State->luck+3):(3)].bitmap,77,189,bitmap);
 
 	//print abilities text - if r-click popup
 	if(type)

+ 23 - 24
CPlayerInterface.h

@@ -25,6 +25,11 @@ class CCreatureSet;
 class CGObjectInstance;
 class CSlider;
 
+namespace boost
+{
+	class mutex;
+};
+
 class IShowable
 {
 public:
@@ -154,7 +159,7 @@ public:
 };
 
 class CInfoWindow : public CSimpleWindow //text + comp. + ok button
-{ //okno usuwa swoje komponenty w chwili zamkniecia
+{ //window deletes its components when closed
 public:
 	CSCButton<CInfoWindow> okb;
 	std::vector<SComponent*> components;
@@ -207,8 +212,9 @@ public:
 	std::string description; //r-click
 	std::string subtitle;
 
+	void init(Etype Type, int Subtype, int Val);
 	SComponent(Etype Type, int Subtype, int Val);
-	//SComponent(const & SComponent r);
+	SComponent(const Component &c);
 
 	void clickRight (boost::logic::tribool down);
 	virtual SDL_Surface * getImg();
@@ -290,17 +296,20 @@ public:
 class CPlayerInterface : public CGameInterface
 {
 public:
+	//minor interfaces
+	boost::mutex *pim;
 	bool makingTurn;
-		SDL_Event * current;
+	SDL_Event * current;
 	IActivable *curint;
 	CAdvMapInt * adventureInt;
 	CCastleInterface * castleInt;
 	FPSmanager * mainFPSmng;
 	IStatusBar *statusbar;
-	//TODO: town interace, battle interface, other interfaces
 
+	//to commucate with engine
 	CCallback * cb;
 
+	//GUI elements
 	std::vector<ClickableL*> lclickable;
 	std::vector<ClickableR*> rclickable;
 	std::vector<Hoverable*> hoverable;
@@ -309,15 +318,7 @@ public:
 	std::vector<TimeInterested*> timeinterested;
 	std::vector<IShowable*> objsToBlit;
 
-	SDL_Surface * hInfo, *tInfo;
-	std::vector<std::pair<int, int> > slotsPos;
-	CDefEssential *luck22, *luck30, *luck42, *luck82,
-		*morale22, *morale30, *morale42, *morale82,
-		*halls, *forts, *bigTownPic;
-	std::map<int,SDL_Surface*> heroWins;
-	std::map<int,SDL_Surface*> townWins;
-
-	//overloaded funcs from Interface
+	//overloaded funcs from CGameInterface
 	void yourTurn();
 	void heroMoved(const HeroMoveDetails & details);
 	void tileRevealed(int3 pos);
@@ -326,19 +327,19 @@ public:
 	void heroCreated(const CGHeroInstance* hero);
 	void heroPrimarySkillChanged(const CGHeroInstance * hero, int which, int val);
 	void receivedResource(int type, int val);
+	void showInfoDialog(std::string text, std::vector<Component*> &components);
 	void showSelDialog(std::string text, std::vector<CSelectableComponent*> & components, int askID);
 	void heroVisitsTown(const CGHeroInstance* hero, const CGTownInstance * town);
 	void garrisonChanged(const CGObjectInstance * obj);
 	void buildChanged(const CGTownInstance *town, int buildingID, int what); //what: 1 - built, 2 - demolished
-
-	//battles
-	void battleStart(CCreatureSet * army1, CCreatureSet * army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, boost::logic::tribool side); //called by engine when battle starts; side=0 - left, side=1 - right
+	//for battles
+	void battleStart(CCreatureSet *army1, CCreatureSet *army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2, bool side); //called by engine when battle starts; side=0 - left, side=1 - right
 	void battlefieldPrepared(int battlefieldType, std::vector<CObstacle*> obstacles); //called when battlefield is prepared, prior the battle beginning
 	void battleNewRound(int round); //called at the beggining of each turn, round=-1 is the tactic phase, round=0 is the first "normal" turn
 	void actionStarted(BattleAction action);//occurs BEFORE every action taken by any stack or by the hero
 	void actionFinished(BattleAction action);//occurs AFTER every action taken by any stack or by the hero
 	BattleAction activeStack(int stackID); //called when it's turn of that stack
-	void battleEnd(CCreatureSet * army1, CCreatureSet * army2, CArmedInstance *hero1, CArmedInstance *hero2, std::vector<int> capturedArtifacts, int expForWinner, bool winner);
+	void battleEnd(BattleResult *br);
 	void battleStackMoved(int ID, int dest, bool startMoving, bool endMoving);
 	void battleStackAttacking(int ID, int dest);
 	void battleStackIsAttacked(int ID, int dmg, int killed, int IDby, bool byShooting);
@@ -349,7 +350,6 @@ public:
 	//-------------//
 
 	void showComp(SComponent comp);
-
 	void openTownWindow(const CGTownInstance * town); //shows townscreen
 	void openHeroWindow(const CGHeroInstance * hero); //shows hero window with given hero
 	SDL_Surface * infoWin(const CGObjectInstance * specific); //specific=0 => draws info about selected town/hero //TODO - gdy sie dorobi sensowna hierarchie klas ins. to wywalic tego brzydkiego void*
@@ -359,14 +359,11 @@ public:
 	void handleMouseMotion(SDL_Event *sEvent);
 	void init(ICallback * CB);
 	int3 repairScreenPos(int3 pos);
+	void removeObjToBlit(IShowable* obj);	
 	void showInfoDialog(std::string text, std::vector<SComponent*> & components);
-	void removeObjToBlit(IShowable* obj);
-	SDL_Surface * drawHeroInfoWin(const CGHeroInstance * curh);
-	SDL_Surface * drawPrimarySkill(const CGHeroInstance *curh, SDL_Surface *ret, int from=0, int to=PRIMARY_SKILLS);
 
-	SDL_Surface * drawTownInfoWin(const CGTownInstance * curh);
-
-	CPlayerInterface(int Player, int serial);
+	CPlayerInterface(int Player, int serial);//c-tor
+	~CPlayerInterface();//d-tor
 };
 class CStatusBar
 	: public CIntObject, public IStatusBar
@@ -537,4 +534,6 @@ public:
 	void show(SDL_Surface * to = NULL);
 };
 
+extern CPlayerInterface * LOCPLINT;
+
 #endif //CPLAYERINTERFACE_H

+ 163 - 127
CPreGame.cpp

@@ -1,5 +1,6 @@
 #include "stdafx.h"
 #include "CPreGame.h"
+#include "hch/CDefHandler.h"
 #include "SDL.h"
 #include "boost/filesystem.hpp"   // includes all needed Boost.Filesystem declarations
 #include "boost/algorithm/string.hpp"
@@ -11,16 +12,22 @@
 #include "CGameInfo.h"
 #include "hch/CGeneralTextHandler.h"
 #include "CCursorHandler.h"
-#include "CScreenHandler.h"
 #include "hch/CLodHandler.h"
 #include "hch/CTownHandler.h"
 #include "hch/CHeroHandler.h"
 #include <cmath>
-
+#include "client/Graphics.h"
+#include <boost/thread.hpp>
+#include <boost/bind.hpp>
 extern SDL_Surface * screen;
 extern SDL_Color tytulowy, tlo, zwykly ;
 extern TTF_Font * TNRB16, *TNR, *GEOR13, *GEORXX, *GEORM;
-
+#ifdef min
+#undef min
+#endif
+#ifdef max
+#undef max
+#endif
 SDL_Rect genRect(int hh, int ww, int xx, int yy);
 SDL_Color genRGB(int r, int g, int b, int a=0);
 //void printAt(std::string text, int x, int y, TTF_Font * font, SDL_Color kolor=tytulowy, SDL_Surface * dst=screen);
@@ -162,16 +169,16 @@ Slider::Slider(int x, int y, int h, int amnt, int cap, bool ver)
 	if (ver)
 	{
 		pos = genRect(h,16,x,y);
-		down = Button(genRect(16,16,x,y+h-16),boost::bind(&Slider::moveDown,this),CGI->spriteh->giveDef("SCNRBDN.DEF"),false);
-		up = Button(genRect(16,16,x,y),boost::bind(&Slider::moveUp,this),CGI->spriteh->giveDef("SCNRBUP.DEF"),false);
-		slider = Button(genRect(16,16,x,y+16),boost::function<void()>(),CGI->spriteh->giveDef("SCNRBSL.DEF"),false);
+		down = Button(genRect(16,16,x,y+h-16),boost::bind(&Slider::moveDown,this),CDefHandler::giveDef("SCNRBDN.DEF"),false);
+		up = Button(genRect(16,16,x,y),boost::bind(&Slider::moveUp,this),CDefHandler::giveDef("SCNRBUP.DEF"),false);
+		slider = Button(genRect(16,16,x,y+16),boost::function<void()>(),CDefHandler::giveDef("SCNRBSL.DEF"),false);
 	}
 	else
 	{
 		pos = genRect(16,h,x,y);
-		down = Button(genRect(16,16,x+h-16,y),boost::bind(&Slider::moveDown,this),CGI->spriteh->giveDef("SCNRBRT.DEF"),false);
-		up = Button(genRect(16,16,x,y),boost::bind(&Slider::moveUp,this),CGI->spriteh->giveDef("SCNRBLF.DEF"),false);
-		slider = Button(genRect(16,16,x+16,y),boost::function<void()>(),CGI->spriteh->giveDef("SCNRBSL.DEF"),false);
+		down = Button(genRect(16,16,x+h-16,y),boost::bind(&Slider::moveDown,this),CDefHandler::giveDef("SCNRBRT.DEF"),false);
+		up = Button(genRect(16,16,x,y),boost::bind(&Slider::moveUp,this),CDefHandler::giveDef("SCNRBLF.DEF"),false);
+		slider = Button(genRect(16,16,x+16,y),boost::function<void()>(),CDefHandler::giveDef("SCNRBSL.DEF"),false);
 	}
 	moving = false;
 	whereAreWe=0;
@@ -447,7 +454,7 @@ void Options::OptionSwitch::press(bool down)
 				for (;;)
 				{
 					ourOpt->castle+=dir;
-					if (((int)pow((double)2,ourOpt->castle))&ourInf->allowedFactions)
+					if (((int)pow((double)2,(int)ourOpt->castle))&ourInf->allowedFactions)
 					{
 						break;
 					}
@@ -585,7 +592,7 @@ void Options::showIcon (int what, int nr, bool abs) //what: -1=castle, 0=hero, 1
 			int pom=ourOpt->castle;
 			if (ourOpt->castle<F_NUMBER && ourOpt->castle>=0)
 			{
-				blitAtWR(CGI->townh->getPic(ourOpt->castle,true,false),176,130+50*se);
+				blitAtWR(graphics->getPic(ourOpt->castle,true,false),176,130+50*se);
 			}
 			else if (ourOpt->castle==-1)
 			{
@@ -608,7 +615,8 @@ void Options::showIcon (int what, int nr, bool abs) //what: -1=castle, 0=hero, 1
 			{
 				if(ourOpt->heroPortrait>=0)
 				{
-					blitAtWR(CGI->heroh->smallPortraits[ourOpt->heroPortrait],252,130+50*se);
+					//TODO: restore drawing hero portrait
+					//blitAtWR(CGI->heroh->heroes[ourOpt->heroPortrait]->portraitSmall,252,130+50*se);
 				}
 				else
 				{
@@ -617,7 +625,8 @@ void Options::showIcon (int what, int nr, bool abs) //what: -1=castle, 0=hero, 1
 			}
 			else
 			{
-				blitAtWR(CGI->heroh->smallPortraits[pom],252,130+50*se);
+				//TODO: restore drawing hero portrait
+				//blitAtWR(CGI->heroh->heroes[pom]->portraitSmall,252,130+50*se);
 			}
 			break;
 		}
@@ -664,35 +673,35 @@ Options::~Options()
 void Options::init()
 {
 	inited=true;
-	bg = CGI->bitmaph->loadBitmap("ADVOPTBK.bmp");
+	bg = BitmapHandler::loadBitmap("ADVOPTBK.bmp");
 	SDL_SetColorKey(bg,SDL_SRCCOLORKEY,SDL_MapRGB(bg->format,0,255,255));
-	left = CGI->spriteh->giveDef("ADOPLFA.DEF");
-	right = CGI->spriteh->giveDef("ADOPRTA.DEF");
-	bonuses = CGI->spriteh->giveDef("SCNRSTAR.DEF");
-	rHero = CGI->bitmaph->loadBitmap("HPSRAND1.bmp");
-	rCastle = CGI->bitmaph->loadBitmap("HPSRAND0.bmp");
-	nHero = CGI->bitmaph->loadBitmap("HPSRAND6.bmp");
-	nCastle = CGI->bitmaph->loadBitmap("HPSRAND5.bmp");
+	left = CDefHandler::giveDef("ADOPLFA.DEF");
+	right = CDefHandler::giveDef("ADOPRTA.DEF");
+	bonuses = CDefHandler::giveDef("SCNRSTAR.DEF");
+	rHero = BitmapHandler::loadBitmap("HPSRAND1.bmp");
+	rCastle = BitmapHandler::loadBitmap("HPSRAND0.bmp");
+	nHero = BitmapHandler::loadBitmap("HPSRAND6.bmp");
+	nCastle = BitmapHandler::loadBitmap("HPSRAND5.bmp");
 	turnLength = new Slider(57,557,195,11,1,false);
 	turnLength->fun=boost::bind(&CPreGame::setTurnLength,CPG,_1);
 
-	flags.push_back(CGI->spriteh->giveDef("AOFLGBR.DEF"));
-	flags.push_back(CGI->spriteh->giveDef("AOFLGBB.DEF"));
-	flags.push_back(CGI->spriteh->giveDef("AOFLGBY.DEF"));
-	flags.push_back(CGI->spriteh->giveDef("AOFLGBG.DEF"));
-	flags.push_back(CGI->spriteh->giveDef("AOFLGBO.DEF"));
-	flags.push_back(CGI->spriteh->giveDef("AOFLGBP.DEF"));
-	flags.push_back(CGI->spriteh->giveDef("AOFLGBT.DEF"));
-	flags.push_back(CGI->spriteh->giveDef("AOFLGBS.DEF"));
-
-	bgs.push_back(CGI->bitmaph->loadBitmap("ADOPRPNL.bmp"));
-	bgs.push_back(CGI->bitmaph->loadBitmap("ADOPBPNL.bmp"));
-	bgs.push_back(CGI->bitmaph->loadBitmap("ADOPYPNL.bmp"));
-	bgs.push_back(CGI->bitmaph->loadBitmap("ADOPGPNL.bmp"));
-	bgs.push_back(CGI->bitmaph->loadBitmap("ADOPOPNL.bmp"));
-	bgs.push_back(CGI->bitmaph->loadBitmap("ADOPPPNL.bmp"));
-	bgs.push_back(CGI->bitmaph->loadBitmap("ADOPTPNL.bmp"));
-	bgs.push_back(CGI->bitmaph->loadBitmap("ADOPSPNL.bmp"));
+	flags.push_back(CDefHandler::giveDef("AOFLGBR.DEF"));
+	flags.push_back(CDefHandler::giveDef("AOFLGBB.DEF"));
+	flags.push_back(CDefHandler::giveDef("AOFLGBY.DEF"));
+	flags.push_back(CDefHandler::giveDef("AOFLGBG.DEF"));
+	flags.push_back(CDefHandler::giveDef("AOFLGBO.DEF"));
+	flags.push_back(CDefHandler::giveDef("AOFLGBP.DEF"));
+	flags.push_back(CDefHandler::giveDef("AOFLGBT.DEF"));
+	flags.push_back(CDefHandler::giveDef("AOFLGBS.DEF"));
+
+	bgs.push_back(BitmapHandler::loadBitmap("ADOPRPNL.bmp"));
+	bgs.push_back(BitmapHandler::loadBitmap("ADOPBPNL.bmp"));
+	bgs.push_back(BitmapHandler::loadBitmap("ADOPYPNL.bmp"));
+	bgs.push_back(BitmapHandler::loadBitmap("ADOPGPNL.bmp"));
+	bgs.push_back(BitmapHandler::loadBitmap("ADOPOPNL.bmp")); 
+	bgs.push_back(BitmapHandler::loadBitmap("ADOPPPNL.bmp"));
+	bgs.push_back(BitmapHandler::loadBitmap("ADOPTPNL.bmp"));
+	bgs.push_back(BitmapHandler::loadBitmap("ADOPSPNL.bmp"));
 }
 void Options::show()
 {
@@ -970,27 +979,88 @@ void MapSel::show()
 	//SDL_Flip(screen);
 	CSDL_Ext::update(screen);
 }
+boost::mutex mx;
+void MapSel::processMaps(std::vector<std::string> &pliczkiTemp, int &index)
+{
+	bool areMaps=true;
+	int pom=-1;
+	while(areMaps)
+	{
+		mx.lock();
+		if(index>=pliczkiTemp.size())
+		{
+			mx.unlock();
+			break;
+		}
+		else
+		{
+			pom = index++;
+			mx.unlock();
+		}
+		gzFile tempf = gzopen(pliczkiTemp[pom].c_str(),"rb");
+		unsigned char * sss = new unsigned char[1000];
+		int iii=0;
+		while(true)
+		{
+			if (iii>=1000) break;
+			int z = gzgetc (tempf);
+			if (z>=0) 
+			{
+				sss[iii++] = (unsigned char)z;
+			}
+			else break;
+		}
+		gzclose(tempf);
+		if(iii<50) {std::cout<<"\t\tWarning: corrupted map file: "<<pliczkiTemp[pom]<<std::endl; continue;}
+		if (!sss[4]) continue; //nie ma graczy? mapa niegrywalna //ju¿ to kiedyœ komentowa³em- - to bzdura //tu calkiem pasuje...
+		CMapInfo mi(pliczkiTemp[pom],sss);
+		mx.lock();
+		ourMaps.push_back(mi);
+		mx.unlock();
+		delete[] sss;
+	}
+}
+
 void MapSel::init()
 {
-	bg = CGI->bitmaph->loadBitmap("SCSELBCK.bmp");
+	//get map files names
+	std::vector<std::string> pliczkiTemp;
+	fs::path tie( (fs::initial_path<fs::path>())/"/maps" );
+	fs::directory_iterator end_iter;
+	for ( fs::directory_iterator dir (tie); dir!=end_iter; ++dir )
+	{
+		if (fs::is_regular(dir->status()));
+		{
+			if (boost::ends_with(dir->path().leaf(),std::string(".h3m")))
+				pliczkiTemp.push_back("Maps/"+(dir->path().leaf()));
+		}
+	}
+
+	int mapInd=0;
+	boost::thread_group group;
+	int cores = std::max((unsigned int)1,boost::thread::hardware_concurrency());
+	for(int ti=0;ti<cores;ti++)
+		group.create_thread(boost::bind(&MapSel::processMaps,this,boost::ref(pliczkiTemp),boost::ref(mapInd)));
+
+	bg = BitmapHandler::loadBitmap("SCSELBCK.bmp");
 	SDL_SetColorKey(bg,SDL_SRCCOLORKEY,SDL_MapRGB(bg->format,0,255,255));
-	small.imgs = CGI->spriteh->giveDef("SCSMBUT.DEF");
+	small.imgs = CDefHandler::giveDef("SCSMBUT.DEF");
 	small.fun = NULL;
 	small.pos = genRect(small.imgs->ourImages[0].bitmap->h,small.imgs->ourImages[0].bitmap->w,161,52);
 	small.ourGroup=NULL;
-	medium.imgs = CGI->spriteh->giveDef("SCMDBUT.DEF");
+	medium.imgs = CDefHandler::giveDef("SCMDBUT.DEF");
 	medium.fun = NULL;
 	medium.pos = genRect(medium.imgs->ourImages[0].bitmap->h,medium.imgs->ourImages[0].bitmap->w,208,52);
 	medium.ourGroup=NULL;
-	large.imgs = CGI->spriteh->giveDef("SCLGBUT.DEF");
+	large.imgs = CDefHandler::giveDef("SCLGBUT.DEF");
 	large.fun = NULL;
 	large.pos = genRect(large.imgs->ourImages[0].bitmap->h,large.imgs->ourImages[0].bitmap->w,255,52);
 	large.ourGroup=NULL;
-	xlarge.imgs = CGI->spriteh->giveDef("SCXLBUT.DEF");
+	xlarge.imgs = CDefHandler::giveDef("SCXLBUT.DEF");
 	xlarge.fun = NULL;
 	xlarge.pos = genRect(xlarge.imgs->ourImages[0].bitmap->h,xlarge.imgs->ourImages[0].bitmap->w,302,52);
 	xlarge.ourGroup=NULL;
-	all.imgs = CGI->spriteh->giveDef("SCALBUT.DEF");
+	all.imgs = CDefHandler::giveDef("SCALBUT.DEF");
 	all.fun = NULL;
 	all.pos = genRect(all.imgs->ourImages[0].bitmap->h,all.imgs->ourImages[0].bitmap->w,349,52);
 	all.ourGroup=NULL;
@@ -998,32 +1068,32 @@ void MapSel::init()
 	small.what=medium.what=large.what=xlarge.what=all.what=&sizeFilter;
 	small.key=36;medium.key=72;large.key=108;xlarge.key=144;all.key=0;
 //Button<> nrplayer, mapsize, type, name, viccon, loscon;
-	nrplayer.imgs = CGI->spriteh->giveDef("SCBUTT1.DEF");
+	nrplayer.imgs = CDefHandler::giveDef("SCBUTT1.DEF");
 	nrplayer.fun = NULL;
 	nrplayer.pos = genRect(nrplayer.imgs->ourImages[0].bitmap->h,nrplayer.imgs->ourImages[0].bitmap->w,26,92);
 	nrplayer.key=_playerAm;
 
-	mapsize.imgs = CGI->spriteh->giveDef("SCBUTT2.DEF");
+	mapsize.imgs = CDefHandler::giveDef("SCBUTT2.DEF");
 	mapsize.fun = NULL;
 	mapsize.pos = genRect(mapsize.imgs->ourImages[0].bitmap->h,mapsize.imgs->ourImages[0].bitmap->w,58,92);
 	mapsize.key=_size;
 
-	type.imgs = CGI->spriteh->giveDef("SCBUTCP.DEF");
+	type.imgs = CDefHandler::giveDef("SCBUTCP.DEF");
 	type.fun = NULL;
 	type.pos = genRect(type.imgs->ourImages[0].bitmap->h,type.imgs->ourImages[0].bitmap->w,91,92);
 	type.key=_format;
 
-	name.imgs = CGI->spriteh->giveDef("SCBUTT3.DEF");
+	name.imgs = CDefHandler::giveDef("SCBUTT3.DEF");
 	name.fun = NULL;
 	name.pos = genRect(name.imgs->ourImages[0].bitmap->h,name.imgs->ourImages[0].bitmap->w,124,92);
 	name.key=_name;
 
-	viccon.imgs = CGI->spriteh->giveDef("SCBUTT4.DEF");
+	viccon.imgs = CDefHandler::giveDef("SCBUTT4.DEF");
 	viccon.fun = NULL;
 	viccon.pos = genRect(viccon.imgs->ourImages[0].bitmap->h,viccon.imgs->ourImages[0].bitmap->w,309,92);
 	viccon.key=_viccon;
 
-	loscon.imgs = CGI->spriteh->giveDef("SCBUTT5.DEF");
+	loscon.imgs = CDefHandler::giveDef("SCBUTT5.DEF");
 	loscon.fun = NULL;
 	loscon.pos = genRect(loscon.imgs->ourImages[0].bitmap->h,loscon.imgs->ourImages[0].bitmap->w,342,92);
 	loscon.key=_loscon;
@@ -1031,49 +1101,13 @@ void MapSel::init()
 	nrplayer.poin=mapsize.poin=type.poin=name.poin=viccon.poin=loscon.poin=(int*)(&sortBy);
 	nrplayer.fun=mapsize.fun=type.fun=name.fun=viccon.fun=loscon.fun=boost::bind(&CPreGame::sortMaps,CPG);
 
-	Dtypes = CGI->spriteh->giveDef("SCSELC.DEF");
-	Dvic = CGI->spriteh->giveDef("SCNRVICT.DEF");
-	Dloss = CGI->spriteh->giveDef("SCNRLOSS.DEF");
+	Dtypes = CDefHandler::giveDef("SCSELC.DEF");
+	Dvic = CDefHandler::giveDef("SCNRVICT.DEF");
+	Dloss = CDefHandler::giveDef("SCNRLOSS.DEF");
 	//Dsizes = CPG->slh->giveDef("SCNRMPSZ.DEF");
-	Dsizes = CGI->spriteh->giveDef("SCNRMPSZ.DEF");
-	sFlags = CGI->spriteh->giveDef("ITGFLAGS.DEF");
-	//get map files names
-	std::vector<std::string> pliczkiTemp;
-	fs::path tie( (fs::initial_path<fs::path>())/"/maps" );
-	fs::directory_iterator end_iter;
-	for ( fs::directory_iterator dir (tie); dir!=end_iter; ++dir )
-	{
-		if (fs::is_regular(dir->status()));
-		{
-			if (boost::ends_with(dir->path().leaf(),std::string(".h3m")))
-				pliczkiTemp.push_back("Maps/"+(dir->path().leaf()));
-		}
-	}
-	for (int i=0; i<pliczkiTemp.size();i++)
-	{
-		gzFile tempf = gzopen(pliczkiTemp[i].c_str(),"rb");
-		std::string sss;
-		int iii=0;
-		while(++iii)
-		{
-			if (iii>4000) break;
-			int z = gzgetc (tempf);
-			if (z>=0)
-			{
-				sss+=(unsigned char)z;
-			}
-			else break;
-		}
-		gzclose(tempf);
-		//if (sss[0]<28) continue; //zly format
-		if(iii<5) {std::cout<<"\t\tWarning: corrupted map file: "<<pliczkiTemp[i]<<std::endl; continue;}
-		if (!sss[4]) continue; //nie ma graczy? mapa niegrywalna //ju? to kiedy? komentowa?em- - to bzdura //tu calkiem pasuje...
-		unsigned char* file2 = new unsigned char[sss.length()];
-		for (int j=0;j<sss.length();j++)
-			file2[j]=sss[j];
-		ourMaps.push_back(CMapInfo(pliczkiTemp[i],file2));
-		delete[] file2;
-	}
+	Dsizes = CDefHandler::giveDef("SCNRMPSZ.DEF");
+	sFlags = CDefHandler::giveDef("ITGFLAGS.DEF");
+	group.join_all();
 	std::sort(ourMaps.begin(),ourMaps.end(),mapSorter(_name));
 	slid = new Slider(375,92,480,ourMaps.size(),18,true);
 	slid->fun = boost::bind(&CPreGame::printMapsFrom,CPG,_1);
@@ -1105,6 +1139,7 @@ void MapSel::select(int which, bool updateMapsList, bool forceSettingsUpdate)
 {
 	bool dontSaveSettings = ((selected!=which) || (CPG->ret.playerInfos.size()==0) || forceSettingsUpdate);
 	selected = which;
+	CPG->ret.mapname = ourMaps[selected].filename;
 	if(updateMapsList)
 		printMaps(slid->whereAreWe,18,0,true);
 	int serialC=0;
@@ -1385,14 +1420,14 @@ void CPreGame::initScenSel()
 {
 	ourScenSel = new ScenSel();
 	ourScenSel->listShowed=false;
-	if (rand()%2) ourScenSel->background=CGI->bitmaph->loadBitmap("ZPIC1000.bmp");
-	else ourScenSel->background=CGI->bitmaph->loadBitmap("ZPIC1001.bmp");
+	if (rand()%2) ourScenSel->background=BitmapHandler::loadBitmap("ZPIC1000.bmp");
+	else ourScenSel->background=BitmapHandler::loadBitmap("ZPIC1001.bmp");
 
 	ourScenSel->pressed=NULL;
 
-	ourScenSel->scenInf=CGI->bitmaph->loadBitmap("GSELPOP1.bmp");//SDL_LoadBMP("h3bitmap.lod\\GSELPOP1.bmp");
-	ourScenSel->randMap=CGI->bitmaph->loadBitmap("RANMAPBK.bmp");
-	ourScenSel->options=CGI->bitmaph->loadBitmap("ADVOPTBK.bmp");
+	ourScenSel->scenInf=BitmapHandler::loadBitmap("GSELPOP1.bmp");//SDL_LoadBMP("h3bitmap.lod\\GSELPOP1.bmp");
+	ourScenSel->randMap=BitmapHandler::loadBitmap("RANMAPBK.bmp");
+	ourScenSel->options=BitmapHandler::loadBitmap("ADVOPTBK.bmp");
 	SDL_SetColorKey(ourScenSel->scenInf,SDL_SRCCOLORKEY,SDL_MapRGB(ourScenSel->scenInf->format,0,255,255));
 	//SDL_SetColorKey(ourScenSel->scenList,SDL_SRCCOLORKEY,SDL_MapRGB(ourScenSel->scenList->format,0,255,255));
 	SDL_SetColorKey(ourScenSel->randMap,SDL_SRCCOLORKEY,SDL_MapRGB(ourScenSel->randMap->format,0,255,255));
@@ -1402,22 +1437,22 @@ void CPreGame::initScenSel()
 	ourScenSel->difficulty->type=1;
 	ourScenSel->selectedDiff=-77;
 	ourScenSel->difficulty->gdzie = &ourScenSel->selectedDiff;
-	ourScenSel->bEasy = IntSelBut(genRect(0,0,506,456),NULL,CGI->spriteh->giveDef("GSPBUT3.DEF"),true,ourScenSel->difficulty,0);
-	ourScenSel->bNormal = IntSelBut(genRect(0,0,538,456),NULL,CGI->spriteh->giveDef("GSPBUT4.DEF"),true,ourScenSel->difficulty,1);
-	ourScenSel->bHard = IntSelBut(genRect(0,0,570,456),NULL,CGI->spriteh->giveDef("GSPBUT5.DEF"),true,ourScenSel->difficulty,2);
-	ourScenSel->bExpert = IntSelBut(genRect(0,0,602,456),NULL,CGI->spriteh->giveDef("GSPBUT6.DEF"),true,ourScenSel->difficulty,3);
-	ourScenSel->bImpossible = IntSelBut(genRect(0,0,634,456),NULL,CGI->spriteh->giveDef("GSPBUT7.DEF"),true,ourScenSel->difficulty,4);
+	ourScenSel->bEasy = IntSelBut(genRect(0,0,506,456),NULL,CDefHandler::giveDef("GSPBUT3.DEF"),true,ourScenSel->difficulty,0);
+	ourScenSel->bNormal = IntSelBut(genRect(0,0,538,456),NULL,CDefHandler::giveDef("GSPBUT4.DEF"),true,ourScenSel->difficulty,1);
+	ourScenSel->bHard = IntSelBut(genRect(0,0,570,456),NULL,CDefHandler::giveDef("GSPBUT5.DEF"),true,ourScenSel->difficulty,2);
+	ourScenSel->bExpert = IntSelBut(genRect(0,0,602,456),NULL,CDefHandler::giveDef("GSPBUT6.DEF"),true,ourScenSel->difficulty,3);
+	ourScenSel->bImpossible = IntSelBut(genRect(0,0,634,456),NULL,CDefHandler::giveDef("GSPBUT7.DEF"),true,ourScenSel->difficulty,4);
 
-	ourScenSel->bBack = Button(genRect(0,0,584,535),boost::bind(&CPreGame::showNewMenu,this),CGI->spriteh->giveDef("SCNRBACK.DEF"));
-	ourScenSel->bBegin = Button(genRect(0,0,414,535),boost::bind(&CPreGame::begin,this),CGI->spriteh->giveDef("SCNRBEG.DEF"));
+	ourScenSel->bBack = Button(genRect(0,0,584,535),boost::bind(&CPreGame::showNewMenu,this),CDefHandler::giveDef("SCNRBACK.DEF"));
+	ourScenSel->bBegin = Button(genRect(0,0,414,535),boost::bind(&CPreGame::begin,this),CDefHandler::giveDef("SCNRBEG.DEF"));
+	ourScenSel->bScens = Button(genRect(0,0,414,81),boost::bind(&CPreGame::showScenList,this),CDefHandler::giveDef("GSPBUTT.DEF"));
 
-	ourScenSel->bScens = Button(genRect(0,0,414,81),boost::bind(&CPreGame::showScenList,this),CGI->spriteh->giveDef("GSPBUTT.DEF"));
 	for (int i=0; i<ourScenSel->bScens.imgs->ourImages.size(); i++)
 		CSDL_Ext::printAt(CGI->generaltexth->allTexts[500],25+i,2+i,GEOR13,zwykly,ourScenSel->bScens.imgs->ourImages[i].bitmap); //"Show Available Scenarios"
-	ourScenSel->bRandom = Button(genRect(0,0,414,105),boost::bind(&CPreGame::showScenList,this),CGI->spriteh->giveDef("GSPBUTT.DEF"));
+	ourScenSel->bRandom = Button(genRect(0,0,414,105),boost::bind(&CPreGame::showScenList,this),CDefHandler::giveDef("GSPBUTT.DEF"));
 	for (int i=0; i<ourScenSel->bRandom.imgs->ourImages.size(); i++)
 		CSDL_Ext::printAt(CGI->generaltexth->allTexts[740],25+i,2+i,GEOR13,zwykly,ourScenSel->bRandom.imgs->ourImages[i].bitmap);
-	ourScenSel->bOptions = Button(genRect(0,0,414,509),boost::bind(&CPreGame::showOptions,this),CGI->spriteh->giveDef("GSPBUTT.DEF"));
+	ourScenSel->bOptions = Button(genRect(0,0,414,509),boost::bind(&CPreGame::showOptions,this),CDefHandler::giveDef("GSPBUTT.DEF"));
 	for (int i=0; i<ourScenSel->bOptions.imgs->ourImages.size(); i++)
 		CSDL_Ext::printAt(CGI->generaltexth->allTexts[501],25+i,2+i,GEOR13,zwykly,ourScenSel->bOptions.imgs->ourImages[i].bitmap); //"Show Advanced Options"
 
@@ -1510,17 +1545,17 @@ void CPreGame::showOptions()
 void CPreGame::initNewMenu()
 {
 	ourNewMenu = new menuItems();
-	ourNewMenu->bgAd = CGI->bitmaph->loadBitmap("ZNEWGAM.bmp");
-	ourNewMenu->background = CGI->bitmaph->loadBitmap("ZPIC1005.bmp");
+	ourNewMenu->bgAd = BitmapHandler::loadBitmap("ZNEWGAM.bmp");
+	ourNewMenu->background = BitmapHandler::loadBitmap("ZPIC1005.bmp");
 	blitAt(ourNewMenu->bgAd,114,312,ourNewMenu->background);
 	 //loading menu buttons
-	ourNewMenu->newGame = CGI->spriteh->giveDef("ZTSINGL.DEF");
-	ourNewMenu->loadGame = CGI->spriteh->giveDef("ZTMULTI.DEF");
-	ourNewMenu->highScores = CGI->spriteh->giveDef("ZTCAMPN.DEF");
-	ourNewMenu->credits = CGI->spriteh->giveDef("ZTTUTOR.DEF");
-	ourNewMenu->quit = CGI->spriteh->giveDef("ZTBACK.DEF");
-	ok = CGI->spriteh->giveDef("IOKAY.DEF");
-	cancel = CGI->spriteh->giveDef("ICANCEL.DEF");
+	ourNewMenu->newGame = CDefHandler::giveDef("ZTSINGL.DEF");
+	ourNewMenu->loadGame = CDefHandler::giveDef("ZTMULTI.DEF");
+	ourNewMenu->highScores = CDefHandler::giveDef("ZTCAMPN.DEF");
+	ourNewMenu->credits = CDefHandler::giveDef("ZTTUTOR.DEF");
+	ourNewMenu->quit = CDefHandler::giveDef("ZTBACK.DEF");
+	ok = CDefHandler::giveDef("IOKAY.DEF");
+	cancel = CDefHandler::giveDef("ICANCEL.DEF");
 	// single scenario
 	ourNewMenu->lNewGame.h=ourNewMenu->newGame->ourImages[0].bitmap->h;
 	ourNewMenu->lNewGame.w=ourNewMenu->newGame->ourImages[0].bitmap->w;
@@ -1572,15 +1607,15 @@ void CPreGame::showNewMenu()
 void CPreGame::initMainMenu()
 {
 	ourMainMenu = new menuItems();
-	ourMainMenu->background = CGI->bitmaph->loadBitmap("ZPIC1005.bmp"); //SDL_LoadBMP("h3bitmap.lod\\ZPIC1005.bmp");
+	ourMainMenu->background = BitmapHandler::loadBitmap("ZPIC1005.bmp"); //SDL_LoadBMP("h3bitmap.lod\\ZPIC1005.bmp");
 	 //loading menu buttons
-	ourMainMenu->newGame = CGI->spriteh->giveDef("ZMENUNG.DEF");
-	ourMainMenu->loadGame = CGI->spriteh->giveDef("ZMENULG.DEF");
-	ourMainMenu->highScores = CGI->spriteh->giveDef("ZMENUHS.DEF");
-	ourMainMenu->credits = CGI->spriteh->giveDef("ZMENUCR.DEF");
-	ourMainMenu->quit = CGI->spriteh->giveDef("ZMENUQT.DEF");
-	ok = CGI->spriteh->giveDef("IOKAY.DEF");
-	cancel = CGI->spriteh->giveDef("ICANCEL.DEF");
+	ourMainMenu->newGame = CDefHandler::giveDef("ZMENUNG.DEF");
+	ourMainMenu->loadGame = CDefHandler::giveDef("ZMENULG.DEF");
+	ourMainMenu->highScores = CDefHandler::giveDef("ZMENUHS.DEF");
+	ourMainMenu->credits = CDefHandler::giveDef("ZMENUCR.DEF");
+	ourMainMenu->quit = CDefHandler::giveDef("ZMENUQT.DEF");
+	ok = CDefHandler::giveDef("IOKAY.DEF");
+	cancel = CDefHandler::giveDef("ICANCEL.DEF");
 	// new game button location
 	ourMainMenu->lNewGame.h=ourMainMenu->newGame->ourImages[0].bitmap->h;
 	ourMainMenu->lNewGame.w=ourMainMenu->newGame->ourImages[0].bitmap->w;
@@ -1820,7 +1855,6 @@ StartInfo CPreGame::runLoop()
 	SDL_Event sEvent;
 	while(run)
 	{
-		CGI->screenh->updateScreen();
 		try
 		{
 			if(SDL_PollEvent(&sEvent))  //wait for event...
@@ -2077,8 +2111,10 @@ StartInfo CPreGame::runLoop()
 		}
 		catch(...)
 		{ continue; }
-
-		SDL_Delay(1); //give time for other apps
+		CGI->curh->draw1();
+		SDL_Flip(screen);
+		CGI->curh->draw2();
+		SDL_Delay(20); //give time for other apps
 	}
 	return ret;
 }

+ 4 - 4
CPreGame.h

@@ -4,16 +4,15 @@
 #include <set>
 #include "SDL.h"
 #include "StartInfo.h"
-#include "hch/CSemiDefHandler.h"
-#include "hch/CSemiLodHandler.h"
-#include "hch/CPreGameTextHandler.h"
+#include "hch/CPreGameTextHandler.h" 
 #include "CMessage.h"
 #include "map.h"
 #include "hch/CMusicHandler.h"
 #include <boost/function.hpp>
 #include <boost/bind.hpp>
 class CPreGame;
-extern class CPreGame *CPG;
+class CDefHandler;
+extern CPreGame * CPG;
 
 typedef void(CPreGame::*ttt)();
 class CGroup;
@@ -204,6 +203,7 @@ public:
 	void moveByOne(bool up);
 	void printSelectedInfo();
 	void printFlags();
+	void processMaps(std::vector<std::string> &pliczkiTemp, int &index);
 	MapSel();
 	~MapSel();
 };

+ 0 - 45
CScreenHandler.cpp

@@ -1,45 +0,0 @@
-#include "stdafx.h"
-#include "CScreenHandler.h"
-#include "SDL.h"
-#include "SDL_thread.h"
-#include "SDL_framerate.h"
-#include "SDL_Extensions.h"
-#include "CCursorHandler.h"
-#include "CGameInfo.h"
-#include "hch/CDefHandler.h"
-
-extern SDL_Surface * screen, * screen2;
-
-void CScreenHandler::initScreen()
-{
-	//myth = SDL_CreateThread(&internalScreenFunc, this);
-}
-
-void CScreenHandler::updateScreen()
-{
-	/*blitAt(screen, 0, 0, screen2);
-	switch(CGI->curh->mode)
-	{
-	case 0:
-		{
-			blitAt(CGI->curh->adventure->ourImages[CGI->curh->number].bitmap, CGI->curh->xpos, CGI->curh->ypos, screen2);
-			break;
-		}
-	case 1:
-		{
-			blitAt(CGI->curh->combat->ourImages[CGI->curh->number].bitmap, CGI->curh->xpos, CGI->curh->ypos, screen2);
-			break;
-		}
-	case 2:
-		{
-			blitAt(CGI->curh->deflt->ourImages[CGI->curh->number].bitmap, CGI->curh->xpos, CGI->curh->ypos, screen2);
-			break;
-		}
-	case 3:
-		{
-			blitAt(CGI->curh->spell->ourImages[CGI->curh->number].bitmap, CGI->curh->xpos, CGI->curh->ypos, screen2);
-			break;
-		}
-	}
-	CSDL_Ext::update(screen2);*/
-}

+ 0 - 17
CScreenHandler.h

@@ -1,17 +0,0 @@
-#ifndef CSCREENHANDLER_H
-#define CSCREENHANDLER_H
-
-struct SDL_Thread;
-
-class CScreenHandler
-{
-private:
-	SDL_Thread * myth;
-public:
-	void initScreen();
-	void updateScreen();
-};
-
-
-
-#endif //CSCREENHANDLER_H

+ 0 - 1
ChangeLog

@@ -1 +0,0 @@
-

二進制
DefSorter.exe


+ 45 - 37
Makefile.am

@@ -1,40 +1,48 @@
 ACLOCAL_AMFLAGS = -I aclocal/m4
 EXTRA_DIST = aclocal/m4
-bin_PROGRAMS = vcmi
-vcmi_LDADD = $(BOOST_SYSTEM_LIB) $(BOOST_FILESYSTEM_LIB)
+#bin_PROGRAMS = vcmi
+#vcmi_LDADD = $(BOOST_SYSTEM_LIB) $(BOOST_FILESYSTEM_LIB) $(BOOST_THREAD_LIB)
 AM_CXXFLAGS = $(BOOST_CPPFLAGS)
-vcmi_SOURCES = \
-	       AdventureMapButton.cpp  CGameState.cpp        CScreenHandler.h \
-	       AdventureMapButton.h    CGameState.h          global.h \
-	       AI_Base.h               CHeroWindow.cpp       int3.h \
-	       CAdvmapInterface.cpp    CHeroWindow.h         map.cpp \
-	       CAdvmapInterface.h      CLua.cpp              map.h \
-	       CBattleInterface.cpp    CLua.h                mapHandler.cpp \
-	       CBattleInterface.h      CLuaHandler.cpp       mapHandler.h \
-	       CCallback.cpp           CLuaHandler.h         nodrze.h \
-	       CCallback.h             CMessage.cpp          SDL_Extensions.cpp \
-	       CCastleInterface.cpp    CMessage.h            SDL_Extensions.h \
-	       CCastleInterface.h      CMT.cpp               SDL_framerate.cpp \
-	       CConsoleHandler.cpp     SDL_framerate.h \
-	       CConsoleHandler.h       CPathfinder.cpp       SDL_rotozoom.cpp \
-	       CCursorHandler.cpp      CPathfinder.h         SDL_rotozoom.h \
-	       CCursorHandler.h        CPlayerInterface.cpp  StartInfo.h \
-	       CGameInfo.cpp           CPlayerInterface.h    stdafx.cpp \
-	       CGameInfo.h             CPreGame.cpp          stdafx.h \
-	       CGameInterface.cpp      CPreGame.h            tchar_amigaos4.h \
-	       CGameInterface.h        CScreenHandler.cpp    timeHandler.h \
-	       hch/CAbilityHandler.cpp   hch/CDefObjInfoHandler.cpp   hch/CSemiDefHandler.cpp \
-	       hch/CAbilityHandler.h     hch/CDefObjInfoHandler.h     hch/CSemiDefHandler.h \
-	       hch/CAmbarCendamo.cpp     hch/CGeneralTextHandler.cpp  hch/CSemiLodHandler.cpp \
-	       hch/CAmbarCendamo.h       hch/CGeneralTextHandler.h    hch/CSemiLodHandler.h \
-	       hch/CArtHandler.cpp       hch/CHeroHandler.cpp         hch/CSndHandler.cpp \
-	       hch/CArtHandler.h         hch/CHeroHandler.h           hch/CSndHandler.h \
-	       hch/CBuildingHandler.cpp  hch/CLodHandler.cpp          hch/CSpellHandler.cpp \
-	       hch/CBuildingHandler.h    hch/CLodHandler.h            hch/CSpellHandler.h \
-	       hch/CCastleHandler.cpp    hch/CMusicHandler.cpp        hch/CTownHandler.cpp \
-	       hch/CCastleHandler.h      hch/CMusicHandler.h          hch/CTownHandler.h \
-	       hch/CCreatureHandler.cpp  hch/CObjectHandler.cpp       hch/CVideoHandler.cpp \
-	       hch/CCreatureHandler.h    hch/CObjectHandler.h         hch/CVideoHandler.h \
-	       hch/CDefHandler.cpp       hch/CPreGameTextHandler.cpp \
-	       hch/CDefHandler.h         hch/CPreGameTextHandler.h 
-
+SUBDIRS = lib client server
+#vcmi_SOURCES = \
+#	       AdventureMapButton.cpp  CGameState.cpp        \
+#	       AdventureMapButton.h    CGameState.h          global.h \
+#	       AI_Base.h               CHeroWindow.cpp       int3.h \
+#	       CAdvmapInterface.cpp    CHeroWindow.h         map.cpp \
+#	       CAdvmapInterface.h      CLua.cpp              map.h \
+#	       CBattleInterface.cpp    CLua.h                mapHandler.cpp \
+#	       CBattleInterface.h      CLuaHandler.cpp       mapHandler.h \
+#	       CCallback.cpp           CLuaHandler.h         nodrze.h \
+#	       CCallback.h             CMessage.cpp          SDL_Extensions.cpp \
+#	       CCastleInterface.cpp    CMessage.h            SDL_Extensions.h \
+#	       CCastleInterface.h      CMT.cpp               SDL_framerate.cpp \
+#	       CConsoleHandler.cpp     SDL_framerate.h \
+#	       CConsoleHandler.h       CPathfinder.cpp       \
+#	       CCursorHandler.cpp      CPathfinder.h         \
+#	       CCursorHandler.h        CPlayerInterface.cpp  StartInfo.h \
+#	       CGameInfo.cpp           CPlayerInterface.h    stdafx.cpp \
+#	       CGameInfo.h             CPreGame.cpp          stdafx.h \
+#	       CGameInterface.cpp      CPreGame.h            tchar_amigaos4.h \
+#	       CGameInterface.h        timeHandler.h \
+#	       hch/CAbilityHandler.cpp   hch/CDefObjInfoHandler.cpp   \
+#	       hch/CAbilityHandler.h     hch/CDefObjInfoHandler.h     \
+#	       hch/CAmbarCendamo.cpp     hch/CGeneralTextHandler.cpp  \
+#	       hch/CAmbarCendamo.h       hch/CGeneralTextHandler.h    \
+#	       hch/CArtHandler.cpp       hch/CHeroHandler.cpp         hch/CSndHandler.cpp \
+#	       hch/CArtHandler.h         hch/CHeroHandler.h           hch/CSndHandler.h \
+#	       hch/CBuildingHandler.cpp  hch/CLodHandler.cpp          hch/CSpellHandler.cpp \
+#	       hch/CBuildingHandler.h    hch/CLodHandler.h            hch/CSpellHandler.h \
+#	       hch/CMusicHandler.cpp        hch/CTownHandler.cpp \
+#	       hch/CMusicHandler.h          hch/CTownHandler.h \
+#	       hch/CCreatureHandler.cpp  hch/CObjectHandler.cpp       hch/CVideoHandler.cpp \
+#	       hch/CCreatureHandler.h    hch/CObjectHandler.h         hch/CVideoHandler.h \
+#	       hch/CDefHandler.cpp       hch/CPreGameTextHandler.cpp \
+#	       hch/CDefHandler.h         hch/CPreGameTextHandler.h \
+#client/CBitmapHandler.cpp  client/CCreatureAnimation.cpp  client/Client.cpp  client/Graphics.cpp \
+#client/CBitmapHandler.h    client/CCreatureAnimation.h    client/Client.h    client/Graphics.h \
+#lib/VCMI_Lib.h lib/VCMI_Lib.cpp \
+#		server/CScriptCallback.h server/CScriptCallback.cpp \
+#		lib/Connection.cpp lib/Connection.h \
+#		CThreadHelper.cpp CThreadHelper.h
+#
+#

+ 0 - 1
NEWS

@@ -1 +0,0 @@
-

二進制
Projekt.dia


+ 0 - 1
README

@@ -1 +0,0 @@
-

+ 4 - 184
SDL_Extensions.cpp

@@ -9,8 +9,7 @@
 #include <boost/algorithm/string.hpp>
 #include "hch/CDefHandler.h"
 #include <map>
-
-extern SDL_Color playerColorPalette[256];
+#include "client/Graphics.h"
 
 SDL_Surface * CSDL_Ext::newSurface(int w, int h, SDL_Surface * mod) //creates new surface, with flags/format same as in surface given
 {
@@ -416,45 +415,6 @@ SDL_Surface * CSDL_Ext::rotate03(SDL_Surface * toRot)
 	}
 	return ret;
 }
- //converts surface to cursor
-SDL_Cursor * CSDL_Ext::SurfaceToCursor(SDL_Surface *image, int hx, int hy)
-{
-	int             w, x, y;
-	Uint8           *data, *mask, *d, *m, r, g, b;
-	Uint32          color;
-	SDL_Cursor      *cursor;
-
-	w = (image->w + 7) / 8;
-	data = (Uint8 *)alloca(w * image->h * 2);
-	if (data == NULL)
-		return NULL;
-	memset(data, 0, w * image->h * 2);
-	mask = data + w * image->h;
-	if (SDL_MUSTLOCK(image))
-		SDL_LockSurface(image);
-	for (y = 0; y < image->h; y++)
-	{
-		d = data + y * w;
-		m = mask + y * w;
-		for (x = 0; x < image->w; x++)
-		{
-			color = CSDL_Ext::SDL_GetPixel(image, x, y);
-			if ((image->flags & SDL_SRCCOLORKEY) == 0 || color != image->format->colorkey)
-			{
-				SDL_GetRGB(color, image->format, &r, &g, &b);
-				color = (r + g + b) / 3;
-				m[x / 8] |= 128 >> (x & 7);
-				if (color < 128)
-					d[x / 8] |= 128 >> (x & 7);
-			}
-		}
-	}
-	if (SDL_MUSTLOCK(image))
-		SDL_UnlockSurface(image);
-	cursor = SDL_CreateCursor(data, mask, w, image->h, hx, hy);
-	return cursor;
-}
-
 Uint32 CSDL_Ext::SDL_GetPixel(SDL_Surface *surface, const int & x, const int & y, bool colorByte)
 {
     int bpp = surface->format->BytesPerPixel;
@@ -486,7 +446,7 @@ Uint32 CSDL_Ext::SDL_GetPixel(SDL_Surface *surface, const int & x, const int & y
         return *(Uint32 *)p;
 
     default:
-        return 0;       /* shouldn't happen, but avoids warnings */
+        return 0;       // shouldn't happen, but avoids warnings 
     }
 }
 
@@ -545,11 +505,6 @@ SDL_Surface * CSDL_Ext::alphaTransform(SDL_Surface *src)
 	return src;
 }
 
-SDL_Surface * CSDL_Ext::secondAlphaTransform(SDL_Surface * src, SDL_Surface * alpha)
-{
-	return copySurface(src);
-}
-
 int CSDL_Ext::blit8bppAlphaTo24bpp(SDL_Surface * src, SDL_Rect * srcRect, SDL_Surface * dst, SDL_Rect * dstRect)
 {
 	static std::map<Uint8, int> st;
@@ -747,132 +702,6 @@ void CSDL_Ext::update(SDL_Surface * what)
 	if(what)
 		SDL_UpdateRect(what, 0, 0, what->w, what->h);
 }
-
-void CSDL_Ext::blueToPlayers(SDL_Surface * sur, int player)
-{
-	if(sur->format->BitsPerPixel == 8)
-	{
-		for(int i=0; i<sur->format->palette->ncolors; ++i)
-		{
-			SDL_Color * cc = sur->format->palette->colors+i;
-			if(cc->r==0 && cc->g==0 && cc->b==255)
-			{
-				cc->r = CGameInfo::mainObj->playerColors[player].r;
-				cc->g = CGameInfo::mainObj->playerColors[player].g;
-				cc->b = CGameInfo::mainObj->playerColors[player].b;
-			}
-		}
-	}
-	else if(sur->format->BitsPerPixel == 24)
-	{
-		for(int y=0; y<sur->h; ++y)
-		{
-			for(int x=0; x<sur->w; ++x)
-			{
-				Uint8* cp = (Uint8*)sur->pixels + y+sur->pitch + x*3;
-/*
-				if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
-				{
-					if(cp[0]==0 && cp[1]==0 && cp[2]==255)
-					{
-						cp[0] = CGameInfo::mainObj->playerColors[player].r;
-						cp[1] = CGameInfo::mainObj->playerColors[player].g;
-						cp[2] = CGameInfo::mainObj->playerColors[player].b;
-					}
-				}
-				else
-				{
-
-*/
-					if(cp[0]==255 && cp[1]==0 && cp[2]==0)
-					{
-						cp[0] = CGameInfo::mainObj->playerColors[player].b;
-						cp[1] = CGameInfo::mainObj->playerColors[player].g;
-						cp[2] = CGameInfo::mainObj->playerColors[player].r;
-					}
-//				}
-			}
-		}
-	}
-}
-
-void CSDL_Ext::blueToPlayersAdv(SDL_Surface * sur, int player, int mode, void* additionalInfo)
-{
-	if(player==1) //it is actually blue...
-		return;
-	if(sur->format->BitsPerPixel == 8)
-	{
-		for(int i=0; i<32; ++i)
-		{
-			sur->format->palette->colors[224+i] = playerColorPalette[32*player+i];
-		}
-	}
-	else if(sur->format->BitsPerPixel == 24) //should never happen in general
-	{
-		for(int y=0; y<sur->h; ++y)
-		{
-			for(int x=0; x<sur->w; ++x)
-			{
-				Uint8* cp = (Uint8*)sur->pixels + y*sur->pitch + x*3;
-/*
-				if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
-				{
-					if(cp[2]>cp[1] && cp[2]>cp[0])
-					{
-						std::vector<long long int> sort1;
-						sort1.push_back(cp[0]);
-						sort1.push_back(cp[1]);
-						sort1.push_back(cp[2]);
-						std::vector< std::pair<long long int, Uint8*> > sort2;
-						sort2.push_back(std::make_pair(CGameInfo::mainObj->playerColors[player].r, &(cp[0])));
-						sort2.push_back(std::make_pair(CGameInfo::mainObj->playerColors[player].g, &(cp[1])));
-						sort2.push_back(std::make_pair(CGameInfo::mainObj->playerColors[player].b, &(cp[2])));
-						std::sort(sort1.begin(), sort1.end());
-						if(sort2[0].first>sort2[1].first)
-							std::swap(sort2[0], sort2[1]);
-						if(sort2[1].first>sort2[2].first)
-							std::swap(sort2[1], sort2[2]);
-						if(sort2[0].first>sort2[1].first)
-							std::swap(sort2[0], sort2[1]);
-						for(int hh=0; hh<3; ++hh)
-						{
-							(*sort2[hh].second) = (sort1[hh] + sort2[hh].first)/2.2;
-						}
-					}
-				}
-				else
-*/
-				{
-					if(
-						((mode==0) && (cp[0]>cp[1]) && (cp[0]>cp[2])) ||
-						((mode==1) && (cp[2]<45) && (cp[0]>80) && (cp[1]<70) && ((cp[0]-cp[1])>40))
-					  )
-					{
-						std::vector<long long int> sort1;
-						sort1.push_back(cp[2]);
-						sort1.push_back(cp[1]);
-						sort1.push_back(cp[0]);
-						std::vector< std::pair<long long int, Uint8*> > sort2;
-						sort2.push_back(std::make_pair(CGameInfo::mainObj->playerColors[player].r, &(cp[2])));
-						sort2.push_back(std::make_pair(CGameInfo::mainObj->playerColors[player].g, &(cp[1])));
-						sort2.push_back(std::make_pair(CGameInfo::mainObj->playerColors[player].b, &(cp[0])));
-						std::sort(sort1.begin(), sort1.end());
-						if(sort2[0].first>sort2[1].first)
-							std::swap(sort2[0], sort2[1]);
-						if(sort2[1].first>sort2[2].first)
-							std::swap(sort2[1], sort2[2]);
-						if(sort2[0].first>sort2[1].first)
-							std::swap(sort2[0], sort2[1]);
-						for(int hh=0; hh<3; ++hh)
-						{
-							(*sort2[hh].second) = (sort1[hh]*0.8 + sort2[hh].first)/2;
-						}
-					}
-				}
-			}
-		}
-	}
-}
 void CSDL_Ext::drawBorder(SDL_Surface * sur, int x, int y, int w, int h, int3 color)
 {
 	for(int i=0;i<w;i++)
@@ -893,9 +722,9 @@ void CSDL_Ext::setPlayerColor(SDL_Surface * sur, unsigned char player)
 	if(sur->format->BitsPerPixel==8)
 	{
 		if(player != 255)
-			*(sur->format->palette->colors+5) = CGameInfo::mainObj->playerColors[player];
+			*(sur->format->palette->colors+5) = graphics->playerColors[player];
 		else
-			*(sur->format->palette->colors+5) = CGameInfo::mainObj->neutralColor;
+			*(sur->format->palette->colors+5) = *graphics->neutralColor;
 	}
 }
 int readNormalNr (std::istream &in, int bytCon)
@@ -916,15 +745,6 @@ int readNormalNr (std::istream &in, int bytCon)
 	return ret;
 }
 
-//void CSDL_Ext::fullAlphaTransform(SDL_Surface *& src)
-//{
-//	src = alphaTransform(src);
-//	//SDL_Surface * hlp2;
-//	//hlp2 = secondAlphaTransform(src, std32bppSurface);
-//	//SDL_FreeSurface(src);
-//	//src = hlp2;
-//}
-
 std::string CSDL_Ext::processStr(std::string str, std::vector<std::string> & tor)
 {
 	for (int i=0;(i<tor.size())&&(boost::find_first(str,"%s"));i++)

+ 0 - 6
SDL_Extensions.h

@@ -34,9 +34,7 @@ namespace CSDL_Ext
 	Uint32 SDL_GetPixel(SDL_Surface *surface, const int & x, const int & y, bool colorByte = false);
 	SDL_Color SDL_GetPixelColor(SDL_Surface *surface, int x, int y);
 	SDL_Surface * alphaTransform(SDL_Surface * src); //adds transparency and shadows (partial handling only; see examples of using for details)
-	SDL_Surface * secondAlphaTransform(SDL_Surface * src, SDL_Surface * alpha); //alpha is a surface we want to blit src to
 	int blit8bppAlphaTo24bpp(SDL_Surface * src, SDL_Rect * srcRect, SDL_Surface * dst, SDL_Rect * dstRect); //blits 8 bpp surface with alpha channel to 24 bpp surface
-	//void fullAlphaTransform(SDL_Surface *& src); //performs first and second alpha transform
 	Uint32 colorToUint32(const SDL_Color * color); //little endian only
 	void printTo(std::string text, int x, int y, TTF_Font * font, SDL_Color kolor=tytulowy, SDL_Surface * dst=screen, unsigned char quality = 2);// quality: 0 - lowest, 1 - medium, 2 - highest; prints at right bottom corner of specific area. position of corner indicated by (x, y)
 	void printToWR(std::string text, int x, int y, TTF_Font * font, SDL_Color kolor=tytulowy, SDL_Surface * dst=screen, unsigned char quality = 2);// quality: 0 - lowest, 1 - medium, 2 - highest; prints at right bottom corner of specific area. position of corner indicated by (x, y)
@@ -45,10 +43,6 @@ namespace CSDL_Ext
 	void printAtWB(std::string text, int x, int y, TTF_Font * font, int charpr, SDL_Color kolor=tytulowy, SDL_Surface * dst=screen);
 	void printAt(std::string text, int x, int y, TTF_Font * font, SDL_Color kolor=tytulowy, SDL_Surface * dst=screen, unsigned char quality = 2); // quality: 0 - lowest, 1 - medium, 2 - highest
 	void update(SDL_Surface * what = screen); //updates whole surface (default - main screen)
-	void blueToPlayers(SDL_Surface * sur, int player); //simple color substitution
-	void blueToPlayersAdv(SDL_Surface * sur, int player, int mode=0, void* additionalInfo=NULL); //substitute blue color by another one, makes it nicer keeping nuances
-																							//mode 1 is calibrated for hero infobox
-																							//mode 2 is calibrated for resbar and gets in additionalInfo a pointer to the set of (SDL_Color) which shouldn't be replaced
 	void drawBorder(SDL_Surface * sur, int x, int y, int w, int h, int3 color);
 	void setPlayerColor(SDL_Surface * sur, unsigned char player); //sets correct color of flags; -1 for neutral
 	std::string processStr(std::string str, std::vector<std::string> & tor); //replaces %s in string

+ 0 - 1231
SDL_rotozoom.cpp

@@ -1,1231 +0,0 @@
-/*  
-
-  SDL_rotozoom.c - rotozoomer for 32bit or 8bit surfaces
-
-  LGPL (c) A. Schiffler
-
-*/
-#include "stdafx.h"
-#ifdef WIN32
-#include <windows.h>
-#endif
-
-#include <stdlib.h>
-#include <string.h>
-
-#include "SDL_rotozoom.h"
-
-#define MAX(a,b)    (((a) > (b)) ? (a) : (b))
-
-
-/* 
- 
- 32bit integer-factor averaging Shrinker
-
- Shrinks 32bit RGBA/ABGR 'src' surface to 'dst' surface.
- 
-*/
-
-int shrinkSurfaceRGBA(SDL_Surface * src, SDL_Surface * dst, int factorx, int factory)
-{
-    int x, y, dx, dy, sgap, dgap, ra, ga, ba, aa;
-    int n_average;
-    tColorRGBA *sp, *osp, *oosp;
-    tColorRGBA *dp;
-
-    /*
-     * Averaging integer shrink
-     */
-
-    /* Precalculate division factor */
-    n_average = factorx*factory;
-   
-    /*
-     * Scan destination
-     */
-    sp = (tColorRGBA *) src->pixels;
-    sgap = src->pitch - src->w * 4;
-
-    dp = (tColorRGBA *) dst->pixels;
-    dgap = dst->pitch - dst->w * 4;
-
-    for (y = 0; y < dst->h; y++) {
-
-      osp=sp;
-      for (x = 0; x < dst->w; x++) {
-
-        /* Trace out source box and accumulate */
-        oosp=sp;
-        ra=ga=ba=aa=0;
-        for (dy=0; dy < factory; dy++) {
-         for (dx=0; dx < factorx; dx++) {
-          ra += sp->r;
-          ga += sp->g;
-          ba += sp->b;
-          aa += sp->a;
-          
-          sp++;
-         } // src dx loop
-         sp = (tColorRGBA *)((Uint8*)sp + (src->pitch - 4*factorx)); // next y
-        } // src dy loop
-
-        // next box-x
-        sp = (tColorRGBA *)((Uint8*)oosp + 4*factorx);
-                
-        /* Store result in destination */
-        dp->r = ra/n_average;
-        dp->g = ga/n_average;
-        dp->b = ba/n_average;
-        dp->a = aa/n_average;
-                 
-        /*
-         * Advance destination pointer 
-         */
-         dp++;
-        } // dst x loop
-
-        // next box-y
-        sp = (tColorRGBA *)((Uint8*)osp + src->pitch*factory);
-
-        /*
-         * Advance destination pointers 
-         */
-        dp = (tColorRGBA *) ((Uint8 *) dp + dgap);
-      } // dst y loop
-
-    return (0);
-}
-
-/* 
- 
- 8bit integer-factor averaging Shrinker
-
- Shrinks 8bit Y 'src' surface to 'dst' surface.
- 
-*/
-
-int shrinkSurfaceY(SDL_Surface * src, SDL_Surface * dst, int factorx, int factory)
-{
-    int x, y, dx, dy, sgap, dgap, a;
-    int n_average;
-    Uint8 *sp, *osp, *oosp;
-    Uint8 *dp;
-
-    /*
-     * Averaging integer shrink
-     */
-
-    /* Precalculate division factor */
-    n_average = factorx*factory;
-   
-    /*
-     * Scan destination
-     */
-    sp = (Uint8 *) src->pixels;
-    sgap = src->pitch - src->w;
-
-    dp = (Uint8 *) dst->pixels;
-    dgap = dst->pitch - dst->w;
-    
-    for (y = 0; y < dst->h; y++) {    
-
-      osp=sp;
-      for (x = 0; x < dst->w; x++) {
-
-        /* Trace out source box and accumulate */
-        oosp=sp;
-        a=0;
-        for (dy=0; dy < factory; dy++) {
-         for (dx=0; dx < factorx; dx++) {
-          a += (*sp);           
-          sp++; // next x
-         } // src dx loop         
-         sp = (Uint8 *)((Uint8*)sp + (src->pitch - factorx)); // next y
-        } // src dy loop
-        
-        // next box-x
-        sp = (Uint8 *)((Uint8*)oosp + factorx);
-                
-        /* Store result in destination */
-        *dp = a/n_average;
-
-        /*
-         * Advance destination pointer 
-         */
-         dp++;
-        } // dst x loop
-
-        // next box-y
-        sp = (Uint8 *)((Uint8*)osp + src->pitch*factory);
-
-        /*
-         * Advance destination pointers 
-         */
-        dp = (Uint8 *)((Uint8 *)dp + dgap);
-      } // dst y loop
-
-    return (0);
-}
-
-/* 
- 
- 32bit Zoomer with optional anti-aliasing by bilinear interpolation.
-
- Zoomes 32bit RGBA/ABGR 'src' surface to 'dst' surface.
- 
-*/
-
-int zoomSurfaceRGBA(SDL_Surface * src, SDL_Surface * dst, int flipx, int flipy, int smooth)
-{
-    int x, y, sx, sy, *sax, *say, *csax, *csay, csx, csy, ex, ey, t1, t2, sstep;
-    tColorRGBA *c00, *c01, *c10, *c11;
-    tColorRGBA *sp, *csp, *dp;
-    int dgap;
-
-    /*
-     * Variable setup 
-     */
-    if (smooth) {
-	/*
-	 * For interpolation: assume source dimension is one pixel 
-	 */
-	/*
-	 * smaller to avoid overflow on right and bottom edge.     
-	 */
-	sx = (int) (65536.0 * (float) (src->w - 1) / (float) dst->w);
-	sy = (int) (65536.0 * (float) (src->h - 1) / (float) dst->h);
-    } else {
-	sx = (int) (65536.0 * (float) src->w / (float) dst->w);
-	sy = (int) (65536.0 * (float) src->h / (float) dst->h);
-    }
-
-    /*
-     * Allocate memory for row increments 
-     */
-    if ((sax = (int *) malloc((dst->w + 1) * sizeof(Uint32))) == NULL) {
-	return (-1);
-    }
-    if ((say = (int *) malloc((dst->h + 1) * sizeof(Uint32))) == NULL) {
-	free(sax);
-	return (-1);
-    }
-
-    /*
-     * Precalculate row increments 
-     */
-    sp = csp = (tColorRGBA *) src->pixels;
-    dp = (tColorRGBA *) dst->pixels;
-
-    if (flipx) csp += (src->w-1);
-    if (flipy) csp  = (tColorRGBA*)( (Uint8*)csp + src->pitch*(src->h-1) );
-
-    csx = 0;
-    csax = sax;
-    for (x = 0; x <= dst->w; x++) {
-	*csax = csx;
-	csax++;
-	csx &= 0xffff;
-	csx += sx;
-    }
-    csy = 0;
-    csay = say;
-    for (y = 0; y <= dst->h; y++) {
-	*csay = csy;
-	csay++;
-	csy &= 0xffff;
-	csy += sy;
-    }
-
-    dgap = dst->pitch - dst->w * 4;
-
-    /*
-     * Switch between interpolating and non-interpolating code 
-     */
-    if (smooth) {
-
-	/*
-	 * Interpolating Zoom 
-	 */
-
-	/*
-	 * Scan destination 
-	 */
-	csay = say;
-	for (y = 0; y < dst->h; y++) {
-	    /*
-	     * Setup color source pointers 
-	     */
-	    c00 = csp;
-	    c01 = csp;
-	    c01++;
-	    c10 = (tColorRGBA *) ((Uint8 *) csp + src->pitch);
-	    c11 = c10;
-	    c11++;
-	    csax = sax;
-	    for (x = 0; x < dst->w; x++) {
-
-		/*
-		 * Interpolate colors 
-		 */
-		ex = (*csax & 0xffff);
-		ey = (*csay & 0xffff);
-		t1 = ((((c01->r - c00->r) * ex) >> 16) + c00->r) & 0xff;
-		t2 = ((((c11->r - c10->r) * ex) >> 16) + c10->r) & 0xff;
-		dp->r = (((t2 - t1) * ey) >> 16) + t1;
-		t1 = ((((c01->g - c00->g) * ex) >> 16) + c00->g) & 0xff;
-		t2 = ((((c11->g - c10->g) * ex) >> 16) + c10->g) & 0xff;
-		dp->g = (((t2 - t1) * ey) >> 16) + t1;
-		t1 = ((((c01->b - c00->b) * ex) >> 16) + c00->b) & 0xff;
-		t2 = ((((c11->b - c10->b) * ex) >> 16) + c10->b) & 0xff;
-		dp->b = (((t2 - t1) * ey) >> 16) + t1;
-		t1 = ((((c01->a - c00->a) * ex) >> 16) + c00->a) & 0xff;
-		t2 = ((((c11->a - c10->a) * ex) >> 16) + c10->a) & 0xff;
-		dp->a = (((t2 - t1) * ey) >> 16) + t1;
-
-		/*
-		 * Advance source pointers 
-		 */
-		csax++;
-		sstep = (*csax >> 16);
-		c00 += sstep;
-		c01 += sstep;
-		c10 += sstep;
-		c11 += sstep;
-		/*
-		 * Advance destination pointer 
-		 */
-		dp++;
-	    }
-	    /*
-	     * Advance source pointer 
-	     */
-	    csay++;
-	    csp = (tColorRGBA *) ((Uint8 *) csp + (*csay >> 16) * src->pitch);
-	    /*
-	     * Advance destination pointers 
-	     */
-	    dp = (tColorRGBA *) ((Uint8 *) dp + dgap);
-	}
-
-    } else {
-
-	/*
-	 * Non-Interpolating Zoom 
-	 */
-
-	csay = say;
-	for (y = 0; y < dst->h; y++) {
-	    sp = csp;
-	    csax = sax;
-	    for (x = 0; x < dst->w; x++) {
-		/*
-		 * Draw 
-		 */
-		*dp = *sp;
-		/*
-		 * Advance source pointers 
-		 */
-		csax++;
-		sstep = (*csax >> 16);
-		if (flipx) sstep = -sstep;
-		sp += sstep;
-		/*
-		 * Advance destination pointer 
-		 */
-		dp++;
-	    }
-	    /*
-	     * Advance source pointer 
-	     */
-	    csay++;
-	    sstep = (*csay >> 16) * src->pitch;
-	    if (flipy) sstep = -sstep;
-	    csp = (tColorRGBA *) ((Uint8 *) csp + sstep);
-
-	    /*
-	     * Advance destination pointers 
-	     */
-	    dp = (tColorRGBA *) ((Uint8 *) dp + dgap);
-	}
-
-    }
-
-    /*
-     * Remove temp arrays 
-     */
-    free(sax);
-    free(say);
-
-    return (0);
-}
-
-/* 
- 
- 8bit Zoomer without smoothing.
-
- Zoomes 8bit palette/Y 'src' surface to 'dst' surface.
- 
-*/
-
-int zoomSurfaceY(SDL_Surface * src, SDL_Surface * dst, int flipx, int flipy)
-{
-    Uint32 x, y, sx, sy, *sax, *say, *csax, *csay, csx, csy;
-    Uint8 *sp, *dp, *csp;
-    int dgap;
-
-    /*
-     * Variable setup 
-     */
-    sx = (Uint32) (65536.0 * (float) src->w / (float) dst->w);
-    sy = (Uint32) (65536.0 * (float) src->h / (float) dst->h);
-
-    /*
-     * Allocate memory for row increments 
-     */
-    if ((sax = (Uint32 *) malloc(dst->w * sizeof(Uint32))) == NULL) {
-	return (-1);
-    }
-    if ((say = (Uint32 *) malloc(dst->h * sizeof(Uint32))) == NULL) {
-	if (sax != NULL) {
-	    free(sax);
-	}
-	return (-1);
-    }
-
-    /*
-     * Precalculate row increments 
-     */
-    csx = 0;
-    csax = sax;
-    for (x = 0; x < dst->w; x++) {
-	csx += sx;
-	*csax = (csx >> 16);
-	csx &= 0xffff;
-	csax++;
-    }
-    csy = 0;
-    csay = say;
-    for (y = 0; y < dst->h; y++) {
-	csy += sy;
-	*csay = (csy >> 16);
-	csy &= 0xffff;
-	csay++;
-    }
-
-    csx = 0;
-    csax = sax;
-    for (x = 0; x < dst->w; x++) {
-	csx += (*csax);
-	csax++;
-    }
-    csy = 0;
-    csay = say;
-    for (y = 0; y < dst->h; y++) {
-	csy += (*csay);
-	csay++;
-    }
-
-    /*
-     * Pointer setup 
-     */
-    sp = csp = (Uint8 *) src->pixels;
-    dp = (Uint8 *) dst->pixels;
-    dgap = dst->pitch - dst->w;
-
-    /*
-     * Draw 
-     */
-    csay = say;
-    for (y = 0; y < dst->h; y++) {
-	csax = sax;
-	sp = csp;
-	for (x = 0; x < dst->w; x++) {
-	    /*
-	     * Draw 
-	     */
-	    *dp = *sp;
-	    /*
-	     * Advance source pointers 
-	     */
-	    sp += (*csax);
-	    csax++;
-	    /*
-	     * Advance destination pointer 
-	     */
-	    dp++;
-	}
-	/*
-	 * Advance source pointer (for row) 
-	 */
-	csp += ((*csay) * src->pitch);
-	csay++;
-	/*
-	 * Advance destination pointers 
-	 */
-	dp += dgap;
-    }
-
-    /*
-     * Remove temp arrays 
-     */
-    free(sax);
-    free(say);
-
-    return (0);
-}
-
-/* 
- 
- 32bit Rotozoomer with optional anti-aliasing by bilinear interpolation.
-
- Rotates and zoomes 32bit RGBA/ABGR 'src' surface to 'dst' surface.
- 
-*/
-
-void transformSurfaceRGBA(SDL_Surface * src, SDL_Surface * dst, int cx, int cy, int isin, int icos, int flipx, int flipy, int smooth)
-{
-    int x, y, t1, t2, dx, dy, xd, yd, sdx, sdy, ax, ay, ex, ey, sw, sh;
-    tColorRGBA c00, c01, c10, c11;
-    tColorRGBA *pc, *sp;
-    int gap;
-
-    /*
-     * Variable setup 
-     */
-    xd = ((src->w - dst->w) << 15);
-    yd = ((src->h - dst->h) << 15);
-    ax = (cx << 16) - (icos * cx);
-    ay = (cy << 16) - (isin * cx);
-    sw = src->w - 1;
-    sh = src->h - 1;
-    pc = (tColorRGBA*)dst->pixels;
-    gap = dst->pitch - dst->w * 4;
-
-    /*
-     * Switch between interpolating and non-interpolating code 
-     */
-    if (smooth) {
-	for (y = 0; y < dst->h; y++) {
-	    dy = cy - y;
-	    sdx = (ax + (isin * dy)) + xd;
-	    sdy = (ay - (icos * dy)) + yd;
-	    for (x = 0; x < dst->w; x++) {
-		dx = (sdx >> 16);
-		dy = (sdy >> 16);
-		if ((dx >= -1) && (dy >= -1) && (dx < src->w) && (dy < src->h)) {
-		    if ((dx >= 0) && (dy >= 0) && (dx < sw) && (dy < sh)) {
-			sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy);
-			sp += dx;
-			c00 = *sp;
-			sp += 1;
-			c01 = *sp;
-			sp = (tColorRGBA *) ((Uint8 *) sp + src->pitch);
-			sp -= 1;
-			c10 = *sp;
-			sp += 1;
-			c11 = *sp;
-		    } else if ((dx == sw) && (dy == sh)) {
-			sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy);
-			sp += dx;
-			c00 = *sp;
-			c01 = *sp;
-			c10 = *sp;
-			c11 = *sp;
-		    } else if ((dx == -1) && (dy == -1)) {
-			sp = (tColorRGBA *) (src->pixels);
-			c00 = *sp;
-			c01 = *sp;
-			c10 = *sp;
-			c11 = *sp;
-		    } else if ((dx == -1) && (dy == sh)) {
-			sp = (tColorRGBA *) (src->pixels);
-			sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy);
-			c00 = *sp;
-			c01 = *sp;
-			c10 = *sp;
-			c11 = *sp;
-		    } else if ((dx == sw) && (dy == -1)) {
-			sp = (tColorRGBA *) (src->pixels);
-			sp += dx;
-			c00 = *sp;
-			c01 = *sp;
-			c10 = *sp;
-			c11 = *sp;
-		    } else if (dx == -1) {
-			sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy);
-			c00 = *sp;
-			c01 = *sp;
-			c10 = *sp;
-			sp = (tColorRGBA *) ((Uint8 *) sp + src->pitch);
-			c11 = *sp;
-		    } else if (dy == -1) {
-			sp = (tColorRGBA *) (src->pixels);
-			sp += dx;
-			c00 = *sp;
-			c01 = *sp;
-			c10 = *sp;
-			sp += 1;
-			c11 = *sp;
-		    } else if (dx == sw) {
-			sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy);
-			sp += dx;
-			c00 = *sp;
-			c01 = *sp;
-			sp = (tColorRGBA *) ((Uint8 *) sp + src->pitch);
-			c10 = *sp;
-			c11 = *sp;
-		    } else if (dy == sh) {
-			sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy);
-			sp += dx;
-			c00 = *sp;
-			sp += 1;
-			c01 = *sp;
-			c10 = *sp;
-			c11 = *sp;
-		    }
-		    /*
-		     * Interpolate colors 
-		     */
-		    ex = (sdx & 0xffff);
-		    ey = (sdy & 0xffff);
-		    t1 = ((((c01.r - c00.r) * ex) >> 16) + c00.r) & 0xff;
-		    t2 = ((((c11.r - c10.r) * ex) >> 16) + c10.r) & 0xff;
-		    pc->r = (((t2 - t1) * ey) >> 16) + t1;
-		    t1 = ((((c01.g - c00.g) * ex) >> 16) + c00.g) & 0xff;
-		    t2 = ((((c11.g - c10.g) * ex) >> 16) + c10.g) & 0xff;
-		    pc->g = (((t2 - t1) * ey) >> 16) + t1;
-		    t1 = ((((c01.b - c00.b) * ex) >> 16) + c00.b) & 0xff;
-		    t2 = ((((c11.b - c10.b) * ex) >> 16) + c10.b) & 0xff;
-		    pc->b = (((t2 - t1) * ey) >> 16) + t1;
-		    t1 = ((((c01.a - c00.a) * ex) >> 16) + c00.a) & 0xff;
-		    t2 = ((((c11.a - c10.a) * ex) >> 16) + c10.a) & 0xff;
-		    pc->a = (((t2 - t1) * ey) >> 16) + t1;
-		}
-		sdx += icos;
-		sdy += isin;
-		pc++;
-	    }
-	    pc = (tColorRGBA *) ((Uint8 *) pc + gap);
-	}
-    } else {
-	for (y = 0; y < dst->h; y++) {
-	    dy = cy - y;
-	    sdx = (ax + (isin * dy)) + xd;
-	    sdy = (ay - (icos * dy)) + yd;
-	    for (x = 0; x < dst->w; x++) {
-		dx = (short) (sdx >> 16);
-		dy = (short) (sdy >> 16);
-		if (flipx) dx = (src->w-1)-dx;
-		if (flipy) dy = (src->h-1)-dy;
-		if ((dx >= 0) && (dy >= 0) && (dx < src->w) && (dy < src->h)) {
-		    sp = (tColorRGBA *) ((Uint8 *) src->pixels + src->pitch * dy);
-		    sp += dx;
-		    *pc = *sp;
-		}
-		sdx += icos;
-		sdy += isin;
-		pc++;
-	    }
-	    pc = (tColorRGBA *) ((Uint8 *) pc + gap);
-	}
-    }
-}
-
-/* 
- 
- 8bit Rotozoomer without smoothing
-
- Rotates and zoomes 8bit palette/Y 'src' surface to 'dst' surface.
- 
-*/
-
-void transformSurfaceY(SDL_Surface * src, SDL_Surface * dst, int cx, int cy, int isin, int icos)
-{
-    int x, y, dx, dy, xd, yd, sdx, sdy, ax, ay, sw, sh;
-    tColorY *pc, *sp;
-    int gap;
-
-    /*
-     * Variable setup 
-     */
-    xd = ((src->w - dst->w) << 15);
-    yd = ((src->h - dst->h) << 15);
-    ax = (cx << 16) - (icos * cx);
-    ay = (cy << 16) - (isin * cx);
-    sw = src->w - 1;
-    sh = src->h - 1;
-    pc = (tColorY*)dst->pixels;
-    gap = dst->pitch - dst->w;
-    /*
-     * Clear surface to colorkey 
-     */
-    memset(pc, (unsigned char) (src->format->colorkey & 0xff), dst->pitch * dst->h);
-    /*
-     * Iterate through destination surface 
-     */
-    for (y = 0; y < dst->h; y++) {
-	dy = cy - y;
-	sdx = (ax + (isin * dy)) + xd;
-	sdy = (ay - (icos * dy)) + yd;
-	for (x = 0; x < dst->w; x++) {
-	    dx = (short) (sdx >> 16);
-	    dy = (short) (sdy >> 16);
-	    if ((dx >= 0) && (dy >= 0) && (dx < src->w) && (dy < src->h)) {
-		sp = (tColorY *) (src->pixels);
-		sp += (src->pitch * dy + dx);
-		*pc = *sp;
-	    }
-	    sdx += icos;
-	    sdy += isin;
-	    pc++;
-	}
-	pc += gap;
-    }
-}
-
-/* 
- 
- rotozoomSurface()
-
- Rotates and zoomes a 32bit or 8bit 'src' surface to newly created 'dst' surface.
- 'angle' is the rotation in degrees. 'zoom' a scaling factor. If 'smooth' is 1
- then the destination 32bit surface is anti-aliased. If the surface is not 8bit
- or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly.
-
-*/
-
-#define VALUE_LIMIT	0.001
-
-
-/* Local rotozoom-size function with trig result return */
-
-void rotozoomSurfaceSizeTrig(int width, int height, double angle, double zoomx, double zoomy, int *dstwidth, int *dstheight, 
-			     double *canglezoom, double *sanglezoom)
-{
-    double x, y, cx, cy, sx, sy;
-    double radangle;
-    int dstwidthhalf, dstheighthalf;
-
-    /*
-     * Determine destination width and height by rotating a centered source box 
-     */
-    radangle = angle * (M_PI / 180.0);
-    *sanglezoom = sin(radangle);
-    *canglezoom = cos(radangle);
-    *sanglezoom *= zoomx;
-    *canglezoom *= zoomx;
-    x = width / 2;
-    y = height / 2;
-    cx = *canglezoom * x;
-    cy = *canglezoom * y;
-    sx = *sanglezoom * x;
-    sy = *sanglezoom * y;
-    
-    dstwidthhalf = MAX((int)
-		       ceil(MAX(MAX(MAX(fabs(cx + sy), fabs(cx - sy)), fabs(-cx + sy)), fabs(-cx - sy))), 1);
-    dstheighthalf = MAX((int)
-			ceil(MAX(MAX(MAX(fabs(sx + cy), fabs(sx - cy)), fabs(-sx + cy)), fabs(-sx - cy))), 1);
-    *dstwidth = 2 * dstwidthhalf;
-    *dstheight = 2 * dstheighthalf;
-}
-
-
-/* Publically available rotozoom-size function */
-
-void rotozoomSurfaceSizeXY(int width, int height, double angle, double zoomx, double zoomy, int *dstwidth, int *dstheight)
-{
-    double dummy_sanglezoom, dummy_canglezoom;
-
-    rotozoomSurfaceSizeTrig(width, height, angle, zoomx, zoomy, dstwidth, dstheight, &dummy_sanglezoom, &dummy_canglezoom);
-}
-
-/* Publically available rotozoom-size function */
-
-void rotozoomSurfaceSize(int width, int height, double angle, double zoom, int *dstwidth, int *dstheight)
-{
-    double dummy_sanglezoom, dummy_canglezoom;
-
-    rotozoomSurfaceSizeTrig(width, height, angle, zoom, zoom, dstwidth, dstheight, &dummy_sanglezoom, &dummy_canglezoom);
-}
-
-/* Publically available rotozoom function */
-
-SDL_Surface *rotozoomSurface(SDL_Surface * src, double angle, double zoom, int smooth)
-{
-  return rotozoomSurfaceXY(src, angle, zoom, zoom, smooth);
-}
-
-/* Publically available rotozoom function */
-
-SDL_Surface *rotozoomSurfaceXY(SDL_Surface * src, double angle, double zoomx, double zoomy, int smooth)
-{
-    SDL_Surface *rz_src;
-    SDL_Surface *rz_dst;
-    double zoominv;
-    double sanglezoom, canglezoom, sanglezoominv, canglezoominv;
-    int dstwidthhalf, dstwidth, dstheighthalf, dstheight;
-    int is32bit;
-    int i, src_converted;
-    int flipx,flipy;
-
-    /*
-     * Sanity check 
-     */
-    if (src == NULL)
-	return (NULL);
-
-    /*
-     * Determine if source surface is 32bit or 8bit 
-     */
-    is32bit = (src->format->BitsPerPixel == 32);
-    if ((is32bit) || (src->format->BitsPerPixel == 8)) {
-	/*
-	 * Use source surface 'as is' 
-	 */
-	rz_src = src;
-	src_converted = 0;
-    } else {
-	/*
-	 * New source surface is 32bit with a defined RGBA ordering 
-	 */
-	rz_src =
-	    SDL_CreateRGBSurface(SDL_SWSURFACE, src->w, src->h, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
-	SDL_BlitSurface(src, NULL, rz_src, NULL);
-	src_converted = 1;
-	is32bit = 1;
-    }
-
-    /*
-     * Sanity check zoom factor 
-     */
-    flipx = (zoomx<0);
-    if (flipx) zoomx=-zoomx;
-    flipy = (zoomy<0);
-    if (flipy) zoomy=-zoomy;
-    if (zoomx < VALUE_LIMIT) zoomx = VALUE_LIMIT;
-    if (zoomy < VALUE_LIMIT) zoomy = VALUE_LIMIT;
-    zoominv = 65536.0 / (zoomx * zoomx);
-
-    /*
-     * Check if we have a rotozoom or just a zoom 
-     */
-    if (fabs(angle) > VALUE_LIMIT) {
-
-	/*
-	 * Angle!=0: full rotozoom 
-	 */
-	/*
-	 * ----------------------- 
-	 */
-
-	/* Determine target size */
-	rotozoomSurfaceSizeTrig(rz_src->w, rz_src->h, angle, zoomx, zoomy, &dstwidth, &dstheight, &canglezoom, &sanglezoom);
-
-	/*
-	 * Calculate target factors from sin/cos and zoom 
-	 */
-	sanglezoominv = sanglezoom;
-	canglezoominv = canglezoom;
-	sanglezoominv *= zoominv;
-	canglezoominv *= zoominv;
-
-	/* Calculate half size */
-	dstwidthhalf = dstwidth / 2;
-	dstheighthalf = dstheight / 2;
-
-	/*
-	 * Alloc space to completely contain the rotated surface 
-	 */
-	rz_dst = NULL;
-	if (is32bit) {
-	    /*
-	     * Target surface is 32bit with source RGBA/ABGR ordering 
-	     */
-	    rz_dst =
-		SDL_CreateRGBSurface(SDL_SWSURFACE, dstwidth, dstheight, 32,
-				     rz_src->format->Rmask, rz_src->format->Gmask,
-				     rz_src->format->Bmask, rz_src->format->Amask);
-	} else {
-	    /*
-	     * Target surface is 8bit 
-	     */
-	    rz_dst = SDL_CreateRGBSurface(SDL_SWSURFACE, dstwidth, dstheight, 8, 0, 0, 0, 0);
-	}
-
-	/*
-	 * Lock source surface 
-	 */
-	SDL_LockSurface(rz_src);
-	/*
-	 * Check which kind of surface we have 
-	 */
-	if (is32bit) {
-	    /*
-	     * Call the 32bit transformation routine to do the rotation (using alpha) 
-	     */
-	    transformSurfaceRGBA(rz_src, rz_dst, dstwidthhalf, dstheighthalf,
-				 (int) (sanglezoominv), (int) (canglezoominv), 
-				 flipx, flipy,
-				 smooth);
-	    /*
-	     * Turn on source-alpha support 
-	     */
-	    SDL_SetAlpha(rz_dst, SDL_SRCALPHA, 255);
-	} else {
-	    /*
-	     * Copy palette and colorkey info 
-	     */
-	    for (i = 0; i < rz_src->format->palette->ncolors; i++) {
-		rz_dst->format->palette->colors[i] = rz_src->format->palette->colors[i];
-	    }
-	    rz_dst->format->palette->ncolors = rz_src->format->palette->ncolors;
-	    /*
-	     * Call the 8bit transformation routine to do the rotation 
-	     */
-	    transformSurfaceY(rz_src, rz_dst, dstwidthhalf, dstheighthalf,
-			      (int) (sanglezoominv), (int) (canglezoominv));
-	    SDL_SetColorKey(rz_dst, SDL_SRCCOLORKEY | SDL_RLEACCEL, rz_src->format->colorkey);
-	}
-	/*
-	 * Unlock source surface 
-	 */
-	SDL_UnlockSurface(rz_src);
-
-    } else {
-
-	/*
-	 * Angle=0: Just a zoom 
-	 */
-	/*
-	 * -------------------- 
-	 */
-
-	/*
-	 * Calculate target size
-	 */
-	zoomSurfaceSize(rz_src->w, rz_src->h, zoomx, zoomy, &dstwidth, &dstheight);
-
-	/*
-	 * Alloc space to completely contain the zoomed surface 
-	 */
-	rz_dst = NULL;
-	if (is32bit) {
-	    /*
-	     * Target surface is 32bit with source RGBA/ABGR ordering 
-	     */
-	    rz_dst =
-		SDL_CreateRGBSurface(SDL_SWSURFACE, dstwidth, dstheight, 32,
-				     rz_src->format->Rmask, rz_src->format->Gmask,
-				     rz_src->format->Bmask, rz_src->format->Amask);
-	} else {
-	    /*
-	     * Target surface is 8bit 
-	     */
-	    rz_dst = SDL_CreateRGBSurface(SDL_SWSURFACE, dstwidth, dstheight, 8, 0, 0, 0, 0);
-	}
-
-	/*
-	 * Lock source surface 
-	 */
-	SDL_LockSurface(rz_src);
-	/*
-	 * Check which kind of surface we have 
-	 */
-	if (is32bit) {
-	    /*
-	     * Call the 32bit transformation routine to do the zooming (using alpha) 
-	     */
-	    zoomSurfaceRGBA(rz_src, rz_dst, flipx, flipy, smooth);
-	    /*
-	     * Turn on source-alpha support 
-	     */
-	    SDL_SetAlpha(rz_dst, SDL_SRCALPHA, 255);
-	} else {
-	    /*
-	     * Copy palette and colorkey info 
-	     */
-	    for (i = 0; i < rz_src->format->palette->ncolors; i++) {
-		rz_dst->format->palette->colors[i] = rz_src->format->palette->colors[i];
-	    }
-	    rz_dst->format->palette->ncolors = rz_src->format->palette->ncolors;
-	    /*
-	     * Call the 8bit transformation routine to do the zooming 
-	     */
-	    zoomSurfaceY(rz_src, rz_dst, flipx, flipy);
-	    SDL_SetColorKey(rz_dst, SDL_SRCCOLORKEY | SDL_RLEACCEL, rz_src->format->colorkey);
-	}
-	/*
-	 * Unlock source surface 
-	 */
-	SDL_UnlockSurface(rz_src);
-    }
-
-    /*
-     * Cleanup temp surface 
-     */
-    if (src_converted) {
-	SDL_FreeSurface(rz_src);
-    }
-
-    /*
-     * Return destination surface 
-     */
-    return (rz_dst);
-}
-
-/* 
- 
- zoomSurface()
-
- Zoomes a 32bit or 8bit 'src' surface to newly created 'dst' surface.
- 'zoomx' and 'zoomy' are scaling factors for width and height. If 'smooth' is 1
- then the destination 32bit surface is anti-aliased. If the surface is not 8bit
- or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly.
-
-*/
-
-#define VALUE_LIMIT	0.001
-
-void zoomSurfaceSize(int width, int height, double zoomx, double zoomy, int *dstwidth, int *dstheight)
-{
-    /*
-     * Sanity check zoom factors 
-     */
-    if (zoomx < VALUE_LIMIT) {
-	zoomx = VALUE_LIMIT;
-    }
-    if (zoomy < VALUE_LIMIT) {
-	zoomy = VALUE_LIMIT;
-    }
-
-    /*
-     * Calculate target size 
-     */
-    *dstwidth = (int) ((double) width * zoomx);
-    *dstheight = (int) ((double) height * zoomy);
-    if (*dstwidth < 1) {
-	*dstwidth = 1;
-    }
-    if (*dstheight < 1) {
-	*dstheight = 1;
-    }
-}
-
-SDL_Surface *zoomSurface(SDL_Surface * src, double zoomx, double zoomy, int smooth)
-{
-    SDL_Surface *rz_src;
-    SDL_Surface *rz_dst;
-    int dstwidth, dstheight;
-    int is32bit;
-    int i, src_converted;
-    int flipx, flipy;
-
-    /*
-     * Sanity check 
-     */
-    if (src == NULL)
-	return (NULL);
-
-    /*
-     * Determine if source surface is 32bit or 8bit 
-     */
-    is32bit = (src->format->BitsPerPixel == 32);
-    if ((is32bit) || (src->format->BitsPerPixel == 8)) {
-	/*
-	 * Use source surface 'as is' 
-	 */
-	rz_src = src;
-	src_converted = 0;
-    } else {
-	/*
-	 * New source surface is 32bit with a defined RGBA ordering 
-	 */
-	rz_src =
-	    SDL_CreateRGBSurface(SDL_SWSURFACE, src->w, src->h, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
-	SDL_BlitSurface(src, NULL, rz_src, NULL);
-	src_converted = 1;
-	is32bit = 1;
-    }
-
-    flipx = (zoomx<0);
-    if (flipx) zoomx = -zoomx;
-    flipy = (zoomy<0);
-    if (flipy) zoomy = -zoomy;
-
-    /* Get size if target */
-    zoomSurfaceSize(rz_src->w, rz_src->h, zoomx, zoomy, &dstwidth, &dstheight);
-
-    /*
-     * Alloc space to completely contain the zoomed surface 
-     */
-    rz_dst = NULL;
-    if (is32bit) {
-	/*
-	 * Target surface is 32bit with source RGBA/ABGR ordering 
-	 */
-	rz_dst =
-	    SDL_CreateRGBSurface(SDL_SWSURFACE, dstwidth, dstheight, 32,
-				 rz_src->format->Rmask, rz_src->format->Gmask,
-				 rz_src->format->Bmask, rz_src->format->Amask);
-    } else {
-	/*
-	 * Target surface is 8bit 
-	 */
-	rz_dst = SDL_CreateRGBSurface(SDL_SWSURFACE, dstwidth, dstheight, 8, 0, 0, 0, 0);
-    }
-
-    /*
-     * Lock source surface 
-     */
-    SDL_LockSurface(rz_src);
-    /*
-     * Check which kind of surface we have 
-     */
-    if (is32bit) {
-	/*
-	 * Call the 32bit transformation routine to do the zooming (using alpha) 
-	 */
-	zoomSurfaceRGBA(rz_src, rz_dst, flipx, flipy, smooth);
-	/*
-	 * Turn on source-alpha support 
-	 */
-	SDL_SetAlpha(rz_dst, SDL_SRCALPHA, 255);
-    } else {
-	/*
-	 * Copy palette and colorkey info 
-	 */
-	for (i = 0; i < rz_src->format->palette->ncolors; i++) {
-	    rz_dst->format->palette->colors[i] = rz_src->format->palette->colors[i];
-	}
-	rz_dst->format->palette->ncolors = rz_src->format->palette->ncolors;
-	/*
-	 * Call the 8bit transformation routine to do the zooming 
-	 */
-	zoomSurfaceY(rz_src, rz_dst, flipx, flipy);
-	SDL_SetColorKey(rz_dst, SDL_SRCCOLORKEY | SDL_RLEACCEL, rz_src->format->colorkey);
-    }
-    /*
-     * Unlock source surface 
-     */
-    SDL_UnlockSurface(rz_src);
-
-    /*
-     * Cleanup temp surface 
-     */
-    if (src_converted) {
-	SDL_FreeSurface(rz_src);
-    }
-
-    /*
-     * Return destination surface 
-     */
-    return (rz_dst);
-}
-
-SDL_Surface *shrinkSurface(SDL_Surface * src, int factorx, int factory)
-{
-    SDL_Surface *rz_src;
-    SDL_Surface *rz_dst;
-    int dstwidth, dstheight;
-    int is32bit;
-    int i, src_converted;
-
-    /*
-     * Sanity check 
-     */
-    if (src == NULL)
-	return (NULL);
-
-    /*
-     * Determine if source surface is 32bit or 8bit 
-     */
-    is32bit = (src->format->BitsPerPixel == 32);
-    if ((is32bit) || (src->format->BitsPerPixel == 8)) {
-	/*
-	 * Use source surface 'as is' 
-	 */
-	rz_src = src;
-	src_converted = 0;
-    } else {
-	/*
-	 * New source surface is 32bit with a defined RGBA ordering 
-	 */
-	rz_src =
-	    SDL_CreateRGBSurface(SDL_SWSURFACE, src->w, src->h, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000);
-	SDL_BlitSurface(src, NULL, rz_src, NULL);
-	src_converted = 1;
-	is32bit = 1;
-    }
-
-    /* Get size for target */
-    dstwidth=rz_src->w/factorx;
-    while (dstwidth*factorx>rz_src->w) { dstwidth--; }
-    dstheight=rz_src->h/factory;
-    while (dstheight*factory>rz_src->h) { dstheight--; }
-
-    /*
-     * Alloc space to completely contain the shrunken surface 
-     */
-    rz_dst = NULL;
-    if (is32bit) {
-	/*
-	 * Target surface is 32bit with source RGBA/ABGR ordering 
-	 */
-	rz_dst =
-	    SDL_CreateRGBSurface(SDL_SWSURFACE, dstwidth, dstheight, 32,
-				 rz_src->format->Rmask, rz_src->format->Gmask,
-				 rz_src->format->Bmask, rz_src->format->Amask);
-    } else {
-	/*
-	 * Target surface is 8bit 
-	 */
-	rz_dst = SDL_CreateRGBSurface(SDL_SWSURFACE, dstwidth, dstheight, 8, 0, 0, 0, 0);
-    }
-
-    /*
-     * Lock source surface 
-     */
-    SDL_LockSurface(rz_src);
-    /*
-     * Check which kind of surface we have 
-     */
-    if (is32bit) {
-	/*
-	 * Call the 32bit transformation routine to do the shrinking (using alpha) 
-	 */
-	shrinkSurfaceRGBA(rz_src, rz_dst, factorx, factory);
-	/*
-	 * Turn on source-alpha support 
-	 */
-	SDL_SetAlpha(rz_dst, SDL_SRCALPHA, 255);
-    } else {
-	/*
-	 * Copy palette and colorkey info 
-	 */
-	for (i = 0; i < rz_src->format->palette->ncolors; i++) {
-	    rz_dst->format->palette->colors[i] = rz_src->format->palette->colors[i];
-	}
-	rz_dst->format->palette->ncolors = rz_src->format->palette->ncolors;
-	/*
-	 * Call the 8bit transformation routine to do the shrinking 
-	 */
-	shrinkSurfaceY(rz_src, rz_dst, factorx, factory);
-	SDL_SetColorKey(rz_dst, SDL_SRCCOLORKEY | SDL_RLEACCEL, rz_src->format->colorkey);
-    }
-    /*
-     * Unlock source surface 
-     */
-    SDL_UnlockSurface(rz_src);
-
-    /*
-     * Cleanup temp surface 
-     */
-    if (src_converted) {
-	SDL_FreeSurface(rz_src);
-    }
-
-    /*
-     * Return destination surface 
-     */
-    return (rz_dst);
-}

+ 0 - 117
SDL_rotozoom.h

@@ -1,117 +0,0 @@
-
-/*
-
- SDL_rotozoom - rotozoomer
-
- LGPL (c) A. Schiffler
-
-*/
-
-#ifndef _SDL_rotozoom_h
-#define _SDL_rotozoom_h
-
-#include <math.h>
-
-/* Set up for C function definitions, even when using C++ */
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#ifndef M_PI
-#define M_PI	3.141592654
-#endif
-
-#include "SDL.h"
-
-/* ---- Defines */
-
-#define SMOOTHING_OFF		0
-#define SMOOTHING_ON		1
-
-/* ---- Structures */
-
-    typedef struct tColorRGBA {
-	Uint8 r;
-	Uint8 g;
-	Uint8 b;
-	Uint8 a;
-    } tColorRGBA;
-
-    typedef struct tColorY {
-	Uint8 y;
-    } tColorY;
-
-
-/* ---- Prototypes */
-
-#ifdef WIN32
-#ifdef BUILD_DLL
-#define DLLINTERFACE __declspec(dllexport)
-#else
-#define DLLINTERFACE __declspec(dllimport)
-#endif
-#else
-#define DLLINTERFACE
-#endif
-
-/* 
- 
- rotozoomSurface()
-
- Rotates and zoomes a 32bit or 8bit 'src' surface to newly created 'dst' surface.
- 'angle' is the rotation in degrees. 'zoom' a scaling factor. If 'smooth' is 1
- then the destination 32bit surface is anti-aliased. If the surface is not 8bit
- or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly.
-
-*/
-
-    SDL_Surface *rotozoomSurface(SDL_Surface * src, double angle, double zoom, int smooth);
-
-    SDL_Surface *rotozoomSurfaceXY
-    (SDL_Surface * src, double angle, double zoomx, double zoomy, int smooth);
-
-/* Returns the size of the target surface for a rotozoomSurface() call */
-
-    void rotozoomSurfaceSize(int width, int height, double angle, double zoom, int *dstwidth,
-					  int *dstheight);
-
-    void rotozoomSurfaceSizeXY
-    (int width, int height, double angle, double zoomx, double zoomy, 
-     int *dstwidth, int *dstheight);
-
-/* 
- 
- zoomSurface()
-
- Zoomes a 32bit or 8bit 'src' surface to newly created 'dst' surface.
- 'zoomx' and 'zoomy' are scaling factors for width and height. If 'smooth' is 1
- then the destination 32bit surface is anti-aliased. If the surface is not 8bit
- or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly.
-
-*/
-
-    SDL_Surface *zoomSurface(SDL_Surface * src, double zoomx, double zoomy, int smooth);
-
-/* Returns the size of the target surface for a zoomSurface() call */
-
-    void zoomSurfaceSize(int width, int height, double zoomx, double zoomy, int *dstwidth, int *dstheight);
-
-
-/* 
-    shrinkSurface()
-
-    Shrinks a 32bit or 8bit 'src' surface ti a newly created 'dst' surface.
-    'factorx' and 'factory' are the shrinking ratios (i.e. 2=1/2 the size,
-    3=1/3 the size, etc.) The destination surface is antialiased by averaging
-    the source box RGBA or Y information. If the surface is not 8bit
-    or 32bit RGBA/ABGR it will be converted into a 32bit RGBA format on the fly.
-*/     
-    
-    SDL_Surface *shrinkSurface(SDL_Surface * src, int factorx, int factory);
-
-/* Ends C function definitions when using C++ */
-#ifdef __cplusplus
-}
-#endif
-
-#endif				/* _SDL_rotozoom_h */

+ 29 - 8
StartInfo.h

@@ -10,22 +10,36 @@ struct StartInfo
 {
 	struct PlayerSettings
 	{
-		int castle, hero,  //ID, if -1 then random, if -2 then none
+		si32 castle, hero,  //ID, if -1 then random, if -2 then none
 			heroPortrait; //-1 if default, else ID
 		std::string heroName;
-		Ebonus bonus;
-		Ecolor color; //from 0 -
-		int serial;
-		int handicap;//0-no, 1-mild, 2-severe
+		si8 bonus; //usees enum type Ebonus
+		ui8 color; //from 0 - 
+		ui8 serial;
+		ui8 handicap;//0-no, 1-mild, 2-severe
 		std::string name;
 		bool human;
+		template <typename Handler> 	void serialize(Handler &h, const int version)
+		{
+			h & castle;
+			h & hero;
+			h & heroPortrait;
+			h & heroName;
+			h & bonus;
+			h & color;
+			h & serial;
+			h & handicap;
+			h & name;
+			h & human;
+		}
 	};
-	int difficulty; //0=easy; 4=impossible
+	si32 difficulty; //0=easy; 4=impossible
 	std::vector<PlayerSettings> playerInfos;
-	int turnTime; //in minutes, 0=unlimited
+	ui8 turnTime; //in minutes, 0=unlimited
+	std::string mapname;
 	PlayerSettings & getIthPlayersSettings(int no)
 	{
-		for(int i=0; i<playerInfos.size(); ++i)
+		for(unsigned int i=0; i<playerInfos.size(); ++i)
 			if(playerInfos[i].color == no)
 				return playerInfos[i];
 #ifndef __GNUC__
@@ -34,6 +48,13 @@ struct StartInfo
 		throw new std::exception();
 #endif
 	}
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & difficulty;
+		h & playerInfos;
+		h & turnTime;
+		h & mapname;
+	}
 };
 
 #endif

+ 1 - 0
aclocal.m4

@@ -851,3 +851,4 @@ AC_SUBST([am__untar])
 m4_include([aclocal/m4/ax_boost_base.m4])
 m4_include([aclocal/m4/ax_boost_filesystem.m4])
 m4_include([aclocal/m4/ax_boost_system.m4])
+m4_include([aclocal/m4/ax_boost_thread.m4])

+ 147 - 0
aclocal/m4/ax_boost_thread.m4

@@ -0,0 +1,147 @@
+# ===========================================================================
+#            http://autoconf-archive.cryp.to/ax_boost_thread.html
+# ===========================================================================
+#
+# SYNOPSIS
+#
+#   AX_BOOST_THREAD
+#
+# DESCRIPTION
+#
+#   Test for Thread library from the Boost C++ libraries. The macro requires
+#   a preceding call to AX_BOOST_BASE. Further documentation is available at
+#   <http://randspringer.de/boost/index.html>.
+#
+#   This macro calls:
+#
+#     AC_SUBST(BOOST_THREAD_LIB)
+#
+#   And sets:
+#
+#     HAVE_BOOST_THREAD
+#
+# LAST MODIFICATION
+#
+#   2008-04-12
+#
+# COPYLEFT
+#
+#   Copyright (c) 2008 Thomas Porschberg <[email protected]>
+#   Copyright (c) 2008 Michael Tindal
+#
+#   Copying and distribution of this file, with or without modification, are
+#   permitted in any medium without royalty provided the copyright notice
+#   and this notice are preserved.
+
+AC_DEFUN([AX_BOOST_THREAD],
+[
+	AC_ARG_WITH([boost-thread],
+	AS_HELP_STRING([--with-boost-thread@<:@=special-lib@:>@],
+                   [use the Thread library from boost - it is possible to specify a certain library for the linker
+                        e.g. --with-boost-thread=boost_thread-gcc-mt ]),
+        [
+        if test "$withval" = "no"; then
+			want_boost="no"
+        elif test "$withval" = "yes"; then
+            want_boost="yes"
+            ax_boost_user_thread_lib=""
+        else
+		    want_boost="yes"
+        	ax_boost_user_thread_lib="$withval"
+		fi
+        ],
+        [want_boost="yes"]
+	)
+
+	if test "x$want_boost" = "xyes"; then
+        AC_REQUIRE([AC_PROG_CC])
+        AC_REQUIRE([AC_CANONICAL_BUILD])
+		CPPFLAGS_SAVED="$CPPFLAGS"
+		CPPFLAGS="$CPPFLAGS $BOOST_CPPFLAGS"
+		export CPPFLAGS
+
+		LDFLAGS_SAVED="$LDFLAGS"
+		LDFLAGS="$LDFLAGS $BOOST_LDFLAGS"
+		export LDFLAGS
+
+        AC_CACHE_CHECK(whether the Boost::Thread library is available,
+					   ax_cv_boost_thread,
+        [AC_LANG_PUSH([C++])
+			 CXXFLAGS_SAVE=$CXXFLAGS
+
+			 if test "x$build_os" = "xsolaris" ; then
+  				 CXXFLAGS="-pthreads $CXXFLAGS"
+			 elif test "x$build_os" = "xming32" ; then
+				 CXXFLAGS="-mthreads $CXXFLAGS"
+			 else
+				CXXFLAGS="-pthread $CXXFLAGS"
+			 fi
+			 AC_COMPILE_IFELSE(AC_LANG_PROGRAM([[@%:@include <boost/thread/thread.hpp>]],
+                                   [[boost::thread_group thrds;
+                                   return 0;]]),
+                   ax_cv_boost_thread=yes, ax_cv_boost_thread=no)
+			 CXXFLAGS=$CXXFLAGS_SAVE
+             AC_LANG_POP([C++])
+		])
+		if test "x$ax_cv_boost_thread" = "xyes"; then
+           if test "x$build_os" = "xsolaris" ; then
+			  BOOST_CPPFLAGS="-pthreads $BOOST_CPPFLAGS"
+		   elif test "x$build_os" = "xming32" ; then
+			  BOOST_CPPFLAGS="-mthreads $BOOST_CPPFLAGS"
+		   else
+			  BOOST_CPPFLAGS="-pthread $BOOST_CPPFLAGS"
+		   fi
+
+			AC_SUBST(BOOST_CPPFLAGS)
+
+			AC_DEFINE(HAVE_BOOST_THREAD,,[define if the Boost::Thread library is available])
+            BOOSTLIBDIR=`echo $BOOST_LDFLAGS | sed -e 's/@<:@^\/@:>@*//'`
+
+			LDFLAGS_SAVE=$LDFLAGS
+                        case "x$build_os" in
+                          *bsd* )
+                               LDFLAGS="-pthread $LDFLAGS"
+                          break;
+                          ;;
+                        esac
+            if test "x$ax_boost_user_thread_lib" = "x"; then
+                for libextension in `ls $BOOSTLIBDIR/libboost_thread*.{so,a}* 2>/dev/null | sed 's,.*/,,' | sed -e 's;^lib\(boost_thread.*\)\.so.*$;\1;' -e 's;^lib\(boost_thread.*\)\.a*$;\1;'` ; do
+                     ax_lib=${libextension}
+				    AC_CHECK_LIB($ax_lib, exit,
+                                 [BOOST_THREAD_LIB="-l$ax_lib"; AC_SUBST(BOOST_THREAD_LIB) link_thread="yes"; break],
+                                 [link_thread="no"])
+  				done
+                if test "x$link_thread" != "xyes"; then
+                for libextension in `ls $BOOSTLIBDIR/boost_thread*.{dll,a}* 2>/dev/null | sed 's,.*/,,' | sed -e 's;^\(boost_thread.*\)\.dll.*$;\1;' -e 's;^\(boost_thread.*\)\.a*$;\1;'` ; do
+                     ax_lib=${libextension}
+				    AC_CHECK_LIB($ax_lib, exit,
+                                 [BOOST_THREAD_LIB="-l$ax_lib"; AC_SUBST(BOOST_THREAD_LIB) link_thread="yes"; break],
+                                 [link_thread="no"])
+  				done
+                fi
+
+            else
+               for ax_lib in $ax_boost_user_thread_lib boost_thread-$ax_boost_user_thread_lib; do
+				      AC_CHECK_LIB($ax_lib, exit,
+                                   [BOOST_THREAD_LIB="-l$ax_lib"; AC_SUBST(BOOST_THREAD_LIB) link_thread="yes"; break],
+                                   [link_thread="no"])
+                  done
+
+            fi
+			if test "x$link_thread" = "xno"; then
+				AC_MSG_ERROR(Could not link against $ax_lib !)
+                        else
+                           case "x$build_os" in
+                              *bsd* )
+			        BOOST_LDFLAGS="-pthread $BOOST_LDFLAGS"
+                              break;
+                              ;;
+                           esac
+
+			fi
+		fi
+
+		CPPFLAGS="$CPPFLAGS_SAVED"
+    	LDFLAGS="$LDFLAGS_SAVED"
+	fi
+])

+ 352 - 0
client/CBitmapHandler.cpp

@@ -0,0 +1,352 @@
+#include "../stdafx.h"
+#include "SDL.h"
+#include "SDL_image.h"
+#include "CBitmapHandler.h"
+#include "../hch/CDefHandler.h"
+#include "../hch/CLodHandler.h"
+#include <sstream>
+#include <boost/thread.hpp>
+boost::mutex bitmap_handler_mx;
+int readNormalNr (int pos, int bytCon, unsigned char * str);
+CLodHandler * BitmapHandler::bitmaph = NULL;
+void BMPHeader::print(std::ostream & out)
+{
+	CDefHandler::print(out,fullSize,4);
+	CDefHandler::print(out,_h1,4);
+	CDefHandler::print(out,_c1,4);
+	CDefHandler::print(out,_c2,4);
+	CDefHandler::print(out,x,4);
+	CDefHandler::print(out,y,4);
+	CDefHandler::print(out,_c3,2);
+	CDefHandler::print(out,_c4,2);
+	CDefHandler::print(out,_h2,4);
+	CDefHandler::print(out,_h3,4);
+	CDefHandler::print(out,dataSize1,4);
+	CDefHandler::print(out,dataSize2,4);
+	for (int i=0;i<8;i++)
+		out << _c5[i];
+	out.flush();
+}
+void CPCXConv::openPCX(char * PCX, int len)
+{
+	pcxs=len;
+	pcx=(unsigned char*)PCX;
+}
+void CPCXConv::fromFile(std::string path)
+{
+	std::ifstream * is = new std::ifstream();
+	is -> open(path.c_str(),std::ios::binary);
+	is->seekg(0,std::ios::end); // to the end
+	pcxs = is->tellg();  // read length
+	is->seekg(0,std::ios::beg); // wracamy na poczatek
+	pcx = new unsigned char[pcxs]; // allocate memory 
+	is->read((char*)pcx, pcxs); // read map file to buffer
+	is->close();
+	delete is;
+}
+void CPCXConv::saveBMP(std::string path)
+{
+	std::ofstream os;
+	os.open(path.c_str(), std::ios::binary);
+	os.write((char*)bmp,bmps);
+	os.close();
+}
+void CPCXConv::convert()
+{
+	BMPHeader bh;
+	BMPPalette pal[256];
+	Epcxformat format;
+	int fSize,i,y;
+	bool check1, check2;
+	unsigned char add;
+	int it=0;
+
+	std::stringstream out;
+
+	fSize = readNormalNr(it,4,pcx);it+=4;
+	bh.x = readNormalNr(it,4,pcx);it+=4;
+	bh.y = readNormalNr(it,4,pcx);it+=4;
+	if (fSize==bh.x*bh.y*3)
+		check1=true;
+	else 
+		check1=false;
+	if (fSize==bh.x*bh.y)
+		check2=true;
+	else 
+		check2=false;
+	if (check1)
+		format=PCX24B;
+	else if (check2)
+		format=PCX8B;
+	else 
+		return;
+	add = 4 - bh.x%4;
+	if (add==4)
+		add=0;
+	bh._h3=bh.x*bh.y;
+	if (format==PCX8B)
+	{
+		bh._c1=0x436;
+		bh._c2=0x28;
+		bh._c3=1;
+		bh._c4=8;
+		//bh.dataSize2=bh.dataSize1=maxx*maxy;
+		bh.dataSize1=bh.x;
+		bh.dataSize2=bh.y;
+		bh.fullSize = bh.dataSize1+436;
+	}
+	else
+	{
+		bh._c1=0x36;
+		bh._c2=0x28;
+		bh._c3=1;
+		bh._c4=0x18;
+		//bh.dataSize2=bh.dataSize1=0xB12;
+		bh.dataSize1=bh.x;
+		bh.dataSize2=bh.y;
+		bh.fullSize=(bh.x+add)*bh.y*3+36+18;
+		bh._h3*=3;
+	}
+	if (format==PCX8B)
+	{
+		it = pcxs-256*3;
+		for (int i=0;i<256;i++)
+		{
+			pal[i].R=pcx[it++];
+			pal[i].G=pcx[it++];
+			pal[i].B=pcx[it++];
+			pal[i].F='\0';
+		}
+	}
+	out<<"BM";
+	bh.print(out);
+	if (format==PCX8B)
+	{
+		for (int i=0;i<256;i++)
+		{
+			out<<pal[i].B;
+			out<<pal[i].G;
+			out<<pal[i].R;
+			out<<pal[i].F;
+		}
+		for (y=bh.y;y>0;y--)
+		{
+			it=0xC+(y-1)*bh.x;
+			for (int j=0;j<bh.x;j++)
+				out<<pcx[it+j];
+			if (add>0)
+			{
+				for (int j=0;j<add;j++)
+					out<<'\0'; //bylo z buforu, ale onnie byl incjalizowany (?!)
+			}
+		}
+	}
+	else
+	{
+		for (y=bh.y; y>0; y--)
+		{
+			it=0xC+(y-1)*bh.x*3;
+			for (int j=0;j<bh.x*3;j++)
+				out<<pcx[it+j];
+			if (add>0)
+			{
+				for (int j=0;j<add*3;j++)
+					out<<'\0'; //bylo z buforu, ale onnie byl incjalizowany (?!)
+			}
+		}
+	}
+	std::string temp = out.str();
+	bmp = new unsigned char[temp.length()];
+	bmps=temp.length();
+	for (int a=0;a<temp.length();a++)
+	{
+		bmp[a]=temp[a];
+	}
+}
+
+SDL_Surface * CPCXConv::getSurface()
+{
+	SDL_Surface * ret;
+
+	BMPHeader bh;
+	Epcxformat format;
+	int fSize,i,y;
+	bool check1, check2;
+	unsigned char add;
+	int it=0;
+
+	fSize = readNormalNr(it,4,pcx);it+=4;
+	bh.x = readNormalNr(it,4,pcx);it+=4;
+	bh.y = readNormalNr(it,4,pcx);it+=4;
+	if (fSize==bh.x*bh.y*3)
+		check1=true;
+	else 
+		check1=false;
+	if (fSize==bh.x*bh.y)
+		check2=true;
+	else 
+		check2=false;
+	if (check1)
+		format=PCX24B;
+	else if (check2)
+		format=PCX8B;
+	else 
+		return NULL;
+	add = 4 - bh.x%4;
+	if (add==4)
+		add=0;
+	if (format==PCX8B)
+	{
+		ret = SDL_CreateRGBSurface(SDL_SWSURFACE, bh.x+add, bh.y, 8, 0, 0, 0, 0);
+	}
+	else
+	{
+#if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
+		int bmask = 0xff0000;
+		int gmask = 0x00ff00;
+		int rmask = 0x0000ff;
+#else
+		int bmask = 0x0000ff;
+		int gmask = 0x00ff00;
+		int rmask = 0xff0000;
+#endif
+		ret = SDL_CreateRGBSurface(SDL_SWSURFACE, bh.x+add, bh.y, 24, rmask, gmask, bmask, 0);
+	}
+	if (format==PCX8B)
+	{
+		it = pcxs-256*3;
+		for (int i=0;i<256;i++)
+		{
+			SDL_Color tp;
+#if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
+			tp.b = pcx[it++];
+			tp.g = pcx[it++];
+			tp.r = pcx[it++];
+#else
+			tp.r = pcx[it++];
+			tp.g = pcx[it++];
+			tp.b = pcx[it++];
+#endif
+			tp.unused = 0;
+			*(ret->format->palette->colors+i) = tp;
+		}
+		for (y=bh.y;y>0;y--)
+		{
+			it=0xC+(y-1)*bh.x;
+			for (int j=0;j<bh.x;j++)
+			{
+				*((char*)ret->pixels + ret->pitch * (y-1) + ret->format->BytesPerPixel * j) = pcx[it+j];
+			}
+			if (add>0)
+			{
+				for (int j=0;j<add;j++)
+				{
+					*((char*)ret->pixels + ret->pitch * (y-1) + ret->format->BytesPerPixel * (j+bh.x)) = 0;
+				}
+			}
+		}
+	}
+	else
+	{
+		for (y=bh.y; y>0; y--)
+		{
+			it=0xC+(y-1)*bh.x*3;
+			for (int j=0;j<bh.x*3;j++)
+			{
+				*((char*)ret->pixels + ret->pitch * (y-1) + j) = pcx[it+j];
+			}
+			if (add>0)
+			{
+				for (int j=0;j<add*3;j++)
+				{
+					*((char*)ret->pixels + ret->pitch * (y-1) + (j+bh.x*3)) = 0;
+				}
+			}
+		}
+	}
+	return ret;
+}
+
+SDL_Surface * BitmapHandler::loadBitmap(std::string fname, bool setKey)
+{
+	if(!fname.size())
+		return NULL;
+	unsigned char * pcx;
+	std::transform(fname.begin(),fname.end(),fname.begin(),toupper);
+	fname.replace(fname.find_first_of('.'),fname.find_first_of('.')+4,".PCX");
+	Entry *e = bitmaph->entries.znajdz(fname);
+	if(!e)
+	{
+		std::cout<<"File "<<fname<<" not found"<<std::endl;
+		return NULL;
+	}
+	if(e->offset<0)
+	{
+		fname.replace(fname.find_first_of('.'),fname.find_first_of('.')+4,".BMP");
+		fname = "Data/"+fname;
+		FILE * f = fopen(fname.c_str(),"r");
+		if(f)
+		{
+			fclose(f);
+			return SDL_LoadBMP(fname.c_str());
+		}
+		else  //file .bmp not present, check .pcx
+		{
+			char sign[3];
+			fname.replace(fname.find_first_of('.'),fname.find_first_of('.')+4,".PCX");
+			f = fopen(fname.c_str(),"r");
+			if(!f)
+				return NULL; 
+			fread(sign,1,3,f);
+			if(sign[0]=='B' && sign[1]=='M') //BMP named as PCX - people (eg. Kulex) sometimes use such files
+			{
+				fclose(f);
+				return SDL_LoadBMP(fname.c_str());
+			}
+			else //PCX - but we don't know which
+			{
+				if((sign[0]==10) && (sign[1]<6) && (sign[2]==1)) //ZSoft PCX
+				{
+					fclose(f);
+					return IMG_Load(fname.c_str());
+				}
+				else //H3-style PCX
+				{
+					CPCXConv cp;
+					pcx = new unsigned char[e->realSize];
+					memcpy(pcx,sign,3);
+					int res = fread((char*)pcx+3, 1, e->realSize-3, f);
+					fclose(f);
+					cp.openPCX((char*)pcx,e->realSize);
+					return cp.getSurface();
+				}
+			}
+		}
+	}
+	bitmap_handler_mx.lock();
+	fseek(bitmaph->FLOD, e->offset, 0);
+	if (e->size==0) //file is not compressed
+	{
+		pcx = new unsigned char[e->realSize];
+		fread((char*)pcx, 1, e->realSize, bitmaph->FLOD);
+		bitmap_handler_mx.unlock();
+	}
+	else 
+	{
+		unsigned char * pcd = new unsigned char[e->size];
+		fread((char*)pcd, 1, e->size, bitmaph->FLOD);
+		bitmap_handler_mx.unlock();
+		int res=bitmaph->infs2(pcd,e->size,e->realSize,pcx);
+		if(res!=0)
+		{
+			std::cout<<"an error "<<res<<" occured while extracting file "<<fname<<std::endl;
+		}
+		delete [] pcd;
+	}
+	CPCXConv cp;
+	cp.openPCX((char*)pcx,e->realSize);
+	SDL_Surface * ret = cp.getSurface();
+	if(setKey)
+		SDL_SetColorKey(ret,SDL_SRCCOLORKEY,SDL_MapRGB(ret->format,0,255,255));
+	return ret;
+}

+ 39 - 0
client/CBitmapHandler.h

@@ -0,0 +1,39 @@
+#pragma once
+#include "../global.h"
+struct SDL_Surface;
+class CLodHandler;
+
+enum Epcxformat {PCX8B, PCX24B};
+
+struct BMPPalette
+{
+	unsigned char R,G,B,F;
+};
+struct BMPHeader
+{
+	int fullSize, _h1, _h2, _h3, _c1, _c2, _c3, _c4, x, y,
+		dataSize1, dataSize2; //DataSize=X*Y+2*Y
+	unsigned char _c5[8];
+	void print(std::ostream & out);
+	BMPHeader(){_h1=_h2=0;for(int i=0;i<8;i++)_c5[i]=0;};
+};
+class CPCXConv
+{	
+public:
+	unsigned char * pcx, *bmp;
+	int pcxs, bmps;
+	void fromFile(std::string path);
+	void saveBMP(std::string path);
+	void openPCX(char * PCX, int len);
+	void openPCX();
+	void convert();
+	SDL_Surface * getSurface(); //for standard H3 PCX
+	//SDL_Surface * getSurfaceZ(); //for ZSoft PCX
+	CPCXConv(){pcx=bmp=NULL;pcxs=bmps=0;};
+	~CPCXConv(){if (pcxs) delete[] pcx; if(bmps) delete[] bmp;}
+};
+namespace BitmapHandler
+{
+	extern CLodHandler *bitmaph;
+	SDL_Surface * loadBitmap(std::string fname, bool setKey=false);
+};

+ 352 - 0
client/CCreatureAnimation.cpp

@@ -0,0 +1,352 @@
+#include "CCreatureAnimation.h"
+#include "../hch/CLodHandler.h"
+int CCreatureAnimation::getType() const
+{
+	return type;
+}
+
+void CCreatureAnimation::setType(int type)
+{
+	this->type = type;
+	curFrame = 0;
+	if(type!=-1)
+	{
+		if(SEntries[curFrame].group!=type) //rewind
+		{
+			int j=-1; //first frame in displayed group
+			for(int g=0; g<SEntries.size(); ++g)
+			{
+				if(SEntries[g].group==type && j==-1)
+				{
+					j = g;
+					break;
+				}
+			}
+			if(curFrame!=-1)
+				curFrame = j;
+		}
+	}
+	else
+	{
+		if(curFrame>=frames)
+			curFrame = 0;
+	}
+}
+
+CCreatureAnimation::CCreatureAnimation(std::string name) : RLEntries(NULL), RWEntries(NULL)
+{
+	FDef = CDefHandler::Spriteh->giveFile(name); //load main file
+
+	//init anim data
+	int i,j, totalInBlock;
+	char Buffer[13];
+	defName=name;
+	i = 0;
+	DEFType = readNormalNr(i,4); i+=4;
+	fullWidth = readNormalNr(i,4); i+=4;
+	fullHeight = readNormalNr(i,4); i+=4;
+	i=0xc;
+	totalBlocks = readNormalNr(i,4); i+=4;
+
+	i=0x10;
+	for (int it=0;it<256;it++)
+	{
+		palette[it].R = FDef[i++];
+		palette[it].G = FDef[i++];
+		palette[it].B = FDef[i++];
+		palette[it].F = 0;
+	}
+	i=0x310;
+	totalEntries=0;
+	for (int z=0; z<totalBlocks; z++)
+	{
+		int unknown1 = readNormalNr(i,4); i+=4;
+		totalInBlock = readNormalNr(i,4); i+=4;
+		for (j=SEntries.size(); j<totalEntries+totalInBlock; j++)
+			SEntries.push_back(SEntry());
+		int unknown2 = readNormalNr(i,4); i+=4;
+		int unknown3 = readNormalNr(i,4); i+=4;
+		for (j=0; j<totalInBlock; j++)
+		{
+			for (int k=0;k<13;k++) Buffer[k]=FDef[i+k]; 
+			i+=13;
+			SEntries[totalEntries+j].name=Buffer;
+		}
+		for (j=0; j<totalInBlock; j++)
+		{ 
+			SEntries[totalEntries+j].offset = readNormalNr(i,4);
+			int unknown4 = readNormalNr(i,4); i+=4;
+		}
+		//totalEntries+=totalInBlock;
+		for(int hh=0; hh<totalInBlock; ++hh)
+		{
+			SEntries[totalEntries].group = z;
+			++totalEntries;
+		}
+	}
+	for(j=0; j<SEntries.size(); ++j)
+	{
+		SEntries[j].name = SEntries[j].name.substr(0, SEntries[j].name.find('.')+4);
+	}
+
+	//init vars
+	curFrame = 0;
+	type = -1;
+	frames = totalEntries;
+}
+
+int CCreatureAnimation::readNormalNr (int pos, int bytCon, unsigned char * str, bool cyclic)
+{
+	int ret=0;
+	int amp=1;
+	if (str)
+	{
+		for (int i=0; i<bytCon; i++)
+		{
+			ret+=str[pos+i]*amp;
+			amp*=256;
+		}
+	}
+	else 
+	{
+		for (int i=0; i<bytCon; i++)
+		{
+			ret+=FDef[pos+i]*amp;
+			amp*=256;
+		}
+	}
+	if(cyclic && bytCon<4 && ret>=amp/2)
+	{
+		ret = ret-amp;
+	}
+	return ret;
+}
+int CCreatureAnimation::nextFrameMiddle(SDL_Surface *dest, int x, int y, bool attacker, bool incrementFrame, bool yellowBorder, SDL_Rect * destRect)
+{
+	return nextFrame(dest,x-fullWidth/2,y-fullHeight/2,attacker,incrementFrame,yellowBorder,destRect);
+}
+int CCreatureAnimation::nextFrame(SDL_Surface *dest, int x, int y, bool attacker, bool incrementFrame, bool yellowBorder, SDL_Rect * destRect)
+{
+	if(dest->format->BytesPerPixel<3)
+		return -1; //not enough depth
+
+	//increasing frame numer
+	int SIndex = -1;
+	if(incrementFrame)
+	{
+		SIndex = curFrame++;
+		if(type!=-1)
+		{
+			if(SEntries[curFrame].group!=type) //rewind
+			{
+				int j=-1; //first frame in displayed group
+				for(int g=0; g<SEntries.size(); ++g)
+				{
+					if(SEntries[g].group==type && j==-1)
+					{
+						j = g;
+						break;
+					}
+				}
+				if(curFrame!=-1)
+					curFrame = j;
+			}
+		}
+		else
+		{
+			if(curFrame>=frames)
+				curFrame = 0;
+		}
+	}
+	else
+	{
+		SIndex = curFrame;
+	}
+	//frame number increased
+
+	long BaseOffset, 
+		SpriteWidth, SpriteHeight, //sprite format
+		LeftMargin, RightMargin, TopMargin,BottomMargin,
+		i, add, FullHeight,FullWidth,
+		TotalRowLength, // length of read segment
+		RowAdd;
+	unsigned char SegmentType, SegmentLength;
+	
+	i=BaseOffset=SEntries[SIndex].offset;
+	int prSize=readNormalNr(i,4,FDef);i+=4;
+	int defType2 = readNormalNr(i,4,FDef);i+=4;
+	FullWidth = readNormalNr(i,4,FDef);i+=4;
+	FullHeight = readNormalNr(i,4,FDef);i+=4;
+	SpriteWidth = readNormalNr(i,4,FDef);i+=4;
+	SpriteHeight = readNormalNr(i,4,FDef);i+=4;
+	LeftMargin = readNormalNr(i,4,FDef);i+=4;
+	TopMargin = readNormalNr(i,4,FDef);i+=4;
+	RightMargin = FullWidth - SpriteWidth - LeftMargin;
+	BottomMargin = FullHeight - SpriteHeight - TopMargin;
+	
+	add = 4 - FullWidth%4;
+
+	int BaseOffsetor = BaseOffset = i;
+
+	int ftcp = 0;
+
+	if (defType2==1) //as it should be allways in creature animations
+	{
+		if (TopMargin>0)
+		{
+			for (int i=0;i<TopMargin;i++)
+			{
+				ftcp+=FullWidth+add;
+			}
+		}
+		RLEntries = new int[SpriteHeight];
+		for (int i=0;i<SpriteHeight;i++)
+		{
+			RLEntries[i]=readNormalNr(BaseOffset,4,FDef);BaseOffset+=4;
+		}
+		for (int i=0;i<SpriteHeight;i++)
+		{
+			BaseOffset=BaseOffsetor+RLEntries[i];
+			if (LeftMargin>0)
+			{
+				ftcp+=LeftMargin;
+			}
+			TotalRowLength=0;
+			do
+			{
+				SegmentType=FDef[BaseOffset++];
+				SegmentLength=FDef[BaseOffset++];
+				if (SegmentType==0xFF)
+				{
+					for (int k=0;k<=SegmentLength;k++)
+					{
+						int xB = (attacker ? ftcp%(FullWidth+add) : (FullWidth+add) - ftcp%(FullWidth+add) - 1) + x;
+						int yB = ftcp/(FullWidth+add) + y;
+						if(xB>=0 && yB>=0 && xB<dest->w && yB<dest->h)
+						{
+							if(!destRect || (destRect->x <= xB && destRect->x + destRect->w > xB && destRect->y <= yB && destRect->y + destRect->h > yB))
+								putPixel(dest, xB + yB*dest->w, palette[FDef[BaseOffset+k]], FDef[BaseOffset+k], yellowBorder);
+						}
+						ftcp++; //increment pos
+						if ((TotalRowLength+k+1)>=SpriteWidth)
+							break;
+					}
+					BaseOffset+=SegmentLength+1;////
+					TotalRowLength+=SegmentLength+1;
+				}
+				else
+				{
+					for (int k=0;k<SegmentLength+1;k++)
+					{
+						int xB = (attacker ? ftcp%(FullWidth+add) : (FullWidth+add) - ftcp%(FullWidth+add) - 1) + x;
+						int yB = ftcp/(FullWidth+add) + y;
+						if(xB>=0 && yB>=0 && xB<dest->w && yB<dest->h)
+						{
+							if(!destRect || (destRect->x <= xB && destRect->x + destRect->w > xB && destRect->y <= yB && destRect->y + destRect->h > yB))
+								putPixel(dest, xB + yB*dest->w, palette[SegmentType], SegmentType, yellowBorder);
+						}
+						ftcp++; //increment pos
+					}
+					TotalRowLength+=SegmentLength+1;
+				}
+			}while(TotalRowLength<SpriteWidth);
+			RowAdd=SpriteWidth-TotalRowLength;
+			if (RightMargin>0)
+			{
+				ftcp+=RightMargin;
+			}
+			if (add>0)
+			{
+				ftcp+=add+RowAdd;
+			}
+		}
+		delete [] RLEntries;
+		RLEntries = NULL;
+		if (BottomMargin>0)
+		{
+			ftcp += BottomMargin * (FullWidth+add);
+		}
+	}
+
+	//SDL_UpdateRect(dest, x, y, FullWidth+add, FullHeight);
+
+	return 0;
+}
+
+int CCreatureAnimation::framesInGroup(int group) const
+{
+	int ret = 0; //number of frames in given group
+	for(int g=0; g<SEntries.size(); ++g)
+	{
+		if(SEntries[g].group == group)
+			++ret;
+	}
+	return ret;
+}
+
+CCreatureAnimation::~CCreatureAnimation()
+{
+	delete [] FDef;
+	if (RWEntries)
+		delete [] RWEntries;
+	if (RLEntries)
+		delete [] RLEntries;
+}
+
+void CCreatureAnimation::putPixel(SDL_Surface * dest, const int & ftcp, const BMPPalette & color, const unsigned char & palc, const bool & yellowBorder) const
+{
+	if(palc!=0)
+	{
+		Uint8 * p = (Uint8*)dest->pixels + ftcp*3;
+		if(palc > 7) //normal color
+		{
+			p[0] = color.B;
+			p[1] = color.G;
+			p[2] = color.R;
+		}
+		else if(yellowBorder && (palc == 6 || palc == 7)) //dark yellow border
+		{
+			p[0] = 0;
+			p[1] = 0xff;
+			p[2] = 0xff;
+		}
+		else if(yellowBorder && (palc == 5)) //yellow border
+		{
+			p[0] = color.B;
+			p[1] = color.G;
+			p[2] = color.R;
+		}
+		else if(palc < 5) //shadow
+		{ 
+			Uint16 alpha;
+			switch(color.G)
+			{
+			case 0:
+				alpha = 128;
+				break;
+			case 50:
+				alpha = 50+32;
+				break;
+			case 100:
+				alpha = 100+64;
+				break;
+			case 125:
+				alpha = 125+64;
+				break;
+			case 128:
+				alpha = 128+64;
+				break;
+			case 150:
+				alpha = 150+64;
+				break;
+			default:
+				alpha = 255;
+				break;
+			}
+			//alpha counted
+			p[0] = (p[0] * alpha)>>8;
+			p[1] = (p[1] * alpha)>>8;
+			p[2] = (p[2] * alpha)>>8;
+		}
+	}
+}

+ 45 - 0
client/CCreatureAnimation.h

@@ -0,0 +1,45 @@
+#pragma once
+#include "../global.h"
+#include "../CPlayerInterface.h"
+#include "../hch/CDefHandler.h"
+
+class CCreatureAnimation : public CIntObject
+{
+private:
+	int totalEntries, DEFType, totalBlocks;
+	bool allowRepaint;
+	int length;
+	BMPPalette palette[256];
+	unsigned int * RWEntries;
+	int * RLEntries;
+	struct SEntry
+	{
+		std::string name;
+		int offset;
+		int group;
+	} ;
+	std::vector<SEntry> SEntries ;
+	char id[2];
+	std::string defName, curDir;
+	int readNormalNr (int pos, int bytCon, unsigned char * str=NULL, bool cyclic=false);
+	void putPixel(SDL_Surface * dest, const int & ftcp, const BMPPalette & color, const unsigned char & palc, const bool & yellowBorder) const;
+
+	////////////
+
+	unsigned char * FDef; //animation raw data
+	unsigned int curFrame; //number of currently displayed frame
+	unsigned int frames; //number of frames
+	int type; //type of animation being displayed (-1 - whole animation, >0 - specified part [default: -1])
+public:
+	int fullWidth, fullHeight; //read-only, please!
+	CCreatureAnimation(std::string name); //c-tor
+	~CCreatureAnimation(); //d-tor
+
+	void setType(int type); //sets type of animation and cleares framecount
+	int getType() const; //returns type of animation
+
+	int nextFrame(SDL_Surface * dest, int x, int y, bool attacker, bool incrementFrame = true, bool yellowBorder = false, SDL_Rect * destRect = NULL); //0 - success, any other - error //print next 
+	int nextFrameMiddle(SDL_Surface * dest, int x, int y, bool attacker, bool incrementFrame = true, bool yellowBorder = false, SDL_Rect * destRect = NULL); //0 - success, any other - error //print next 
+
+	int framesInGroup(int group) const; //retirns number of fromes in given group
+};

+ 425 - 0
client/Client.cpp

@@ -0,0 +1,425 @@
+#include "Client.h"
+#include "../lib/Connection.h"
+#include "../StartInfo.h"
+#include "../map.h"
+#include "../CGameState.h"
+#include "../CGameInfo.h"
+#include "../mapHandler.h"
+#include "../CCallback.h"
+#include "../CPlayerInterface.h"
+#include "../CConsoleHandler.h"
+#include "../lib/NetPacks.h"
+#include <boost/bind.hpp>
+#include <boost/thread.hpp>
+#include <boost/foreach.hpp>
+#include "../hch/CObjectHandler.h"
+#include "../hch/CGeneralTextHandler.h"
+#include "../hch/CArtHandler.h"
+#include <boost/thread/shared_mutex.hpp>
+#include "../lib/VCMI_Lib.h"
+CSharedCond<std::set<IPack*> > mess(new std::set<IPack*>);
+
+std::string toString(MetaString &ms)
+{
+	std::string ret;
+	for(int i=0;i<ms.message.size();i++)
+	{
+		if(ms.message[i]>0)
+		{
+			ret += ms.strings[ms.message[i]-1];
+		}
+		else
+		{
+			std::vector<std::string> *vec;
+			int type = ms.texts[-ms.message[i]-1].first,
+				ser = ms.texts[-ms.message[i]-1].second;
+			if(type == 5)
+			{
+				ret += CGI->arth->artifacts[ser].name;
+				continue;
+			}
+			else if(type == 7)
+			{
+				ret += CGI->creh->creatures[ser].namePl;
+				continue;
+			}
+			else if(type == 9)
+			{
+				ret += CGI->objh->mines[ser].first;
+				continue;
+			}
+			else if(type == 10)
+			{
+				ret += CGI->objh->mines[ser].second;
+				continue;
+			}
+			else
+			{
+				switch(type)
+				{
+				case 1:
+					vec = &CGI->generaltexth->allTexts;
+					break;
+				case 2:
+					vec = &CGI->objh->xtrainfo;
+					break;
+				case 3:
+					vec = &CGI->objh->names;
+					break;
+				case 4:
+					vec = &CGI->objh->restypes;
+					break;
+				case 6:
+					vec = &CGI->generaltexth->arraytxt;
+					break;
+				case 8:
+					vec = &CGI->objh->creGens;
+					break;
+				case 11:
+					vec = &CGI->objh->advobtxt;
+				}
+				ret += (*vec)[ser];
+			}
+		}
+	}
+	for(int i=0;i<ms.replacements.size();i++)
+	{
+		ret.replace(ret.find("%s"),2,ms.replacements[i]);
+	}
+	return ret;
+}
+
+CClient::CClient(void)
+{
+}
+CClient::CClient(CConnection *con, StartInfo *si)
+	:serv(con)
+{		
+	timeHandler tmh;
+	CGI->state = new CGameState();
+	THC std::cout<<"\tGamestate: "<<tmh.getDif()<<std::endl;
+	CConnection &c(*con);
+////////////////////////////////////////////////////
+	ui8 pom8;
+	c << ui8(2) << ui8(1); //new game; one client
+	c << *si;
+	c >> pom8;
+	if(pom8) throw "Server cannot open the map!";
+	c << ui8(si->playerInfos.size());
+	for(int i=0;i<si->playerInfos.size();i++)
+		c << ui8(si->playerInfos[i].color);
+
+	ui32 seed, sum;
+	std::string mapname;
+	c >> mapname >> sum >> seed;
+	THC std::cout<<"\tSending/Getting info to/from the server: "<<tmh.getDif()<<std::endl;
+
+	Mapa * mapa = new Mapa(mapname);
+	THC std::cout<<"Reading and detecting map file (together): "<<tmh.getDif()<<std::endl;
+	std::cout << "\tServer checksum for "<<mapname <<": "<<sum << std::endl;
+	std::cout << "\tOur checksum for the map: "<< mapa->checksum << std::endl;
+
+	if(mapa->checksum != sum)
+	{
+#ifndef __GNUC__
+		throw std::exception("Wrong checksum");
+#else
+		throw std::exception();
+#endif
+		exit(-1);
+	}
+	std::cout << "\tUsing random seed: "<<seed << std::endl;
+
+	gs = CGI->state;
+	gs->scenarioOps = si;
+	gs->init(si,mapa,seed);
+
+	CGI->mh = new CMapHandler();
+	THC std::cout<<"Initializing GameState (together): "<<tmh.getDif()<<std::endl;
+	CGI->mh->map = mapa;
+	THC std::cout<<"Creating mapHandler: "<<tmh.getDif()<<std::endl;
+	CGI->mh->init();
+	THC std::cout<<"Initializing mapHandler (together): "<<tmh.getDif()<<std::endl;
+
+	for (int i=0; i<CGI->state->scenarioOps->playerInfos.size();i++) //initializing interfaces
+	{ 
+		ui8 color = gs->scenarioOps->playerInfos[i].color;
+		CCallback *cb = new CCallback(gs,color,this);
+		if(!gs->scenarioOps->playerInfos[i].human)
+		{
+			playerint[color] = static_cast<CGameInterface*>(CAIHandler::getNewAI(cb,"EmptyAI.dll"));
+		}
+		else 
+		{
+			gs->currentPlayer = color;
+			playerint[color] = new CPlayerInterface(color,i);
+			playerint[color]->init(cb);
+		}
+	}
+	CGI->consoleh->cb = new CCallback(gs,-1,this);
+}
+CClient::~CClient(void)
+{
+}
+void CClient::process(int what)
+{
+	switch (what)
+	{
+	case 100: //one of our interaces has turn
+		{
+			ui8 player;
+			*serv >> player;//who?
+			std::cout << "It's turn of "<<(unsigned)player<<" player."<<std::endl;
+			boost::thread(boost::bind(&CGameInterface::yourTurn,playerint[player]));
+			break;
+		}
+	case 101:
+		{
+			NewTurn n;
+			*serv >> n;
+			std::cout << "New day: "<<(unsigned)n.day<<". Applying changes... ";
+			gs->apply(&n);
+			std::cout << "done!"<<std::endl;
+			break;
+		}
+	case 102: //set resource amount
+		{
+			SetResource sr;
+			*serv >> sr;
+			std::cout << "Set amount of "<<CGI->objh->restypes[sr.resid] 
+			  << " of player "<<(unsigned)sr.player <<" to "<<sr.val<<std::endl;
+			gs->apply(&sr);
+			playerint[sr.player]->receivedResource(sr.resid,sr.val);
+			break;
+		}
+	case 103: //show info dialog
+		{
+			InfoWindow iw;
+			*serv >> iw;
+			std::vector<Component*> comps;
+			for(int i=0;i<iw.components.size();i++)
+				comps.push_back(&iw.components[i]);
+			playerint[iw.player]->showInfoDialog(toString(iw.text),comps);
+			break;
+		}
+	case 104:
+		{
+			SetResources sr;
+			*serv >> sr;
+			std::cout << "Set amount of resources of player "<<(unsigned)sr.player<<std::endl;
+			gs->apply(&sr);
+			playerint[sr.player]->receivedResource(-1,-1);
+			break;
+		}
+	case 105:
+		{
+			SetPrimSkill sps;
+			*serv >> sps;
+			std::cout << "Changing hero primary skill"<<std::endl;
+			gs->apply(&sps);
+			playerint[gs->getHero(sps.id)->tempOwner]->heroPrimarySkillChanged(gs->getHero(sps.id),sps.which,sps.val);
+			break;
+		}
+	case 107:
+		{
+			ShowInInfobox sii;
+			*serv >> sii;
+			SComponent sc(sii.c);
+			sc.description = toString(sii.text);
+			if(playerint[sii.player]->human)
+				static_cast<CPlayerInterface*>(playerint[sii.player])->showComp(sc);
+			break;
+		}
+	case 500:
+		{
+			RemoveHero rh;
+			*serv >> rh;
+			CGHeroInstance *h = static_cast<CGHeroInstance*>(gs->map->objects[rh.id]);
+			std::cout << "Removing hero with id = "<<(unsigned)rh.id<<std::endl;
+			CGI->mh->removeObject(h);
+			gs->apply(&rh);
+			playerint[h->tempOwner]->heroKilled(h);
+			break;
+		}
+	case 501: //hero movement response - we have to notify interfaces and callback
+		{
+			TryMoveHero *th = new TryMoveHero; //will be deleted by callback after processing
+			*serv >> *th;
+			std::cout << "HeroMove: id="<<th->id<<"\tResult: "<<(unsigned)th->result<<"\tPosition "<<th->end<<std::endl;
+
+			gs->apply(th);
+			int player = gs->map->objects[th->id]->getOwner();
+
+			if(playerint[player])
+			{
+				for(std::set<int3>::iterator i=th->fowRevealed.begin(); i != th->fowRevealed.end(); i++)
+					playerint[player]->tileRevealed(*i);
+				//std::for_each(th->fowRevealed.begin(),th->fowRevealed.end(),boost::bind(&CGameInterface::tileRevealed,playerint[player],_1));
+			}
+
+			//notify interfacesabout move
+			int nn=0; //number of interfece of currently browsed player
+			for(std::map<ui8, CGameInterface*>::iterator i=playerint.begin();i!=playerint.end();i++)
+			{
+				if(gs->players[i->first].fogOfWarMap[th->start.x-1][th->start.y][th->start.z] || gs->players[i->first].fogOfWarMap[th->end.x-1][th->end.y][th->end.z])
+				{
+					HeroMoveDetails hmd(th->start,th->end,static_cast<CGHeroInstance*>(gs->map->objects[th->id]));
+					hmd.successful = th->result;
+					i->second->heroMoved(hmd);
+				}
+			}
+
+			//add info for callback
+			mess.mx->lock();
+			mess.res->insert(th);
+			mess.mx->unlock();
+			mess.cv->notify_all();
+			break;
+		}
+	case 502:
+		{
+			SetGarrisons sg;
+			*serv >> sg;
+			gs->apply(&sg);
+			for(std::map<ui32,CCreatureSet>::iterator i = sg.garrs.begin(); i!=sg.garrs.end(); i++)
+				playerint[gs->map->objects[i->first]->tempOwner]->garrisonChanged(gs->map->objects[i->first]);
+			break;
+		}
+	case 503:
+		{
+			SetStrInfo ssi;
+			*serv >> ssi;
+			gs->apply(&ssi);
+			//TODO: notify interfaces
+			break;
+		}
+	case 504:
+		{
+			NewStructures ns;
+			*serv >> ns;
+			gs->apply(&ns);
+			BOOST_FOREACH(si32 bid, ns.bid)
+				playerint[gs->map->objects[ns.tid]->tempOwner]->buildChanged(static_cast<CGTownInstance*>(gs->map->objects[ns.tid]),bid,1);
+			break;
+		}
+	case 1001:
+		{
+			SetObjectProperty sop;
+			*serv >> sop;
+			std::cout << "Setting " << (unsigned)sop.what << " property of " << sop.id <<" object to "<<sop.val<<std::endl;
+			gs->apply(&sop);
+			break;
+		}
+	case 1002:
+		{
+			SetHoverName shn;
+			*serv >> shn;
+			std::cout << "Setting a name of " << shn.id <<" object to "<< toString(shn.name) <<std::endl;
+			gs->mx->lock();
+			gs->map->objects[shn.id]->hoverName = toString(shn.name);
+			gs->mx->unlock();
+			break;
+		}
+	case 3000:
+		{
+			BattleStart bs;
+			*serv >> bs; //uses new to allocate memory for battleInfo - must be deleted when battle is over
+			std::cout << "Starting battle!" <<std::endl;
+			gs->apply(&bs);
+
+			if(playerint.find(gs->curB->side1) != playerint.end())
+				playerint[gs->curB->side1]->battleStart(&gs->curB->army1, &gs->curB->army2, gs->curB->tile, gs->getHero(gs->curB->hero1), gs->getHero(gs->curB->hero2), 0);
+			if(playerint.find(gs->curB->side2) != playerint.end())
+				playerint[gs->curB->side2]->battleStart(&gs->curB->army1, &gs->curB->army2, gs->curB->tile, gs->getHero(gs->curB->hero1), gs->getHero(gs->curB->hero2), 1);
+			
+			break;
+		}
+	case 3001:
+		{
+			BattleNextRound bnr;
+			*serv >> bnr;
+			std::cout << "Round nr " << bnr.round <<std::endl;
+			gs->apply(&bnr);
+
+			//tell players about next round
+			if(playerint.find(gs->curB->side1) != playerint.end())
+				playerint[gs->curB->side1]->battleNewRound(bnr.round);
+			if(playerint.find(gs->curB->side2) != playerint.end())
+				playerint[gs->curB->side2]->battleNewRound(bnr.round);
+			break;
+		}
+	case 3002:
+		{
+			BattleSetActiveStack sas;
+			*serv >> sas;
+			std::cout << "Active stack: " << sas.stack <<std::endl;
+			gs->apply(&sas);
+			int owner = gs->curB->getStack(sas.stack)->owner;
+			if(owner >= PLAYER_LIMIT) //ugly workaround to skip neutral creatures - should be replaced with AI
+			{
+				BattleAction ba;
+				ba.stackNumber = sas.stack;
+				ba.actionType = 3;
+				*serv << ui16(3002) << ba;
+			}
+			else
+			{
+				boost::thread(boost::bind(&CClient::waitForMoveAndSend,this,owner));
+			}
+			break;
+		}
+	case 3003:
+		{
+			BattleResult br;
+			*serv >> br;
+			std::cout << "Battle ends. Winner: " << (unsigned)br.winner<< ". Type of end: "<< (unsigned)br.result <<std::endl;
+
+			if(playerint.find(gs->curB->side1) != playerint.end())
+				playerint[gs->curB->side1]->battleEnd(&br);
+			if(playerint.find(gs->curB->side2) != playerint.end())
+				playerint[gs->curB->side2]->battleEnd(&br);
+
+			gs->apply(&br);
+			break;
+		}
+	case 3004:
+		{
+			BattleStackMoved br;
+			*serv >> br;
+			std::cout << "Stack "<<br.stack <<" moves to the tile "<<br.tile<<std::endl;
+			if(playerint.find(gs->curB->side1) != playerint.end())
+				playerint[gs->curB->side1]->battleStackMoved(br.stack,br.tile,br.flags&1,br.flags&2);
+			if(playerint.find(gs->curB->side2) != playerint.end())
+				playerint[gs->curB->side2]->battleStackMoved(br.stack,br.tile,br.flags&1,br.flags&2);
+			gs->apply(&br);
+			break;
+		}
+	case 9999:
+		break;
+	default:
+#ifndef __GNUC__
+		throw std::exception("Not supported server message!");
+#else
+		throw std::exception();
+#endif
+		break;
+	}
+}
+void CClient::waitForMoveAndSend(int color)
+{
+	BattleAction ba = playerint[color]->activeStack(gs->curB->activeStack);
+	*serv << ui16(3002) << ba;
+}
+void CClient::run()
+{
+	try
+	{
+		ui16 typ;
+		while(1)
+		{
+			*serv >> typ;
+			process(typ);
+		}
+	} HANDLE_EXCEPTION
+}
+

+ 53 - 0
client/Client.h

@@ -0,0 +1,53 @@
+#pragma once
+#include "../global.h"
+#include <boost/thread.hpp>
+struct StartInfo;
+class CGameState;
+class CGameInterface;
+class CConnection;
+class CCallback;
+
+namespace boost
+{
+	class mutex;
+	class condition_variable;
+}
+
+template <typename T>
+struct CSharedCond
+{
+	boost::mutex *mx;
+	boost::condition_variable *cv;
+	T *res;
+	CSharedCond(T*R)
+	{
+		res = R;
+		mx = new boost::mutex;
+		cv = new boost::condition_variable;
+	}
+	~CSharedCond()
+	{
+		delete res;
+		delete mx;
+		delete cv;
+	}
+};
+
+class CClient
+{
+	CGameState *gs;
+	std::map<ui8,CGameInterface *> playerint;
+	CConnection *serv;
+
+	void waitForMoveAndSend(int color);
+public:
+	CClient(void);
+	CClient(CConnection *con, StartInfo *si);
+	~CClient(void);
+
+	void process(int what);
+	void run();
+
+	friend class CCallback;
+	friend class CScriptCallback;
+};

+ 486 - 0
client/Graphics.cpp

@@ -0,0 +1,486 @@
+#include "../stdafx.h"
+#include "Graphics.h"
+#include "../hch/CDefHandler.h"
+#include "../hch/CObjectHandler.h"
+#include "../SDL_Extensions.h"
+#include <boost/assign/std/vector.hpp> 
+#include <sstream>
+#include <iomanip>
+#include <boost/thread.hpp>
+#include <boost/function.hpp>
+#include <boost/bind.hpp>
+#include <boost/assign/std/vector.hpp>
+#include "../CThreadHelper.h"
+#include "../CGameInfo.h"
+#include "../hch/CLodHandler.h"
+using namespace boost::assign;
+using namespace CSDL_Ext;
+#ifdef min
+#undef min
+#endif
+#ifdef max
+#undef max
+#endif
+Graphics * graphics = NULL;
+SDL_Surface * Graphics::drawPrimarySkill(const CGHeroInstance *curh, SDL_Surface *ret, int from, int to)
+{
+	char * buf = new char[10];
+	for (int i=from;i<to;i++)
+	{
+		SDL_itoa(curh->primSkills[i],buf,10);
+		printAtMiddle(buf,84+28*i,68,GEOR13,zwykly,ret);
+	}
+	delete[] buf;
+	return ret;
+}
+SDL_Surface * Graphics::drawHeroInfoWin(const CGHeroInstance * curh)
+{
+	char * buf = new char[10];
+	blueToPlayersAdv(hInfo,curh->tempOwner);
+	SDL_Surface * ret = SDL_DisplayFormat(hInfo);
+	SDL_SetColorKey(ret,SDL_SRCCOLORKEY,SDL_MapRGB(ret->format,0,255,255));
+	printAt(curh->name,75,15,GEOR13,zwykly,ret);
+	drawPrimarySkill(curh, ret);
+	for (std::map<si32,std::pair<ui32,si32> >::const_iterator i=curh->army.slots.begin(); i!=curh->army.slots.end();i++)
+	{
+		blitAt(graphics->smallImgs[(*i).second.first],slotsPos[(*i).first].first+1,slotsPos[(*i).first].second+1,ret);
+		SDL_itoa((*i).second.second,buf,10);
+		printAtMiddle(buf,slotsPos[(*i).first].first+17,slotsPos[(*i).first].second+39,GEORM,zwykly,ret);
+	}
+	blitAt(graphics->portraitLarge[curh->portrait],11,12,ret);
+	SDL_itoa(curh->mana,buf,10);
+	printAtMiddle(buf,166,109,GEORM,zwykly,ret); //mana points
+	delete[] buf;
+	blitAt(morale22->ourImages[curh->getCurrentMorale()+3].bitmap,14,84,ret);
+	blitAt(luck22->ourImages[curh->getCurrentLuck()+3].bitmap,14,101,ret);
+	return ret;
+}
+SDL_Surface * Graphics::drawTownInfoWin(const CGTownInstance * curh)
+{
+	char * buf = new char[10];
+	blueToPlayersAdv(tInfo,curh->tempOwner);
+	SDL_Surface * ret = SDL_DisplayFormat(tInfo);
+	SDL_SetColorKey(ret,SDL_SRCCOLORKEY,SDL_MapRGB(ret->format,0,255,255));
+	printAt(curh->name,75,15,GEOR13,zwykly,ret);
+
+	int pom = curh->fortLevel() - 1; if(pom<0) pom = 3;
+	blitAt(forts->ourImages[pom].bitmap,115,42,ret);
+	if((pom=curh->hallLevel())>=0)
+		blitAt(halls->ourImages[pom].bitmap,77,42,ret);
+	SDL_itoa(curh->dailyIncome(),buf,10);
+	printAtMiddle(buf,167,70,GEORM,zwykly,ret);
+	for (std::map<si32,std::pair<ui32,si32> >::const_iterator i=curh->army.slots.begin(); i!=curh->army.slots.end();i++)
+	{
+		if(!i->second.first)
+			continue;
+		blitAt(graphics->smallImgs[(*i).second.first],slotsPos[(*i).first].first+1,slotsPos[(*i).first].second+1,ret);
+		SDL_itoa((*i).second.second,buf,10);
+		printAtMiddle(buf,slotsPos[(*i).first].first+17,slotsPos[(*i).first].second+39,GEORM,zwykly,ret);
+	}
+
+	//blit town icon
+	pom = curh->subID*2;
+	if (!curh->hasFort())
+		pom += F_NUMBER*2;
+	if(curh->builded >= MAX_BUILDING_PER_TURN)
+		pom++;
+	blitAt(bigTownPic->ourImages[pom].bitmap,13,13,ret);
+	delete[] buf;
+	return ret;
+}
+
+void Graphics::loadPaletteAndColors()
+{
+	std::string pals = CGI->bitmaph->getTextFile("PLAYERS.PAL");
+	playerColorPalette = new SDL_Color[256];
+	neutralColor = new SDL_Color;
+	playerColors = new SDL_Color[PLAYER_LIMIT];
+	int startPoint = 24; //beginning byte; used to read
+	for(int i=0; i<256; ++i)
+	{
+		SDL_Color col;
+		col.r = pals[startPoint++];
+		col.g = pals[startPoint++];
+		col.b = pals[startPoint++];
+		col.unused = pals[startPoint++];
+		playerColorPalette[i] = col;
+	}
+	//colors initialization
+	int3 kolory[] = {int3(0xff,0,0),int3(0x31,0x52,0xff),int3(0x9c,0x73,0x52),int3(0x42,0x94,0x29),
+		int3(0xff,0x84,0x0),int3(0x8c,0x29,0xa5),int3(0x09,0x9c,0xa5),int3(0xc6,0x7b,0x8c)};
+	for(int i=0;i<8;i++)
+	{
+		playerColors[i].r = kolory[i].x;
+		playerColors[i].g = kolory[i].y;
+		playerColors[i].b = kolory[i].z;
+		playerColors[i].unused = 0;
+	}
+	neutralColor->r = 0x84; neutralColor->g = 0x84; neutralColor->b = 0x84;//gray
+}	
+void Graphics::initializeBattleGraphics()
+{
+	std::ifstream bback("config/battleBack.txt");
+	battleBacks.resize(9);
+	for(int i=0; i<9; ++i) //9 - number of terrains battle can be fought on
+	{
+		int am;
+		bback>>am;
+		battleBacks[i].resize(am);
+		for(int f=0; f<am; ++f)
+		{
+			bback>>battleBacks[i][f];
+		}
+	}
+
+	//initializing battle hero animation
+	std::ifstream bher("config/battleHeroes.txt");
+	int numberofh;
+	bher>>numberofh;
+	battleHeroes.resize(numberofh);
+	for(int i=0; i<numberofh; ++i) //9 - number of terrains battle can be fought on
+	{
+		bher>>battleHeroes[i];
+	}
+}
+Graphics::Graphics()
+{
+	slotsPos.push_back(std::pair<int,int>(44,82));
+	slotsPos.push_back(std::pair<int,int>(80,82));
+	slotsPos.push_back(std::pair<int,int>(116,82));
+	slotsPos.push_back(std::pair<int,int>(26,131));
+	slotsPos.push_back(std::pair<int,int>(62,131));
+	slotsPos.push_back(std::pair<int,int>(98,131));
+	slotsPos.push_back(std::pair<int,int>(134,131));
+
+	CDefHandler *smi, *smi2;
+
+	std::vector<Task> tasks; //preparing list of graphics to load
+	tasks += boost::bind(&Graphics::loadPaletteAndColors,this);
+	tasks += boost::bind(&Graphics::loadHeroFlags,this);
+	tasks += boost::bind(&Graphics::loadHeroPortraits,this);
+	tasks += boost::bind(&Graphics::initializeBattleGraphics,this);
+	tasks += GET_SURFACE(hInfo,"HEROQVBK.bmp");
+	tasks += GET_SURFACE(tInfo,"TOWNQVBK.bmp");
+	tasks += GET_DEF(artDefs,"ARTIFACT.DEF");
+	tasks += GET_DEF_ESS(forts,"ITMCLS.DEF");
+	tasks += GET_DEF_ESS(luck22,"ILCK22.DEF");
+	tasks += GET_DEF_ESS(luck30,"ILCK30.DEF");
+	tasks += GET_DEF_ESS(luck42,"ILCK42.DEF");
+	tasks += GET_DEF_ESS(luck82,"ILCK82.DEF");
+	tasks += GET_DEF_ESS(morale22,"IMRL22.DEF");
+	tasks += GET_DEF_ESS(morale30,"IMRL30.DEF");
+	tasks += GET_DEF_ESS(morale42,"IMRL42.DEF");
+	tasks += GET_DEF_ESS(morale82,"IMRL82.DEF");
+	tasks += GET_DEF_ESS(halls,"ITMTLS.DEF");
+	tasks += GET_DEF_ESS(bigTownPic,"ITPT.DEF");
+	tasks += GET_DEF(pskillsb,"PSKILL.DEF");
+	tasks += GET_DEF(resources,"RESOUR82.DEF");
+	tasks += GET_DEF(un44,"UN44.DEF");
+	tasks += GET_DEF(smallIcons,"ITPA.DEF");
+	tasks += GET_DEF(resources32,"RESOURCE.DEF");
+	tasks += GET_DEF(smi,"CPRSMALL.DEF");
+	tasks += GET_DEF(smi2,"TWCRPORT.DEF");
+
+	std::ifstream ifs("config/cr_bgs.txt"); 
+	int id;
+	std::string name;
+	while(!ifs.eof())
+	{
+		ifs >> id >> name;
+		tasks += GET_SURFACE(backgrounds[id],name);
+	}
+
+	CThreadHelper th(&tasks,std::max((unsigned int)1,boost::thread::hardware_concurrency()));
+	th.run();
+
+	//handling 32x32px imgs
+	smi->notFreeImgs = true;
+	for (int i=0; i<smi->ourImages.size(); i++)
+	{
+		smallImgs[i-2] = smi->ourImages[i].bitmap;
+	}
+	delete smi;
+	smi2->notFreeImgs = true;
+	for (int i=0; i<smi2->ourImages.size(); i++)
+	{
+		bigImgs[i-2] = smi2->ourImages[i].bitmap;
+	}
+	delete smi2;
+}
+void Graphics::loadHeroPortraits()
+{	
+	std::ifstream of("config/portrety.txt");
+	int numberOfPortraits;
+	of>>numberOfPortraits;
+	for (int j=0; j<numberOfPortraits; j++)
+	{
+		int ID;
+		of>>ID;
+		std::string path;
+		of>>path;
+		portraitSmall.push_back(BitmapHandler::loadBitmap(path));
+		for(int ff=0; ff<path.size(); ++ff) //size letter is usually third one, but there are exceptions an it should fix the problem
+		{
+			if(path[ff]=='S')
+			{
+				path[ff]='L';
+				break;
+			}
+		}
+		portraitLarge.push_back(BitmapHandler::loadBitmap(path));
+		SDL_SetColorKey(portraitLarge[portraitLarge.size()-1],SDL_SRCCOLORKEY,SDL_MapRGB(portraitLarge[portraitLarge.size()-1]->format,0,255,255));
+
+	}
+	of.close();
+}
+void Graphics::loadHeroAnim(std::vector<CDefHandler **> & anims)
+{
+	std::vector<std::pair<int,int> > rotations; //first - group number to be rotated1, second - group number after rotation1
+	rotations += std::make_pair(6,10), std::make_pair(7,11), std::make_pair(8,12), std::make_pair(1,13),
+		std::make_pair(2,14), std::make_pair(3,15);
+	for(int i=0; i<anims.size();i++)
+	{
+		std::stringstream nm;
+		nm << "AH" << std::setw(2) << std::setfill('0') << i << "_.DEF";
+		std::string name = nm.str();
+		(*anims[i]) = CDefHandler::giveDef(name);
+		int pom = 0; //how many groups has been rotated
+		for(int o=7; pom<6; ++o)
+		{
+			for(int p=0;p<6;p++)
+			{
+				if((*anims[i])->ourImages[o].groupNumber==rotations[p].first)
+				{
+					for(int e=0; e<8; ++e)
+					{
+						Cimage nci;
+						nci.bitmap = CSDL_Ext::rotate01((*anims[i])->ourImages[o+e].bitmap);
+						nci.groupNumber = rotations[p].second;
+						nci.imName = std::string();
+						(*anims[i])->ourImages.push_back(nci);
+						if(pom>2) //we need only one frame for groups 13/14/15
+							break;
+					}
+					if(pom<3) //there are eight frames of animtion of groups 6/7/8 so for speed we'll skip them
+						o+=8;
+					else //there is only one frame of 1/2/3
+						o+=1;
+					++pom;
+					if(p==2 && pom<4) //group1 starts at index 1
+						o = 1;
+				}
+			}
+		}
+		for(int ff=0; ff<(*anims[i])->ourImages.size(); ++ff)
+		{
+			CSDL_Ext::alphaTransform((*anims[i])->ourImages[ff].bitmap);
+		}
+		(*anims[i])->alphaTransformed = true;
+	}
+}
+
+void Graphics::loadHeroFlags(std::pair<std::vector<CDefHandler *> Graphics::*, std::vector<const char *> > &pr, bool mode)
+{
+	for(int i=0;i<8;i++)
+		(this->*pr.first).push_back(CDefHandler::giveDef(pr.second[i]));
+	std::vector<std::pair<int,int> > rotations; //first - group number to be rotated1, second - group number after rotation1
+	rotations += std::make_pair(6,10), std::make_pair(7,11), std::make_pair(8,12);
+	for(int q=0; q<8; ++q)
+	{
+		for(int o=0; o<(this->*pr.first)[q]->ourImages.size(); ++o)
+		{
+			for(int p=0;p<rotations.size();p++)
+			{
+				if((this->*pr.first)[q]->ourImages[o].groupNumber==rotations[p].first)
+				{
+					for(int e=0; e<8; ++e)
+					{
+						Cimage nci;
+						nci.bitmap = CSDL_Ext::rotate01((this->*pr.first)[q]->ourImages[o+e].bitmap);
+						nci.groupNumber = rotations[p].second;
+						nci.imName = std::string();
+						(this->*pr.first)[q]->ourImages.push_back(nci);
+					}
+					o+=8;
+				}
+			}
+		}
+		if (mode)
+		{
+			for(int o=0; o<flags4[q]->ourImages.size(); ++o)
+			{
+				if(flags4[q]->ourImages[o].groupNumber==1)
+				{
+					for(int e=0; e<8; ++e)
+					{
+						Cimage nci;
+						nci.bitmap = CSDL_Ext::rotate01(flags4[q]->ourImages[o+e].bitmap);
+						nci.groupNumber = 13;
+						nci.imName = std::string();
+						flags4[q]->ourImages.push_back(nci);
+					}
+					o+=8;
+				}
+				if(flags4[q]->ourImages[o].groupNumber==2)
+				{
+					for(int e=0; e<8; ++e)
+					{
+						Cimage nci;
+						nci.bitmap = CSDL_Ext::rotate01(flags4[q]->ourImages[o+e].bitmap);
+						nci.groupNumber = 14;
+						nci.imName = std::string();
+						flags4[q]->ourImages.push_back(nci);
+					}
+					o+=8;
+				}
+				if(flags4[q]->ourImages[o].groupNumber==3)
+				{
+					for(int e=0; e<8; ++e)
+					{
+						Cimage nci;
+						nci.bitmap = CSDL_Ext::rotate01(flags4[q]->ourImages[o+e].bitmap);
+						nci.groupNumber = 15;
+						nci.imName = std::string();
+						flags4[q]->ourImages.push_back(nci);
+					}
+					o+=8;
+				}
+			}
+		}
+		for(int ff=0; ff<(this->*pr.first)[q]->ourImages.size(); ++ff)
+		{
+			SDL_SetColorKey((this->*pr.first)[q]->ourImages[ff].bitmap, SDL_SRCCOLORKEY,
+				SDL_MapRGB((this->*pr.first)[q]->ourImages[ff].bitmap->format, 0, 255, 255)
+				);
+		}
+		(this->*pr.first)[q]->alphaTransformed = true;
+	}
+}
+
+void Graphics::loadHeroFlags()
+{
+	using namespace boost::assign;
+	timeHandler th;
+	std::vector<CDefHandler *> Graphics::*point;
+	std::pair<std::vector<CDefHandler *> Graphics::*, std::vector<const char *> > pr[4];
+	pr[0].first = &Graphics::flags1;
+	pr[0].second+=("ABF01L.DEF"),("ABF01G.DEF"),("ABF01R.DEF"),("ABF01D.DEF"),("ABF01B.DEF"),
+		("ABF01P.DEF"),("ABF01W.DEF"),("ABF01K.DEF");
+	pr[1].first = &Graphics::flags2;
+	pr[1].second+=("ABF02L.DEF"),("ABF02G.DEF"),("ABF02R.DEF"),("ABF02D.DEF"),("ABF02B.DEF"),
+		("ABF02P.DEF"),("ABF02W.DEF"),("ABF02K.DEF");
+	pr[2].first = &Graphics::flags3;
+	pr[2].second+=("ABF03L.DEF"),("ABF03G.DEF"),("ABF03R.DEF"),("ABF03D.DEF"),("ABF03B.DEF"),
+		("ABF03P.DEF"),("ABF03W.DEF"),("ABF03K.DEF");
+	pr[3].first = &Graphics::flags4;
+	pr[3].second+=("AF00.DEF"),("AF01.DEF"),("AF02.DEF"),("AF03.DEF"),("AF04.DEF"),
+		("AF05.DEF"),("AF06.DEF"),("AF07.DEF");
+	boost::thread_group grupa;
+	grupa.create_thread(boost::bind(&Graphics::loadHeroFlags,this,boost::ref(pr[3]),true));
+	grupa.create_thread(boost::bind(&Graphics::loadHeroFlags,this,boost::ref(pr[2]),false));
+	grupa.create_thread(boost::bind(&Graphics::loadHeroFlags,this,boost::ref(pr[1]),false));
+	grupa.create_thread(boost::bind(&Graphics::loadHeroFlags,this,boost::ref(pr[0]),false));
+	grupa.join_all();
+	std::cout << "Loading and transforming heroes' flags: "<<th.getDif()<<std::endl;
+}
+SDL_Surface * Graphics::getPic(int ID, bool fort, bool builded)
+{
+	if (ID==-1)
+		return smallIcons->ourImages[0].bitmap;
+	else if (ID==-2)
+		return smallIcons->ourImages[1].bitmap;
+	else if (ID==-3)
+		return smallIcons->ourImages[2+F_NUMBER*4].bitmap;
+	else if (ID>F_NUMBER || ID<-3)
+#ifndef __GNUC__
+		throw new std::exception("Invalid ID");
+#else
+		throw new std::exception();
+#endif
+	else
+	{
+		int pom = 3;
+		if(!fort)
+			pom+=F_NUMBER*2;
+		pom += ID*2;
+		if (!builded)
+			pom--;
+		return smallIcons->ourImages[pom].bitmap;
+	}
+}
+
+void Graphics::blueToPlayersAdv(SDL_Surface * sur, int player)
+{
+	if(player==1) //it is actually blue...
+		return;
+	if(sur->format->BitsPerPixel == 8)
+	{
+		for(int i=0; i<32; ++i)
+		{
+			sur->format->palette->colors[224+i] = playerColorPalette[32*player+i];
+		}
+	}
+	else if(sur->format->BitsPerPixel == 24) //should never happen in general
+	{
+		for(int y=0; y<sur->h; ++y)
+		{
+			for(int x=0; x<sur->w; ++x)
+			{
+				Uint8* cp = (Uint8*)sur->pixels + y*sur->pitch + x*3;
+				if(SDL_BYTEORDER == SDL_BIG_ENDIAN)
+				{
+					if(cp[2]>cp[1] && cp[2]>cp[0])
+					{
+						std::vector<long long int> sort1;
+						sort1.push_back(cp[0]);
+						sort1.push_back(cp[1]);
+						sort1.push_back(cp[2]);
+						std::vector< std::pair<long long int, Uint8*> > sort2;
+						sort2.push_back(std::make_pair(graphics->playerColors[player].r, &(cp[0])));
+						sort2.push_back(std::make_pair(graphics->playerColors[player].g, &(cp[1])));
+						sort2.push_back(std::make_pair(graphics->playerColors[player].b, &(cp[2])));
+						std::sort(sort1.begin(), sort1.end());
+						if(sort2[0].first>sort2[1].first)
+							std::swap(sort2[0], sort2[1]);
+						if(sort2[1].first>sort2[2].first)
+							std::swap(sort2[1], sort2[2]);
+						if(sort2[0].first>sort2[1].first)
+							std::swap(sort2[0], sort2[1]);
+						for(int hh=0; hh<3; ++hh)
+						{
+							(*sort2[hh].second) = (sort1[hh] + sort2[hh].first)/2.2;
+						}
+					}
+				}
+				else
+				{
+					if(
+						(/*(mode==0) && (cp[0]>cp[1]) && (cp[0]>cp[2])) ||
+						((mode==1) &&*/ (cp[2]<45) && (cp[0]>80) && (cp[1]<70) && ((cp[0]-cp[1])>40))
+					  )
+					{
+						std::vector<long long int> sort1;
+						sort1.push_back(cp[2]);
+						sort1.push_back(cp[1]);
+						sort1.push_back(cp[0]);
+						std::vector< std::pair<long long int, Uint8*> > sort2;
+						sort2.push_back(std::make_pair(graphics->playerColors[player].r, &(cp[2])));
+						sort2.push_back(std::make_pair(graphics->playerColors[player].g, &(cp[1])));
+						sort2.push_back(std::make_pair(graphics->playerColors[player].b, &(cp[0])));
+						std::sort(sort1.begin(), sort1.end());
+						if(sort2[0].first>sort2[1].first)
+							std::swap(sort2[0], sort2[1]);
+						if(sort2[1].first>sort2[2].first)
+							std::swap(sort2[1], sort2[2]);
+						if(sort2[0].first>sort2[1].first)
+							std::swap(sort2[0], sort2[1]);
+						for(int hh=0; hh<3; ++hh)
+						{
+							(*sort2[hh].second) = (sort1[hh]*0.8 + sort2[hh].first)/2;
+						}
+					}
+				}
+			}
+		}
+	}
+}

+ 53 - 0
client/Graphics.h

@@ -0,0 +1,53 @@
+#pragma once
+#include "../global.h"
+class CDefEssential;
+struct SDL_Surface;
+class CGHeroInstance;
+class CGTownInstance;
+class CDefHandler;
+class CHeroClass;
+struct SDL_Color;
+class Graphics
+{
+public:
+	//various graphics
+	SDL_Color * playerColors; //array [8]
+	SDL_Color * neutralColor;
+	SDL_Color * playerColorPalette; //palette to make interface colors good - array of size [256]
+	SDL_Surface * hInfo, *tInfo; //hero and town infobox bgs
+	std::vector<std::pair<int, int> > slotsPos; //creature slot positions in infoboxes
+	CDefEssential *luck22, *luck30, *luck42, *luck82,
+		*morale22, *morale30, *morale42, *morale82,
+		*halls, *forts, *bigTownPic;
+	std::map<int,SDL_Surface*> heroWins; //hero_ID => infobox
+	std::map<int,SDL_Surface*> townWins; //town_ID => infobox
+	CDefHandler * artDefs; //artifacts
+	std::vector<SDL_Surface *> portraitSmall; //48x32 px portraits of heroes
+	std::vector<SDL_Surface *> portraitLarge; //58x64 px portraits of heroes
+	std::vector<CDefHandler *> flags1, flags2, flags3, flags4; //flags blitted on heroes when ,
+	CDefHandler * pskillsb, *resources; //82x93
+	CDefHandler * un44; //many things
+	CDefHandler * smallIcons, *resources32; //resources 32x32
+	//creatures
+	std::map<int,SDL_Surface*> smallImgs; //creature ID -> small 32x32 img of creature; //ID=-2 is for blank (black) img; -1 for the border
+	std::map<int,SDL_Surface*> bigImgs; //creature ID -> big 58x64 img of creature; //ID=-2 is for blank (black) img; -1 for the border
+	std::map<int,SDL_Surface*> backgrounds; //castle ID -> 100x130 background creature image // -1 is for neutral
+	//for battles
+	std::vector< std::vector< std::string > > battleBacks; //battleBacks[terType] - vector of possible names for certain terrain type
+	std::vector< std::string > battleHeroes; //battleHeroes[hero type] - name of def that has hero animation for battle
+	//functions
+	Graphics();	
+	void initializeBattleGraphics();
+	void loadPaletteAndColors();
+	void loadHeroFlags();
+	void loadHeroFlags(std::pair<std::vector<CDefHandler *> Graphics::*, std::vector<const char *> > &pr, bool mode);
+	void loadHeroAnim(std::vector<CDefHandler **> & anims);
+	void loadHeroPortraits();
+	SDL_Surface * drawHeroInfoWin(const CGHeroInstance * curh);
+	SDL_Surface * drawPrimarySkill(const CGHeroInstance *curh, SDL_Surface *ret, int from=0, int to=PRIMARY_SKILLS);
+	SDL_Surface * drawTownInfoWin(const CGTownInstance * curh);
+	SDL_Surface * getPic(int ID, bool fort=true, bool builded=false); //returns small picture of town: ID=-1 - blank; -2 - border; -3 - random
+	void blueToPlayersAdv(SDL_Surface * sur, int player); //replaces blue interface colour with a color of player
+};
+
+extern Graphics * graphics;

+ 83 - 0
client/Makefile.am

@@ -0,0 +1,83 @@
+AUTOMAKE_OPTIONS=foreign
+bin_PROGRAMS = vcmiclient
+#vcmi_LDADD = $(BOOST_SYSTEM_LIB) $(BOOST_FILESYSTEM_LIB) $(BOOST_THREAD_LIB)
+#AM_CXXFLAGS = $(BOOST_CPPFLAGS)
+vcmiclient_LDADD = $(BOOST_SYSTEM_LIB) $(BOOST_FILESYSTEM_LIB) $(BOOST_THREAD_LIB)
+#vcmiclient_LDADD = $(BOOST_SYSTEM_LIB) $(BOOST_FILESYSTEM_LIB) $(BOOST_THREAD_LIB)
+vcmiclient_LDFLAGS = -L$(top_builddir)/lib
+vcmiclient_LDADD += -lvcmi
+vcmiclient_SOURCES =  \
+../AdventureMapButton.cpp \
+../hch/CAbilityHandler.cpp \
+../CAdvmapInterface.cpp \
+../CBattleInterface.cpp \
+./CBitmapHandler.cpp \
+../CCallback.cpp \
+../CCastleInterface.cpp \
+../CConsoleHandler.cpp \
+./CCreatureAnimation.cpp \
+../CCursorHandler.cpp \
+../hch/CDefHandler.cpp \
+../CGameInfo.cpp \
+../CGameInterface.cpp \
+../hch/CGeneralTextHandler.cpp \
+../CHeroWindow.cpp \
+./Client.cpp \
+../CLuaHandler.cpp \
+../CMessage.cpp \
+../CMT.cpp \
+../hch/CMusicHandler.cpp \
+../CPathfinder.cpp \
+../CPlayerInterface.cpp \
+../CPreGame.cpp \
+../hch/CPreGameTextHandler.cpp \
+../hch/CSndHandler.cpp \
+../hch/CSpellHandler.cpp \
+../CThreadHelper.cpp \
+./Graphics.cpp \
+../mapHandler.cpp \
+../SDL_Extensions.cpp \
+../SDL_framerate.cpp \
+../AdventureMapButton.h \
+../AI_Base.h \
+../hch/CAbilityHandler.h \
+../CAdvmapInterface.h \
+../hch/CAmbarCendamo.h \
+../hch/CArtHandler.h \
+../CBattleInterface.h \
+./CBitmapHandler.h \
+../hch/CBuildingHandler.h \
+../CCallback.h \
+../CCastleInterface.h \
+../CConsoleHandler.h \
+./CCreatureAnimation.h \
+../hch/CCreatureHandler.h \
+../CCursorHandler.h \
+../hch/CDefHandler.h \
+../CGameInfo.h \
+../CGameInterface.h \
+../hch/CGeneralTextHandler.h \
+../hch/CHeroHandler.h \
+../CHeroWindow.h \
+./Client.h \
+../CLuaHandler.h \
+../CMessage.h \
+../hch/CMusicHandler.h \
+../hch/CObjectHandler.h \
+../CPathfinder.h \
+../CPlayerInterface.h \
+../CPreGame.h \
+../hch/CPreGameTextHandler.h \
+../hch/CSndHandler.h \
+../hch/CSpellHandler.h \
+../CThreadHelper.h \
+../global.h \
+./Graphics.h \
+../int3.h \
+../map.h \
+../mapHandler.h \
+../nodrze.h \
+../SDL_framerate.h \
+../StartInfo.h \
+../stdafx.h \
+../timeHandler.h

+ 570 - 0
client/VCMI_client.vcproj

@@ -0,0 +1,570 @@
+<?xml version="1.0" encoding="windows-1250"?>
+<VisualStudioProject
+	ProjectType="Visual C++"
+	Version="9,00"
+	Name="VCMI_client"
+	ProjectGUID="{8355EBA8-65C2-44A4-BC2D-78053E1BF2D6}"
+	RootNamespace="VCMI_client"
+	TargetFrameworkVersion="196613"
+	>
+	<Platforms>
+		<Platform
+			Name="Win32"
+		/>
+	</Platforms>
+	<ToolFiles>
+	</ToolFiles>
+	<Configurations>
+		<Configuration
+			Name="Debug|Win32"
+			OutputDirectory="$(SolutionDir)"
+			IntermediateDirectory="$(ConfigurationName)"
+			ConfigurationType="1"
+			CharacterSet="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="0"
+				AdditionalIncludeDirectories="G:\vcmt\repa\include"
+				GeneratePreprocessedFile="0"
+				MinimalRebuild="true"
+				BasicRuntimeChecks="3"
+				RuntimeLibrary="3"
+				WarningLevel="1"
+				DebugInformationFormat="4"
+				DisableSpecificWarnings="4251"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="SDL.lib zdll.lib SDL_image.lib SDL_ttf.lib SDL_mixer.lib lua5.1.lib VCMI_lib.lib"
+				ShowProgress="0"
+				AdditionalLibraryDirectories="G:\vcmt\repa\libs"
+				GenerateDebugInformation="true"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="Release|Win32"
+			OutputDirectory="$(SolutionDir)$(ConfigurationName)"
+			IntermediateDirectory="$(ConfigurationName)"
+			ConfigurationType="1"
+			CharacterSet="1"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="3"
+				EnableIntrinsicFunctions="true"
+				FavorSizeOrSpeed="1"
+				OmitFramePointers="true"
+				EnableFiberSafeOptimizations="true"
+				WholeProgramOptimization="true"
+				AdditionalIncludeDirectories="G:\vcmt\repa\include"
+				StringPooling="true"
+				BasicRuntimeChecks="0"
+				RuntimeLibrary="2"
+				EnableFunctionLevelLinking="false"
+				EnableEnhancedInstructionSet="0"
+				WarningLevel="3"
+				DebugInformationFormat="0"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="SDL.lib zdll.lib SDL_image.lib SDL_ttf.lib SDL_mixer.lib lua5.1.lib VCMI_lib.lib"
+				AdditionalLibraryDirectories="G:\vcmt\repa\libs"
+				GenerateDebugInformation="false"
+				Driver="0"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				LinkTimeCodeGeneration="0"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+		<Configuration
+			Name="RD|Win32"
+			OutputDirectory="$(SolutionDir)$(ConfigurationName)"
+			IntermediateDirectory="$(ConfigurationName)"
+			ConfigurationType="1"
+			CharacterSet="1"
+			WholeProgramOptimization="1"
+			>
+			<Tool
+				Name="VCPreBuildEventTool"
+			/>
+			<Tool
+				Name="VCCustomBuildTool"
+			/>
+			<Tool
+				Name="VCXMLDataGeneratorTool"
+			/>
+			<Tool
+				Name="VCWebServiceProxyGeneratorTool"
+			/>
+			<Tool
+				Name="VCMIDLTool"
+			/>
+			<Tool
+				Name="VCCLCompilerTool"
+				Optimization="3"
+				EnableIntrinsicFunctions="true"
+				FavorSizeOrSpeed="1"
+				OmitFramePointers="true"
+				EnableFiberSafeOptimizations="true"
+				WholeProgramOptimization="true"
+				AdditionalIncludeDirectories="G:\vcmt\repa\include"
+				StringPooling="true"
+				BasicRuntimeChecks="0"
+				RuntimeLibrary="2"
+				EnableFunctionLevelLinking="false"
+				EnableEnhancedInstructionSet="0"
+				WarningLevel="3"
+				DebugInformationFormat="3"
+			/>
+			<Tool
+				Name="VCManagedResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCResourceCompilerTool"
+			/>
+			<Tool
+				Name="VCPreLinkEventTool"
+			/>
+			<Tool
+				Name="VCLinkerTool"
+				AdditionalDependencies="SDL.lib zdll.lib SDL_image.lib SDL_ttf.lib SDL_mixer.lib lua5.1.lib VCMI_lib.lib"
+				AdditionalLibraryDirectories="G:\vcmt\repa\libs"
+				GenerateDebugInformation="true"
+				Driver="0"
+				OptimizeReferences="2"
+				EnableCOMDATFolding="2"
+				LinkTimeCodeGeneration="0"
+				TargetMachine="1"
+			/>
+			<Tool
+				Name="VCALinkTool"
+			/>
+			<Tool
+				Name="VCManifestTool"
+			/>
+			<Tool
+				Name="VCXDCMakeTool"
+			/>
+			<Tool
+				Name="VCBscMakeTool"
+			/>
+			<Tool
+				Name="VCFxCopTool"
+			/>
+			<Tool
+				Name="VCAppVerifierTool"
+			/>
+			<Tool
+				Name="VCPostBuildEventTool"
+			/>
+		</Configuration>
+	</Configurations>
+	<References>
+	</References>
+	<Files>
+		<Filter
+			Name="Source Files"
+			Filter="cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx"
+			UniqueIdentifier="{4FC737F1-C7A5-4376-A066-2A32D752A2FF}"
+			>
+			<File
+				RelativePath="..\AdventureMapButton.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CAbilityHandler.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CAdvmapInterface.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CBattleInterface.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\CBitmapHandler.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CCallback.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CCastleInterface.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CConsoleHandler.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\CCreatureAnimation.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CCursorHandler.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CDefHandler.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CGameInfo.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CGameInterface.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CGeneralTextHandler.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CHeroWindow.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\Client.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CLuaHandler.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CMessage.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CMT.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CMusicHandler.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CPathfinder.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CPlayerInterface.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CPreGame.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CPreGameTextHandler.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CSndHandler.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CSpellHandler.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\CThreadHelper.cpp"
+				>
+			</File>
+			<File
+				RelativePath=".\Graphics.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\mapHandler.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\SDL_Extensions.cpp"
+				>
+			</File>
+			<File
+				RelativePath="..\SDL_framerate.cpp"
+				>
+			</File>
+		</Filter>
+		<Filter
+			Name="Header Files"
+			Filter="h;hpp;hxx;hm;inl;inc;xsd"
+			UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}"
+			>
+			<File
+				RelativePath="..\AdventureMapButton.h"
+				>
+			</File>
+			<File
+				RelativePath="..\AI_Base.h"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CAbilityHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CAdvmapInterface.h"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CAmbarCendamo.h"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CArtHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CBattleInterface.h"
+				>
+			</File>
+			<File
+				RelativePath=".\CBitmapHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CBuildingHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CCallback.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CCastleInterface.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CConsoleHandler.h"
+				>
+			</File>
+			<File
+				RelativePath=".\CCreatureAnimation.h"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CCreatureHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CCursorHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CDefHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CGameInfo.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CGameInterface.h"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CGeneralTextHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CHeroHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CHeroWindow.h"
+				>
+			</File>
+			<File
+				RelativePath=".\Client.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CLuaHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CMessage.h"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CMusicHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CObjectHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CPathfinder.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CPlayerInterface.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CPreGame.h"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CPreGameTextHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CSndHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\hch\CSpellHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\CThreadHelper.h"
+				>
+			</File>
+			<File
+				RelativePath="..\global.h"
+				>
+			</File>
+			<File
+				RelativePath=".\Graphics.h"
+				>
+			</File>
+			<File
+				RelativePath="..\int3.h"
+				>
+			</File>
+			<File
+				RelativePath="..\map.h"
+				>
+			</File>
+			<File
+				RelativePath="..\mapHandler.h"
+				>
+			</File>
+			<File
+				RelativePath="..\nodrze.h"
+				>
+			</File>
+			<File
+				RelativePath="..\SDL_framerate.h"
+				>
+			</File>
+			<File
+				RelativePath="..\StartInfo.h"
+				>
+			</File>
+			<File
+				RelativePath="..\stdafx.h"
+				>
+			</File>
+			<File
+				RelativePath="..\timeHandler.h"
+				>
+			</File>
+		</Filter>
+	</Files>
+	<Globals>
+	</Globals>
+</VisualStudioProject>

+ 3 - 0
config.h.in

@@ -54,6 +54,9 @@
 /* define if the Boost::System library is available */
 #undef HAVE_BOOST_SYSTEM
 
+/* define if the Boost::Thread library is available */
+#undef HAVE_BOOST_THREAD
+
 /* Define to 1 if you have the <fcntl.h> header file. */
 #undef HAVE_FCNTL_H
 

+ 2 - 1
configure.ac

@@ -11,6 +11,7 @@ AC_PROG_CXX
 AX_BOOST_BASE([1.33])
 AX_BOOST_SYSTEM
 AX_BOOST_FILESYSTEM
+AX_BOOST_THREAD
 AC_PROG_CC
 AC_PROG_CPP
 AC_PROG_RANLIB
@@ -74,4 +75,4 @@ AC_FUNC_SELECT_ARGTYPES
 AC_CHECK_FUNCS([lua_pushhstring lua_calchash],, AC_MSG_ERROR([Lua required fuctions not found]))
 AC_CHECK_FUNCS([atexit memset pow select sqrt])
 
-AC_OUTPUT(Makefile hch/Makefile)
+AC_OUTPUT(Makefile lib/Makefile client/Makefile server/Makefile)

+ 30 - 27
global.h

@@ -1,22 +1,30 @@
 #ifndef GLOBAL_H
 #define GLOBAL_H
+#include <iostream>
+#include <boost/logic/tribool.hpp>
+#include <boost/cstdint.hpp>
+typedef boost::uint32_t ui32;  //unsigned int 32 bits (4 bytes)
+typedef boost::uint16_t ui16; //unsigned int 16 bits (2 bytes)
+typedef boost::uint8_t ui8; //unsigned int 8 bits (1 byte)
+typedef boost::int32_t si32; //signed int 32 bits (4 bytes)
+typedef boost::int16_t si16; //signed int 16 bits (2 bytes)
+typedef boost::int8_t si8; //signed int 8 bits (1 byte)
+#include "int3.h"
 #define CHECKTIME 1
 #if CHECKTIME
 #include "timeHandler.h"
-#include <boost/logic/tribool.hpp>
-#include <iostream>
-#include "int3.h"
 #define THC
-#else
-#define THC //
 #endif
 
-#ifdef WIN32
+#define NAME_VER ("VCMI \"Altanatse\" 0.7")
+
+
+#ifdef _WIN32
 #define PATHSEPARATOR "\\"
-#define DATADIR ""
+#define DATA_DIR ""
 #else
 #define PATHSEPARATOR "/"
-#define DATADIR "/progdir/"
+#define DATA_DIR "/progdir/"
 #endif
 
 enum Ecolor {RED, BLUE, TAN, GREEN, ORANGE, PURPLE, TEAL, PINK}; //player's colors
@@ -30,31 +38,12 @@ enum ElossCon {lossCastle, lossHero, timeExpires, lossStandard=255};
 enum EHeroClasses {HERO_KNIGHT, HERO_CLERIC, HERO_RANGER, HERO_DRUID, HERO_ALCHEMIST, HERO_WIZARD,
 	HERO_DEMONIAC, HERO_HERETIC, HERO_DEATHKNIGHT, HERO_NECROMANCER, HERO_WARLOCK, HERO_OVERLORD,
 	HERO_BARBARIAN, HERO_BATTLEMAGE, HERO_BEASTMASTER, HERO_WITCH, HERO_PLANESWALKER, HERO_ELEMENTALIST};
-
-#ifdef _DEBUG
 class CGameInfo;
 extern CGameInfo* CGI;
-#else
-#define CGI (CGameInfo::mainObj)
-#endif
-#define CURPLINT (((CPlayerInterface*)((CGameInfo::mainObj)->playerint[(CGameInfo::mainObj)->state->currentPlayer])))
-#define LOCPLINT (((CPlayerInterface*)((CGameInfo::mainObj)->playerint[(CGameInfo::mainObj)->localPlayer])))
-//CURPLINT gives pointer to the interface of human player which is currently making turn,
-//LOCPLINT gives pointer to the interface which is currently showed (on this machine)
 
 #define HEROI_TYPE (0)
 #define TOWNI_TYPE (1)
 
-//#define LOGUJ
-
-#ifdef LOGUJ
-#define LOG(x) std::cout<<x;
-#define LOGE(x) std::cout<<x<<std::endl;
-#else
-#define LOG(x) ;
-#define LOGE(x) ;
-#endif
-
 const int F_NUMBER = 9; //factions (town types) quantity
 const int PLAYER_LIMIT = 8; //player limit per map
 const int HEROES_PER_TYPE=8; //amount of heroes of each type
@@ -62,6 +51,7 @@ const int SKILL_QUANTITY=28;
 const int SKILL_PER_HERO=8;
 const int ARTIFACTS_QUANTITY=171;
 const int HEROES_QUANTITY=156;
+const int SPELLS_QUANTITY=70;
 const int RESOURCE_QUANTITY=8;
 const int TERRAIN_TYPES=10;
 const int PRIMARY_SKILLS=4;
@@ -75,6 +65,19 @@ const int MAX_BUILDING_PER_TURN = 1;
 
 #define DEFBYPASS
 
+#ifdef _WIN32
+	#ifdef VCMI_DLL
+		#define DLL_EXPORT __declspec(dllexport)
+	#else
+		#define DLL_EXPORT __declspec(dllimport)
+	#endif
+#else
+	#if defined(__GNUC__) && __GNUC__ >= 4
+		#define DLL_EXPORT	__attribute__ ((visibility("default")))
+	#else
+		#define DLL_EXPORT
+	#endif
+#endif
 
 #define HANDLE_EXCEPTION  \
 	catch (const std::exception& e) {	\

+ 11 - 11
hch/CAbilityHandler.cpp

@@ -7,33 +7,33 @@
 
 void CAbilityHandler::loadAbilities()
 {
-	std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("SSTRAITS.TXT");
+	std::string buf = CGI->bitmaph->getTextFile("SSTRAITS.TXT");
 	int it=0;
 	std::string dump;
 	for(int i=0; i<2; ++i)
 	{
-		CGeneralTextHandler::loadToIt(dump,buf,it,3);
+		loadToIt(dump,buf,it,3);
 	}
 	for (int i=0; i<SKILL_QUANTITY; i++)
 	{
 		CAbility * nab = new CAbility; //new skill, that will be read
-		CGeneralTextHandler::loadToIt(nab->name,buf,it,4);
-		CGeneralTextHandler::loadToIt(nab->basicText,buf,it,4);
-		CGeneralTextHandler::loadToIt(nab->advText,buf,it,4);
-		CGeneralTextHandler::loadToIt(nab->expText,buf,it,3);
+		loadToIt(nab->name,buf,it,4);
+		loadToIt(nab->basicText,buf,it,4);
+		loadToIt(nab->advText,buf,it,4);
+		loadToIt(nab->expText,buf,it,3);
 		nab->idNumber = abilities.size();
 		abilities.push_back(nab);
 	}
-	abils32 = CGI->spriteh->giveDef("SECSK32.DEF");
-	abils44 = CGI->spriteh->giveDef("SECSKILL.DEF");
-	abils82 = CGI->spriteh->giveDef("SECSK82.DEF");
+	abils32 = CDefHandler::giveDef("SECSK32.DEF");
+	abils44 = CDefHandler::giveDef("SECSKILL.DEF");
+	abils82 = CDefHandler::giveDef("SECSK82.DEF");
 
-	buf = CGameInfo::mainObj->bitmaph->getTextFile("SKILLLEV.TXT");
+	buf = CGI->bitmaph->getTextFile("SKILLLEV.TXT");
 	it=0;
 	for(int i=0; i<6; ++i)
 	{
 		std::string buffo;
-		CGeneralTextHandler::loadToIt(buffo,buf,it,3);
+		loadToIt(buffo,buf,it,3);
 		levels.push_back(buffo);
 	}
 }

+ 43 - 2707
hch/CAmbarCendamo.cpp

@@ -1,2707 +1,43 @@
-#include "../stdafx.h"
-#include "CAmbarCendamo.h"
-#include "CSemiDefHandler.h"
-#include "../CGameInfo.h"
-#include "CObjectHandler.h"
-#include "CCastleHandler.h"
-#include "CTownHandler.h"
-#include "CDefObjInfoHandler.h"
-#include "../SDL_Extensions.h"
-#include "boost/filesystem.hpp"
-#include "../CGameState.h"
-#include "CLodHandler.h"
-#include <set>
-#include <iomanip>
-#include <sstream>
-#include "../CLua.h"
-
-int readInt(unsigned char * bufor, int bytCon)
-{
-	int ret=0;
-	int amp=1;
-	for (int i=0; i<bytCon; i++)
-	{
-		ret+=bufor[i]*amp;
-		amp*=256;
-	}
-	return ret;
-}
-unsigned int intPow(unsigned int a, unsigned int b)
-{
-	unsigned int ret=1;
-	for(int i=0; i<b; ++i)
-		ret*=a;
-	return ret;
-}
-unsigned char reverse(unsigned char arg)
-{
-	unsigned char ret = 0;
-	for (int i=0; i<8;i++)
-	{
-		if(((arg)&(1<<i))>>i)
-		{
-			ret |= (128>>i);
-		}
-	}
-	return ret;
-}
-CAmbarCendamo::CAmbarCendamo (unsigned char * map)
-{
-	bufor=map;
-}
-CAmbarCendamo::CAmbarCendamo (const char * tie)
-{
-	is = new std::ifstream();
-	is -> open(tie,std::ios::binary);
-	is->seekg(0,std::ios::end); // na koniec
-	andame = is->tellg();  // read length
-	is->seekg(0,std::ios::beg); // wracamy na poczatek
-	bufor = new unsigned char[andame]; // allocate memory
-	is->read((char*)bufor, andame); // read map file to buffer
-	is->close();
-	delete is;
-}
-CAmbarCendamo::~CAmbarCendamo ()
-{// free memory
-	for (int ii=0;ii<map.width;ii++)
-		delete map.terrain[ii] ;
-	delete map.terrain;
-	delete bufor;
-}
-void CAmbarCendamo::teceDef()
-{
-	//for (int i=0; i<map.defy.size(); i++)
-	//{
-	//	std::ofstream * of = new std::ofstream(map.defy[i].name.c_str());
-	//	for (int j=0;j<46;j++)
-	//	{
-	//		(*of) << map.defy[i].bytes[j]<<std::endl;
-	//	}
-	//	of->close();
-	//	delete of;
-	//}
-}
-std::set<int> convertBuildings(const std::set<int> h3m, int castleID)
-{
-	std::map<int,int> mapa;
-	std::set<int> ret;
-	std::ifstream b5("config/buildings5.txt");
-	while(!b5.eof())
-	{
-		int a, b;
-		b5 >> a >> b;
-		if(castleID==8 && b==17) //magic university ID 17 (h3m) => 21 (vcmi)
-			b=21;
-		mapa[a]=b;
-	}
-
-	for(std::set<int>::const_iterator i=h3m.begin();i!=h3m.end();i++)
-	{
-		if(mapa[*i]>=0)
-			ret.insert(mapa[*i]);
-		else if(mapa[*i]  >=  (-CREATURES_PER_TOWN)) // horde buildings
-		{
-			int level = (-mapa[*i]);
-			if(h3m.find(20+(level*3)) != h3m.end()) //upgraded creature horde building
-			{
-				if(((castleID==1) || (castleID==3)) && ((level==3) || (level==5)))
-					ret.insert(25);
-				else
-					ret.insert(19);
-			}
-			else
-			{
-				if(((castleID==1) || (castleID==3)) && ((level==3) || (level==5)))
-					ret.insert(24);
-				else
-					ret.insert(18);
-			}
-		}
-		else
-		{
-			std::cout<<"Conversion warning: unknown building "<<*i<<" in castle "<<castleID<<std::endl;
-		}
-	}
-
-	ret.insert(10); //village hall is always present
-	ret.insert(-1); //houses near v.hall / eyecandies
-	ret.insert(-2); //terrain eyecandy, if -1 is used
-
-	if(ret.find(11)!=ret.end())
-		ret.insert(27);
-	if(ret.find(12)!=ret.end())
-		ret.insert(28);
-	if(ret.find(13)!=ret.end())
-		ret.insert(29);
-
-	return ret;
-}
-void CAmbarCendamo::deh3m()
-{
-	THC timeHandler th;
-	th.getDif();
-	map.version = (Eformat)bufor[0]; //wersja mapy
-	map.areAnyPLayers = bufor[4]; //invalid on some maps
-	map.height = map.width = bufor[5]; // wymiary mapy
-	map.twoLevel = bufor[9]; //czy sa lochy
-	map.terrain = new TerrainTile*[map.width]; // allocate memory
-	for (int ii=0;ii<map.width;ii++)
-		map.terrain[ii] = new TerrainTile[map.height]; // allocate memory
-	if (map.twoLevel)
-	{
-		map.undergroungTerrain = new TerrainTile*[map.width]; // allocate memory
-		for (int ii=0;ii<map.width;ii++)
-			map.undergroungTerrain[ii] = new TerrainTile[map.height]; // allocate memory
-	}
-	int length = bufor[10]; //name length
-	int i=14, pom;
-	while (i-14<length)	//read name
-		map.name+=bufor[i++];
-	length = bufor[i] + bufor[i+1]*256; //description length
-	i+=4;
-	for (pom=0;pom<length;pom++)
-		map.description+=bufor[i++];
-	map.difficulty = bufor[i++]; // reading map difficulty
-	if(map.version != RoE)
-	{
-		map.levelLimit = bufor[i++]; // hero level limit
-	}
-	else
-	{
-		map.levelLimit = 0;
-	}
-	for (pom=0;pom<8;pom++)
-	{
-		map.players[pom].canHumanPlay = bufor[i++];
-		map.players[pom].canComputerPlay = bufor[i++];
-		if ((!(map.players[pom].canHumanPlay || map.players[pom].canComputerPlay)))
-		{
-			switch(map.version)
-			{
-			case SoD: case WoG:
-				i+=13;
-				break;
-			case AB:
-				i+=12;
-				break;
-			case RoE:
-				i+=6;
-				break;
-			}
-			continue;
-		}
-
-		map.players[pom].AITactic = bufor[i++];
-
-		if(map.version == SoD || map.version == WoG)
-			map.players[pom].p7= bufor[i++];
-
-		map.players[pom].allowedFactions = 0;
-		map.players[pom].allowedFactions += bufor[i++];
-		if(map.version != RoE)
-			map.players[pom].allowedFactions += (bufor[i++])*256;
-
-		map.players[pom].isFactionRandom = bufor[i++];
-		map.players[pom].hasMainTown = bufor[i++];
-		if (map.players[pom].hasMainTown)
-		{
-			if(map.version != RoE)
-			{
-				map.players[pom].generateHeroAtMainTown = bufor[i++];
-				map.players[pom].generateHero = bufor[i++];
-			}
-			else
-			{
-				map.players[pom].generateHeroAtMainTown = false;
-				map.players[pom].generateHero = false;
-			}
-
-			map.players[pom].posOfMainTown.x = bufor[i++];
-			map.players[pom].posOfMainTown.y = bufor[i++];
-			map.players[pom].posOfMainTown.z = bufor[i++];
-
-
-		}
-		map.players[pom].p8= bufor[i++];
-		map.players[pom].p9= bufor[i++];
-		if(map.players[pom].p9!=0xff)
-		{
-			map.players[pom].mainHeroPortrait = bufor[i++];
-			int nameLength = bufor[i++];
-			i+=3;
-			for (int pp=0;pp<nameLength;pp++)
-				map.players[pom].mainHeroName+=bufor[i++];
-		}
-
-		if(map.version != RoE)
-		{
-			i++; ////unknown byte
-			int heroCount = bufor[i++];
-			i+=3;
-			for (int pp=0;pp<heroCount;pp++)
-			{
-				SheroName vv;
-				vv.heroID=bufor[i++];
-				int hnl = bufor[i++];
-				i+=3;
-				for (int zz=0;zz<hnl;zz++)
-				{
-					vv.heroName+=bufor[i++];
-				}
-				map.players[pom].heroesNames.push_back(vv);
-			}
-		}
-	}
-	map.victoryCondition = (EvictoryConditions)bufor[i++];
-	if (map.victoryCondition != winStandard) //specific victory conditions
-	{
-		int nr;
-		switch (map.victoryCondition) //read victory conditions
-		{
-		case artifact:
-			{
-				map.vicConDetails = new VicCon0();
-				((VicCon0*)map.vicConDetails)->ArtifactID = bufor[i+2];
-				nr=(map.version==RoE ? 1 : 2);
-				break;
-			}
-		case gatherTroop:
-			{
-				map.vicConDetails = new VicCon1();
-				int temp1 = bufor[i+2];
-				int temp2 = bufor[i+3];
-				((VicCon1*)map.vicConDetails)->monsterID = bufor[i+2];
-				((VicCon1*)map.vicConDetails)->neededQuantity=readNormalNr(i+(map.version==RoE ? 3 : 4));
-				nr=(map.version==RoE ? 5 : 6);
-				break;
-			}
-		case gatherResource:
-			{
-				map.vicConDetails = new VicCon2();
-				((VicCon2*)map.vicConDetails)->resourceID = bufor[i+2];
-				((VicCon2*)map.vicConDetails)->neededQuantity=readNormalNr(i+3);
-				nr=5;
-				break;
-			}
-		case buildCity:
-			{
-				map.vicConDetails = new VicCon3();
-				((VicCon3*)map.vicConDetails)->posOfCity.x = bufor[i+2];
-				((VicCon3*)map.vicConDetails)->posOfCity.y = bufor[i+3];
-				((VicCon3*)map.vicConDetails)->posOfCity.z = bufor[i+4];
-				((VicCon3*)map.vicConDetails)->councilNeededLevel = bufor[i+5];
-				((VicCon3*)map.vicConDetails)->fortNeededLevel = bufor[i+6];
-				nr=5;
-				break;
-			}
-		case buildGrail:
-			{
-				map.vicConDetails = new VicCon4();
-				if (bufor[i+4]>2)
-					((VicCon4*)map.vicConDetails)->anyLocation = true;
-				else
-				{
-					((VicCon4*)map.vicConDetails)->whereBuildGrail.x = bufor[i+2];
-					((VicCon4*)map.vicConDetails)->whereBuildGrail.y = bufor[i+3];
-					((VicCon4*)map.vicConDetails)->whereBuildGrail.z = bufor[i+4];
-				}
-				nr=3;
-				break;
-			}
-		case beatHero:
-			{
-				map.vicConDetails = new VicCon5();
-				((VicCon5*)map.vicConDetails)->locationOfHero.x = bufor[i+2];
-				((VicCon5*)map.vicConDetails)->locationOfHero.y = bufor[i+3];
-				((VicCon5*)map.vicConDetails)->locationOfHero.z = bufor[i+4];
-				nr=3;
-				break;
-			}
-		case captureCity:
-			{
-				map.vicConDetails = new VicCon6();
-				((VicCon6*)map.vicConDetails)->locationOfTown.x = bufor[i+2];
-				((VicCon6*)map.vicConDetails)->locationOfTown.y = bufor[i+3];
-				((VicCon6*)map.vicConDetails)->locationOfTown.z = bufor[i+4];
-				nr=3;
-				break;
-			}
-		case beatMonster:
-			{
-				map.vicConDetails = new VicCon7();
-				((VicCon7*)map.vicConDetails)->locationOfMonster.x = bufor[i+2];
-				((VicCon7*)map.vicConDetails)->locationOfMonster.y = bufor[i+3];
-				((VicCon7*)map.vicConDetails)->locationOfMonster.z = bufor[i+4];
-				nr=3;
-				break;
-			}
-		case takeDwellings:
-			{
-				map.vicConDetails = new CspecificVictoryConidtions();
-				nr=0;
-				break;
-			}
-		case takeMines:
-			{
-				map.vicConDetails = new CspecificVictoryConidtions();
-				nr=0;
-				break;
-			}
-		case transportItem:
-			{
-				map.vicConDetails = new VicCona();
-				((VicCona*)map.vicConDetails)->artifactID =  bufor[i+2];
-				((VicCona*)map.vicConDetails)->destinationPlace.x = bufor[i+3];
-				((VicCona*)map.vicConDetails)->destinationPlace.y = bufor[i+4];
-				((VicCona*)map.vicConDetails)->destinationPlace.z = bufor[i+5];
-				nr=4;
-				break;
-			}
-		}
-		map.vicConDetails->allowNormalVictory = bufor[i++];
-		map.vicConDetails->appliesToAI = bufor[i++];
-		i+=nr;
-	}
-	map.lossCondition.typeOfLossCon = (ElossCon)bufor[i++];
-	switch (map.lossCondition.typeOfLossCon) //read loss conditions
-	{
-	case lossCastle:
-		  {
-			  map.lossCondition.castlePos.x=bufor[i++];
-			  map.lossCondition.castlePos.y=bufor[i++];
-			  map.lossCondition.castlePos.z=bufor[i++];
-			  break;
-		  }
-	case lossHero:
-		  {
-			  map.lossCondition.heroPos.x=bufor[i++];
-			  map.lossCondition.heroPos.y=bufor[i++];
-			  map.lossCondition.heroPos.z=bufor[i++];
-			  break;
-		  }
-	case timeExpires:
-		{
-			map.lossCondition.timeLimit = readNormalNr(i++,2);
-			i++;
-			 break;
-		}
-	}
-	map.howManyTeams=bufor[i++]; //read number of teams
-	if(map.howManyTeams>0) //read team numbers
-	{
-		for(int rr=0; rr<8; ++rr)
-		{
-			map.players[rr].team=bufor[i++];
-		}
-	}
-	//reading allowed heroes (20 bytes)
-	int ist;
-
-	ist=i; //starting i for loop
-	for(i; i<ist+ (map.version == RoE ? 16 : 20) ; ++i)
-	{
-		unsigned char c = bufor[i];
-		for(int yy=0; yy<8; ++yy)
-		{
-			if((i-ist)*8+yy < CGameInfo::mainObj->heroh->heroes.size())
-			{
-				if(c == (c|((unsigned char)intPow(2, yy))))
-					CGameInfo::mainObj->heroh->heroes[(i-ist)*8+yy]->isAllowed = true;
-				else
-					CGameInfo::mainObj->heroh->heroes[(i-ist)*8+yy]->isAllowed = false;
-			}
-		}
-	}
-	if(map.version>RoE) //probably reserved for further heroes
-		i+=4;
-	unsigned char disp = 0;
-	if(map.version>=SoD)
-	{
-		disp = bufor[i++];
-		map.disposedHeroes.resize(disp);
-		for(int g=0; g<disp; ++g)
-		{
-			map.disposedHeroes[g].ID = bufor[i++];
-			map.disposedHeroes[g].portrait = bufor[i++];
-			int lenbuf = readNormalNr(i); i+=4;
-			for (int zz=0; zz<lenbuf; zz++)
-				map.disposedHeroes[g].name+=bufor[i++];
-			int players = bufor[i++];
-			for(int zz=0;zz<8;zz++)
-			{
-				int por = (1<<zz);
-				if(players & por)
-					map.disposedHeroes[g].players[zz] = true;
-				else
-					map.disposedHeroes[g].players[zz] = false;
-			}
-		}
-	}
-	//allowed heroes have been read
-	unsigned char aaa1=bufor[i], aaa2=bufor[i+1], aaa3=bufor[i+2];
-	i+=31; //omitting 0s
-	//reading allowed artifacts //18 bytes
-	if(map.version!=RoE)
-	{
-		ist=i; //starting i for loop
-		for(i; i<ist+(map.version==AB ? 17 : 18); ++i)
-		{
-			unsigned char c = bufor[i];
-			for(int yy=0; yy<8; ++yy)
-			{
-				if((i-ist)*8+yy < CGameInfo::mainObj->arth->artifacts.size())
-				{
-					if(c != (c|((unsigned char)intPow(2, yy))))
-						CGameInfo::mainObj->arth->artifacts[(i-ist)*8+yy].isAllowed = true;
-					else
-						CGameInfo::mainObj->arth->artifacts[(i-ist)*8+yy].isAllowed = false;
-				}
-			}
-		}//allowed artifacts have been read
-	}
-
-	//reading allowed spells (9 bytes)
-	if(map.version>=SoD)
-	{
-		ist=i; //starting i for loop
-		for(i; i<ist+9; ++i)
-		{
-			unsigned char c = bufor[i];
-			for(int yy=0; yy<8; ++yy)
-			{
-				if((i-ist)*8+yy < CGameInfo::mainObj->spellh->spells.size())
-				{
-					if(c != (c|((unsigned char)intPow(2, yy))))
-						CGameInfo::mainObj->spellh->spells[(i-ist)*8+yy].isAllowed = true;
-					else
-						CGameInfo::mainObj->spellh->spells[(i-ist)*8+yy].isAllowed = false;
-				}
-			}
-		}
-		//allowed spells have been read
-		//allowed hero's abilities (4 bytes)
-		ist=i; //starting i for loop
-		for(i; i<ist+4; ++i)
-		{
-			unsigned char c = bufor[i];
-			for(int yy=0; yy<8; ++yy)
-			{
-				if((i-ist)*8+yy < CGameInfo::mainObj->abilh->abilities.size())
-				{
-					if(c != (c|((unsigned char)intPow(2, yy))))
-						CGameInfo::mainObj->abilh->abilities[(i-ist)*8+yy]->isAllowed = true;
-					else
-						CGameInfo::mainObj->abilh->abilities[(i-ist)*8+yy]->isAllowed = false;
-				}
-			}
-		}
-	}
-	//allowed hero's abilities have been read
-
-	THC std::cout<<"\tReading header: "<<th.getDif()<<std::endl;
-	int rumNr = readNormalNr(i,4);i+=4;
-	for (int it=0;it<rumNr;it++)
-	{
-		Rumor ourRumor;
-		int nameL = readNormalNr(i,4);i+=4; //read length of name of rumor
-		for (int zz=0; zz<nameL; zz++)
-			ourRumor.name+=bufor[i++];
-		nameL = readNormalNr(i,4);i+=4; //read length of rumor
-		for (int zz=0; zz<nameL; zz++)
-			ourRumor.text+=bufor[i++];
-		map.rumors.push_back(ourRumor); //add to our list
-	}
-	THC std::cout<<"\tReading rumors: "<<th.getDif()<<std::endl;
-	switch(map.version)
-	{
-	case WoG: case SoD:
-		{
-			for(int z=0;z<HEROES_QUANTITY;z++) //disposed heroes
-			{
-				int custom =  bufor[i++];
-				if(!custom)
-					continue;
-				CHeroObjInfo * spec = new CHeroObjInfo;
-				spec->type = CGI->heroh->heroes[z];
-				bool isExp = bufor[i]; ++i; //true if hore's experience is greater than 0
-				if(isExp)
-				{
-					spec->experience = readNormalNr(i); i+=4;
-				}
-				else
-				{
-					spec->experience = 0;
-				}
-				bool nonstandardAbilities = bufor[i]; ++i; //true if hero has specified abilities
-				if(nonstandardAbilities)
-				{
-					int howMany = readNormalNr(i); i+=4;
-					for(int yy=0; yy<howMany; ++yy)
-					{
-						spec->abilities.push_back(CGameInfo::mainObj->abilh->abilities[readNormalNr(i, 1)]); ++i;
-						spec->abilityLevels.push_back(readNormalNr(i, 1)); ++i;
-					}
-				}
-				bool artSet = bufor[i]; ++i; //true if artifact set is not default (hero has some artifacts)
-				int artmask = map.version == RoE ? 0xff : 0xffff;
-				int artidlen = map.version == RoE ? 1 : 2;
-				spec->artifWorn.resize(19);
-				if(artSet)
-				{
-					//head art //1
-					int id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[0] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[0] = NULL;
-					//shoulders art //2
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[1] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[1] = NULL;
-					//neck art //3
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[2] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[2] = NULL;
-					//right hand art //4
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[3] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[3] = NULL;
-					//left hand art //5
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[4] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[4] = NULL;
-					//torso art //6
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[5] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[5] = NULL;
-					//right hand ring //7
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[6] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[6] = NULL;
-					//left hand ring //8
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[7] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[7] = NULL;
-					//feet art //9
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[8] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[8] = NULL;
-					//misc1 art //10
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[9] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[9] = NULL;
-					//misc2 art //11
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[10] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[10] = NULL;
-					//misc3 art //12
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[11] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[11] = NULL;
-					//misc4 art //13
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[12] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[12] = NULL;
-					//machine1 art //14
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[13] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[13] = NULL;
-					//machine2 art //15
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[14] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[14] = NULL;
-					//machine3 art //16
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[15] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[15] = NULL;
-					//misc5 art //17
-					if(map.version>=SoD)
-					{
-						i+=2;
-						/*id = readNormalNr(i, artidlen); i+=artidlen;
-						if(id!=artmask)
-							spec->artMisc5 = &(CGameInfo::mainObj->arth->artifacts[id]);
-						else
-							spec->artMisc5 = NULL;*/
-					}
-					//spellbook
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[17] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[17] = NULL;
-					//19 //???what is that? gap in file or what? - it's probably fifth slot..
-					if(map.version>RoE)
-					{
-						id = readNormalNr(i, artidlen); i+=artidlen;
-						if(id!=artmask)
-							spec->artifWorn[18] = &(CGameInfo::mainObj->arth->artifacts[id]);
-						else
-							spec->artifWorn[18] = NULL;
-					}
-					else
-						i+=1;
-					//bag artifacts //20
-					int amount = readNormalNr(i, 2); i+=2; //number of artifacts in hero's bag
-					if(amount>0)
-					{
-						for(int ss=0; ss<amount; ++ss)
-						{
-							id = readNormalNr(i, artidlen); i+=artidlen;
-							if(id!=artmask)
-								spec->artifacts.push_back(&(CGameInfo::mainObj->arth->artifacts[id]));
-							else
-								spec->artifacts.push_back(NULL);
-						}
-					}
-				} //artifacts
-				else
-				{
-					spec->artifWorn[8] = NULL;
-					spec->artifWorn[0] = NULL;
-					spec->artifWorn[4] = NULL;
-					spec->artifWorn[7] = NULL;
-					spec->artifWorn[13] = NULL;
-					spec->artifWorn[14] = NULL;
-					spec->artifWorn[15] = NULL;
-					spec->artifWorn[16] = NULL;
-					spec->artifWorn[9] = NULL;
-					spec->artifWorn[10] = NULL;
-					spec->artifWorn[11] = NULL;
-					spec->artifWorn[12] = NULL;
-					spec->artifWorn[18] = NULL;
-					spec->artifWorn[2] = NULL;
-					spec->artifWorn[3] = NULL;
-					spec->artifWorn[6] = NULL;
-					spec->artifWorn[1] = NULL;
-					spec->artifWorn[17] = NULL;
-					spec->artifWorn[5] = NULL;
-				}
-				for(int t=spec->artifacts.size(); t<10; ++t) //it does make sense, even it is not obvious ;]
-					spec->artifacts.push_back(NULL);
-				int customBio = bufor[i++];
-				if(customBio)
-				{
-					int length = readNormalNr(i); i+=4;
-					for (int zz=0; zz<length; zz++)
-						spec->biography+=bufor[i++];
-				}
-				int sex =   bufor[i++]; // 0xFF is default, 00 male, 01 female
-				bool areSpells = bufor[i]; ++i;
-				if(areSpells) //TODO: sprawdziæ //seems to be ok - tow
-				{
-					int ist = i;
-					for(i; i<ist+9; ++i)
-					{
-						unsigned char c = bufor[i];
-						for(int yy=0; yy<8; ++yy)
-						{
-							if((i-ist)*8+yy < CGameInfo::mainObj->spellh->spells.size())
-							{
-								if(c == (c|((unsigned char)intPow(2, yy))))
-									spec->spells.push_back(&(CGameInfo::mainObj->spellh->spells[(i-ist)*8+yy]));
-							}
-						}
-					}
-				}
-				int customPrimSkills = bufor[i++];
-				if(customPrimSkills)
-				{
-					spec->attack = bufor[i++];
-					spec->defence = bufor[i++];
-					spec->power = bufor[i++];
-					spec->knowledge = bufor[i++];
-				}
-				else
-				{
-					spec->attack = -1;
-					spec->defence = -1;
-					spec->power = -1;
-					spec->knowledge = -1;
-				}
-				map.predefinedHeroes.push_back(spec);
-			}
-			break;
-		}
-	case RoE:
-		i+=0;
-		break;
-	}
-	for (int c=0; c<map.width; c++) // reading terrain
-	{
-		for (int z=0; z<map.height; z++)
-		{
-			map.terrain[z][c].tertype = (EterrainType)(bufor[i++]);
-			map.terrain[z][c].terview = bufor[i++];
-			map.terrain[z][c].nuine = (Eriver)bufor[i++];
-			map.terrain[z][c].rivDir = bufor[i++];
-			map.terrain[z][c].malle = (Eroad)bufor[i++];
-			map.terrain[z][c].roadDir = bufor[i++];
-			map.terrain[z][c].siodmyTajemniczyBajt = bufor[i++];
-		}
-	}
-	if (map.twoLevel) // read underground terrain
-	{
-		for (int c=0; c<map.width; c++) // reading terrain
-		{
-			for (int z=0; z<map.height; z++)
-			{
-				map.undergroungTerrain[z][c].tertype = (EterrainType)(bufor[i++]);
-				map.undergroungTerrain[z][c].terview = bufor[i++];
-				map.undergroungTerrain[z][c].nuine = (Eriver)bufor[i++];
-				map.undergroungTerrain[z][c].rivDir = bufor[i++];
-				map.undergroungTerrain[z][c].malle = (Eroad)bufor[i++];
-				map.undergroungTerrain[z][c].roadDir = bufor[i++];
-				map.undergroungTerrain[z][c].siodmyTajemniczyBajt = bufor[i++];
-			}
-		}
-	}
-	THC std::cout<<"\tReading terrain: "<<th.getDif()<<std::endl;
-	int defAmount = bufor[i]; // liczba defow
-	defAmount = readNormalNr(i);
-	i+=4;
-
-	std::vector<std::string> defsToUnpack;
-	for (int idd = 0 ; idd<defAmount; idd++) // reading defs
-	{
-		int nameLength = readNormalNr(i,4);i+=4;
-		CGDefInfo * vinya = new CGDefInfo(); // info about new def
-		for (int cd=0;cd<nameLength;cd++)
-		{
-			vinya->name += bufor[i++];
-		}
-		//for (int v=0; v<42; v++) // read info
-		//{
-		//	vinya->bytes[v] = bufor[i++];
-		//}
-		std::transform(vinya->name.begin(),vinya->name.end(),vinya->name.begin(),(int(*)(int))toupper);
-		unsigned char bytes[12];
-		for (int v=0; v<12; v++) // read info
-		{
-			bytes[v] = bufor[i++];
-		}
-		vinya->terrainAllowed = readNormalNr(i,2);i+=2;
-		vinya->terrainMenu = readNormalNr(i,2);i+=2;
-		vinya->id = readNormalNr(i,4);i+=4;
-		vinya->subid = readNormalNr(i,4);i+=4;
-		vinya->type = bufor[i++];
-		vinya->printPriority = bufor[i++];
-		for (int zi=0; zi<6; zi++)
-		{
-			vinya->blockMap[zi] = reverse(bytes[zi]);
-		}
-		for (int zi=0; zi<6; zi++)
-		{
-			vinya->visitMap[zi] = reverse(bytes[6+zi]);
-		}
-		i+=16;
-		map.defy.push_back(vinya); // add this def to the vector
-		defsToUnpack.push_back(vinya->name);
-	}
-	THC std::cout<<"\tReading defs: "<<th.getDif()<<std::endl;
-	////loading objects
-	int howManyObjs = readNormalNr(i, 4); i+=4;
-	for(int ww=0; ww<howManyObjs; ++ww) //comment this line to turn loading objects off
-	{
-		//std::cout << "object nr "<<ww<<"\ti= "<<i<<std::endl;
-		CGObjectInstance * nobj = new CGObjectInstance(); //we will read this object
-		nobj->id = CGameInfo::mainObj->objh->objInstances.size();
-		nobj->pos.x = bufor[i++];
-		nobj->pos.y = bufor[i++];
-		nobj->pos.z = bufor[i++];
-
-		int tempd = readNormalNr(i, 4); i+=4;
-		nobj->defInfo = map.defy[tempd];
-		nobj->ID = nobj->defInfo->id;
-		nobj->subID = nobj->defInfo->subid;
-		//nobj->defInfo = readNormalNr(i, 4); i+=4;
-		//nobj->isHero = false;
-		//nobj->moveDir = 0;
-		//nobj->isStanding = true;
-		//nobj->state->owner = 254; //a lot of objs will never have an owner
-
-		//if (((nobj.x==0)&&(nobj.y==0)) || nobj.x>map.width || nobj.y>map.height || nobj.z>1 || nobj.defNumber>map.defy.size())
-		//	std::cout << "Alarm!!! Obiekt "<<ww<<" jest kopniety (lub wystaje poza mape)\n";
-
-		i+=5;
-		unsigned char buff [30];
-		for(int ccc=0; ccc<30; ++ccc)
-		{
-			buff[ccc] = bufor[i+ccc];
-		}
-		EDefType uu = getDefType(nobj->defInfo);
-		int j = nobj->defInfo->id;
-		int p = 99;
-		switch(uu)
-		{
-		case EVENTOBJ_DEF: //for event - objects
-			{
-				CEventObjInfo * spec = new CEventObjInfo;
-				bool guardMess;
-				guardMess = bufor[i]; ++i;
-				if(guardMess)
-				{
-					int messLong = readNormalNr(i, 4); i+=4;
-					if(messLong>0)
-					{
-						spec->isMessage = true;
-						for(int yy=0; yy<messLong; ++yy)
-						{
-							spec->message +=bufor[i+yy];
-						}
-						i+=messLong;
-					}
-					spec->areGuarders = bufor[i]; ++i;
-					if(spec->areGuarders)
-					{
-						spec->guarders = readCreatureSet(i); i+=( map.version == RoE ? 21 : 28);
-					}
-					i+=4;
-				}
-				else
-				{
-					spec->isMessage = false;
-					spec->areGuarders = false;
-					spec->message = std::string("");
-				}
-				spec->gainedExp = readNormalNr(i, 4); i+=4;
-				spec->manaDiff = readNormalNr(i, 4); i+=4;
-				spec->moraleDiff = readNormalNr(i, 1, true); ++i;
-				spec->luckDiff = readNormalNr(i, 1, true); ++i;
-				spec->wood = readNormalNr(i); i+=4;
-				spec->mercury = readNormalNr(i); i+=4;
-				spec->ore = readNormalNr(i); i+=4;
-				spec->sulfur = readNormalNr(i); i+=4;
-				spec->crystal = readNormalNr(i); i+=4;
-				spec->gems = readNormalNr(i); i+=4;
-				spec->gold = readNormalNr(i); i+=4;
-				spec->attack = readNormalNr(i, 1); ++i;
-				spec->defence = readNormalNr(i, 1); ++i;
-				spec->power = readNormalNr(i, 1); ++i;
-				spec->knowledge = readNormalNr(i, 1); ++i;
-				int gabn; //number of gained abilities
-				gabn = readNormalNr(i, 1); ++i;
-				for(int oo = 0; oo<gabn; ++oo)
-				{
-					spec->abilities.push_back((CGameInfo::mainObj->abilh)->abilities[readNormalNr(i, 1)]); ++i;
-					spec->abilityLevels.push_back(readNormalNr(i, 1)); ++i;
-				}
-				int gart = readNormalNr(i, 1); ++i; //number of gained artifacts
-				for(int oo = 0; oo<gart; ++oo)
-				{
-					spec->artifacts.push_back(&(CGameInfo::mainObj->arth->artifacts[readNormalNr(i, (map.version == RoE ? 1 : 2))])); i+=(map.version == RoE ? 1 : 2);
-				}
-				int gspel = readNormalNr(i, 1); ++i; //number of gained spells
-				for(int oo = 0; oo<gspel; ++oo)
-				{
-					spec->spells.push_back(&(CGameInfo::mainObj->spellh->spells[readNormalNr(i, 1)])); ++i;
-				}
-				int gcre = readNormalNr(i, 1); ++i; //number of gained creatures
-				spec->creatures = readCreatureSet(i, gcre); i+=3*gcre;
-				if(map.version>RoE)
-					i+=gcre;
-				i+=8;
-				spec->availableFor = readNormalNr(i, 1); ++i;
-				spec->computerActivate = readNormalNr(i, 1); ++i;
-				spec->humanActivate = readNormalNr(i, 1); ++i;
-				i+=4;
-				nobj->info = spec;
-				break;
-			}
-		case HERO_DEF:
-			{
-				CHeroObjInfo * spec = new CHeroObjInfo;
-				if(map.version>RoE)
-				{
-					spec->bytes[0] = bufor[i]; ++i;
-					spec->bytes[1] = bufor[i]; ++i;
-					spec->bytes[2] = bufor[i]; ++i;
-					spec->bytes[3] = bufor[i]; ++i;
-				}
-				spec->player = bufor[i]; ++i;
-				int typeBuf = readNormalNr(i, 1); ++i;
-				if(typeBuf==0xff)
-					spec->type = NULL;
-				else
-					spec->type = CGameInfo::mainObj->heroh->heroes[typeBuf];
-				bool isName = bufor[i]; ++i; //true if hero has nonstandard name
-				if(isName)
-				{
-					int length = readNormalNr(i, 4); i+=4;
-					for(int gg=0; gg<length; ++gg)
-					{
-						spec->name+=bufor[i]; ++i;
-					}
-				}
-				else
-					spec->name = std::string("");
-				if(map.version>AB)
-				{
-					bool isExp = bufor[i]; ++i; //true if hore's experience is greater than 0
-					if(isExp)
-					{
-						spec->experience = readNormalNr(i); i+=4;
-					}
-					else
-						spec->experience = 0;
-				}
-				else
-				{
-					spec->experience = readNormalNr(i); i+=4;
-				}
-				bool portrait=bufor[i]; ++i;
-				if (portrait)
-					i++; //TODO read portrait nr, save, open
-				bool nonstandardAbilities = bufor[i]; ++i; //true if hero has specified abilities
-				if(nonstandardAbilities)
-				{
-					int howMany = readNormalNr(i); i+=4;
-					for(int yy=0; yy<howMany; ++yy)
-					{
-						spec->abilities.push_back(CGameInfo::mainObj->abilh->abilities[readNormalNr(i, 1)]); ++i;
-						spec->abilityLevels.push_back(readNormalNr(i, 1)); ++i;
-					}
-				}
-				bool standGarrison = bufor[i]; ++i; //true if hero has nonstandard garrison
-				spec->standardGarrison = standGarrison;
-				if(standGarrison)
-				{
-					spec->garrison = readCreatureSet(i); i+= (map.version == RoE ? 21 : 28); //4 bytes per slot
-				}
-				bool form = bufor[i]; ++i; //formation
-				spec->garrison.formation = form;
-				bool artSet = bufor[i]; ++i; //true if artifact set is not default (hero has some artifacts)
-				int artmask = map.version == RoE ? 0xff : 0xffff;
-				int artidlen = map.version == RoE ? 1 : 2;
-				spec->artifWorn.resize(19);
-				if(artSet)
-				{
-					//head art //1
-					int id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[0] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[0] = NULL;
-					//shoulders art //2
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[1] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[1] = NULL;
-					//neck art //3
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[2] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[2] = NULL;
-					//right hand art //4
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[3] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[3] = NULL;
-					//left hand art //5
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[4] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[4] = NULL;
-					//torso art //6
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[5] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[5] = NULL;
-					//right hand ring //7
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[6] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[6] = NULL;
-					//left hand ring //8
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[7] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[7] = NULL;
-					//feet art //9
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[8] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[8] = NULL;
-					//misc1 art //10
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[9] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[9] = NULL;
-					//misc2 art //11
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[10] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[10] = NULL;
-					//misc3 art //12
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[11] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[11] = NULL;
-					//misc4 art //13
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[12] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[12] = NULL;
-					//machine1 art //14
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[13] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[13] = NULL;
-					//machine2 art //15
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[14] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[14] = NULL;
-					//machine3 art //16
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[15] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[15] = NULL;
-					//misc5 art //17
-					if(map.version>=SoD)
-					{
-						i+=2;
-						/*id = readNormalNr(i, artidlen); i+=artidlen;
-						if(id!=artmask)
-							spec->artMisc5 = &(CGameInfo::mainObj->arth->artifacts[id]);
-						else
-							spec->artMisc5 = NULL;*/
-					}
-					//spellbook
-					id = readNormalNr(i, artidlen); i+=artidlen;
-					if(id!=artmask)
-						spec->artifWorn[17] = &(CGameInfo::mainObj->arth->artifacts[id]);
-					else
-						spec->artifWorn[17] = NULL;
-					//19 //???what is that? gap in file or what? - it's probably fifth slot..
-					if(map.version>RoE)
-					{
-						id = readNormalNr(i, artidlen); i+=artidlen;
-						if(id!=artmask)
-							spec->artifWorn[18] = &(CGameInfo::mainObj->arth->artifacts[id]);
-						else
-							spec->artifWorn[18] = NULL;
-					}
-					else
-						i+=1;
-					//bag artifacts //20
-					int amount = readNormalNr(i, 2); i+=2; //number of artifacts in hero's bag
-					if(amount>0)
-					{
-						for(int ss=0; ss<amount; ++ss)
-						{
-							id = readNormalNr(i, artidlen); i+=artidlen;
-							if(id!=artmask)
-								spec->artifacts.push_back(&(CGameInfo::mainObj->arth->artifacts[id]));
-							else
-								spec->artifacts.push_back(NULL);
-						}
-					}
-				} //artifacts
-				else
-				{
-					spec->artifWorn[8] = NULL;
-					spec->artifWorn[0] = NULL;
-					spec->artifWorn[4] = NULL;
-					spec->artifWorn[7] = NULL;
-					spec->artifWorn[13] = NULL;
-					spec->artifWorn[14] = NULL;
-					spec->artifWorn[15] = NULL;
-					spec->artifWorn[16] = NULL;
-					spec->artifWorn[9] = NULL;
-					spec->artifWorn[10] = NULL;
-					spec->artifWorn[11] = NULL;
-					spec->artifWorn[12] = NULL;
-					spec->artifWorn[18] = NULL;
-					spec->artifWorn[2] = NULL;
-					spec->artifWorn[3] = NULL;
-					spec->artifWorn[6] = NULL;
-					spec->artifWorn[1] = NULL;
-					spec->artifWorn[17] = NULL;
-					spec->artifWorn[5] = NULL;
-				}
-				for(int t=spec->artifacts.size(); t<10; ++t) //it does make sense, even it is not obvious ;]
-					spec->artifacts.push_back(NULL);
-
-				spec->guardRange = readNormalNr(i, 1); ++i;
-				if(spec->guardRange == 0xff)
-					spec->isGuarding = false;
-				else
-					spec->isGuarding = true;
-				if(map.version>RoE)
-				{
-					bool hasBiography = bufor[i]; ++i; //true if hero has nonstandard (mapmaker defined) biography
-					if(hasBiography)
-					{
-						int length = readNormalNr(i); i+=4;
-						int iStart = i;
-						i+=length;
-						for(int bb=0; bb<length; ++bb)
-						{
-							spec->biography+=bufor[iStart+bb];
-						}
-					}
-					spec->sex = !(bufor[i]); ++i;
-				}
-				//spells
-				if(map.version>AB)
-				{
-					bool areSpells = bufor[i]; ++i;
-
-					if(areSpells) //TODO: sprawdziæ //seems to be ok - tow
-					{
-						int ist = i;
-						for(i; i<ist+9; ++i)
-						{
-							unsigned char c = bufor[i];
-							for(int yy=0; yy<8; ++yy)
-							{
-								if((i-ist)*8+yy < CGameInfo::mainObj->spellh->spells.size())
-								{
-									if(c == (c|((unsigned char)intPow(2, yy))))
-										spec->spells.push_back(&(CGameInfo::mainObj->spellh->spells[(i-ist)*8+yy]));
-								}
-							}
-						}
-					}
-				}
-				else if(map.version==AB) //we can read one spell
-				{
-					unsigned char buff = bufor[i]; ++i;
-					if(buff!=254)
-					{
-						spec->spells.push_back(&(CGameInfo::mainObj->spellh->spells[buff]));
-					}
-				}
-				//spells loaded
-				if(map.version>AB)
-				{
-					spec->defaultMainStats = bufor[i]; ++i;
-					if(spec->defaultMainStats)
-					{
-						spec->attack = bufor[i]; ++i;
-						spec->defence = bufor[i]; ++i;
-						spec->power = bufor[i]; ++i;
-						spec->knowledge = bufor[i]; ++i;
-					}
-					else
-					{
-						spec->attack = -1;
-						spec->defence = -1;
-						spec->power = -1;
-						spec->knowledge = -1;
-					}
-				}
-				else
-				{
-					spec->attack = -1;
-					spec->defence = -1;
-					spec->power = -1;
-					spec->knowledge = -1;
-				}
-				i+=16;
-				nobj->info = spec;
-				//////creating CHeroInstance
-				CGHeroInstance * nhi = new CGHeroInstance;
-				(*(static_cast<CGObjectInstance*>(nhi))) = *nobj;
-				delete nobj;
-				nobj=nhi;
-				spec->myInstance = nhi;
-				//nobj->isHero = true;
-				(static_cast<CGHeroInstance*>(nobj))->moveDir = 4;
-				nhi->isStanding = true;
-				nhi->exp = spec->experience;
-				nhi->level = CGI->heroh->level(nhi->exp);
-				nhi->primSkills.resize(PRIMARY_SKILLS);
-				nhi->artifWorn.resize(19);
-				nhi->primSkills[0] = spec->attack;
-				nhi->primSkills[1] = spec->defence;
-				nhi->primSkills[2] = spec->power;
-				nhi->primSkills[3] = spec->knowledge;
-				nhi->mana = spec->knowledge * 10;
-				nhi->movement = -1;
-				nhi->name = spec->name;
-				nhi->setOwner(spec->player);
-				nhi->pos = nobj->pos;
-				nhi->type = spec->type;
-				nhi->army = spec->garrison;
-				nhi->portrait = nobj->subID; // TODO: przypisywac portret
-				nhi->artifWorn[8] = spec->artifWorn[8];
-				nhi->artifWorn[0] = spec->artifWorn[0];
-				nhi->artifacts = spec->artifacts;
-				nhi->artifWorn[4] = spec->artifWorn[4];
-				nhi->artifWorn[7] = spec->artifWorn[7];
-				nhi->artifWorn[13] = spec->artifWorn[13];
-				nhi->artifWorn[14] = spec->artifWorn[14];
-				nhi->artifWorn[15] = spec->artifWorn[15];
-				nhi->artifWorn[16] = spec->artifWorn[16] = new CArtifact(CGI->arth->artifacts[3]);
-				nhi->artifWorn[9] = spec->artifWorn[9];
-				nhi->artifWorn[10] = spec->artifWorn[10];
-				nhi->artifWorn[11] = spec->artifWorn[11];
-				nhi->artifWorn[12] = spec->artifWorn[12];
-				nhi->artifWorn[18] = spec->artifWorn[18];
-				nhi->artifWorn[2] = spec->artifWorn[2];
-				nhi->artifWorn[3] = spec->artifWorn[3];
-				nhi->artifWorn[6] = spec->artifWorn[6];
-				nhi->artifWorn[1] = spec->artifWorn[1];
-				nhi->artifWorn[17] = spec->artifWorn[17];
-				nhi->artifWorn[5] = spec->artifWorn[5];
-				for(int qq=0; qq<spec->abilities.size(); ++qq)
-				{
-					nhi->secSkills.push_back(std::make_pair(spec->abilities[qq]->idNumber, spec->abilityLevels[qq]-1));
-				}
-				if(nhi->ID==34)
-					CGI->heroh->heroInstances.push_back(nhi);
-				else
-					CGI->objh->objInstances.push_back(nhi);
-
-				break;
-			}
-		case CREATURES_DEF:
-			{
-				CCreatureObjInfo * spec = new CCreatureObjInfo;
-				if(map.version>RoE)
-				{
-					spec->bytes[0] = bufor[i]; ++i;
-					spec->bytes[1] = bufor[i]; ++i;
-					spec->bytes[2] = bufor[i]; ++i;
-					spec->bytes[3] = bufor[i]; ++i;
-				}
-				spec->number = readNormalNr(i, 2); i+=2;
-				spec->character = bufor[i]; ++i;
-				bool isMesTre = bufor[i]; ++i; //true if there is message or treasury
-				if(isMesTre)
-				{
-					int messLength = readNormalNr(i); i+=4;
-					if(messLength>0)
-					{
-						for(int tt=0; tt<messLength; ++tt)
-						{
-							spec->message += bufor[i]; ++i;
-						}
-					}
-					spec->wood = readNormalNr(i); i+=4;
-					spec->mercury = readNormalNr(i); i+=4;
-					spec->ore = readNormalNr(i); i+=4;
-					spec->sulfur = readNormalNr(i); i+=4;
-					spec->crytal = readNormalNr(i); i+=4;
-					spec->gems = readNormalNr(i); i+=4;
-					spec->gold = readNormalNr(i); i+=4;
-					int artID = readNormalNr(i, (map.version == RoE ? 1 : 2)); i+=(map.version == RoE ? 1 : 2);
-					if(map.version==RoE)
-					{
-						if(artID!=0xff)
-							spec->gainedArtifact = &(CGameInfo::mainObj->arth->artifacts[artID]);
-						else
-							spec->gainedArtifact = NULL;
-					}
-					else
-					{
-						if(artID!=0xffff)
-							spec->gainedArtifact = &(CGameInfo::mainObj->arth->artifacts[artID]);
-						else
-							spec->gainedArtifact = NULL;
-					}
-				}
-				spec->neverFlees = bufor[i]; ++i;
-				spec->notGrowingTeam = bufor[i]; ++i;
-				i+=2;
-				nobj->info = spec;
-				break;
-			}
-		case SIGN_DEF:
-			{
-				CSignObjInfo * spec = new CSignObjInfo;
-				int length = readNormalNr(i); i+=4;
-				for(int rr=0; rr<length; ++rr)
-				{
-					spec->message += bufor[i]; ++i;
-				}
-				i+=4;
-				nobj->info = spec;
-				break;
-			}
-		case SEERHUT_DEF:
-			{
-				CSeerHutObjInfo * spec = new CSeerHutObjInfo;
-				if(map.version>RoE)
-				{
-					spec->missionType = bufor[i]; ++i;
-					switch(spec->missionType)
-					{
-					case 0:
-						i+=3;
-						continue;
-					case 1:
-						{
-							spec->m1level = readNormalNr(i); i+=4;
-							int limit = readNormalNr(i); i+=4;
-							if(limit == ((int)0xffffffff))
-							{
-								spec->isDayLimit = false;
-								spec->lastDay = -1;
-							}
-							else
-							{
-								spec->isDayLimit = true;
-								spec->lastDay = limit;
-							}
-							break;
-						}
-					case 2:
-						{
-							spec->m2attack = bufor[i]; ++i;
-							spec->m2defence = bufor[i]; ++i;
-							spec->m2power = bufor[i]; ++i;
-							spec->m2knowledge = bufor[i]; ++i;
-							int limit = readNormalNr(i); i+=4;
-							if(limit == ((int)0xffffffff))
-							{
-								spec->isDayLimit = false;
-								spec->lastDay = -1;
-							}
-							else
-							{
-								spec->isDayLimit = true;
-								spec->lastDay = limit;
-							}
-							break;
-						}
-					case 3:
-						{
-							spec->m3bytes[0] = bufor[i]; ++i;
-							spec->m3bytes[1] = bufor[i]; ++i;
-							spec->m3bytes[2] = bufor[i]; ++i;
-							spec->m3bytes[3] = bufor[i]; ++i;
-							int limit = readNormalNr(i); i+=4;
-							if(limit == ((int)0xffffffff))
-							{
-								spec->isDayLimit = false;
-								spec->lastDay = -1;
-							}
-							else
-							{
-								spec->isDayLimit = true;
-								spec->lastDay = limit;
-							}
-							break;
-						}
-					case 4:
-						{
-							spec->m4bytes[0] = bufor[i]; ++i;
-							spec->m4bytes[1] = bufor[i]; ++i;
-							spec->m4bytes[2] = bufor[i]; ++i;
-							spec->m4bytes[3] = bufor[i]; ++i;
-							int limit = readNormalNr(i); i+=4;
-							if(limit == ((int)0xffffffff))
-							{
-								spec->isDayLimit = false;
-								spec->lastDay = -1;
-							}
-							else
-							{
-								spec->isDayLimit = true;
-								spec->lastDay = limit;
-							}
-							break;
-						}
-					case 5:
-						{
-							int artNumber = bufor[i]; ++i;
-							for(int yy=0; yy<artNumber; ++yy)
-							{
-								int artid = readNormalNr(i, 2); i+=2;
-								spec->m5arts.push_back(&(CGameInfo::mainObj->arth->artifacts[artid]));
-							}
-							int limit = readNormalNr(i); i+=4;
-							if(limit == ((int)0xffffffff))
-							{
-								spec->isDayLimit = false;
-								spec->lastDay = -1;
-							}
-							else
-							{
-								spec->isDayLimit = true;
-								spec->lastDay = limit;
-							}
-							break;
-						}
-					case 6:
-						{
-							int typeNumber = bufor[i]; ++i;
-							for(int hh=0; hh<typeNumber; ++hh)
-							{
-								int creType = readNormalNr(i, 2); i+=2;
-								int creNumb = readNormalNr(i, 2); i+=2;
-								spec->m6cre.push_back(&(CGameInfo::mainObj->creh->creatures[creType]));
-								spec->m6number.push_back(creNumb);
-							}
-							int limit = readNormalNr(i); i+=4;
-							if(limit == ((int)0xffffffff))
-							{
-								spec->isDayLimit = false;
-								spec->lastDay = -1;
-							}
-							else
-							{
-								spec->isDayLimit = true;
-								spec->lastDay = limit;
-							}
-							break;
-						}
-					case 7:
-						{
-							spec->m7wood = readNormalNr(i); i+=4;
-							spec->m7mercury = readNormalNr(i); i+=4;
-							spec->m7ore = readNormalNr(i); i+=4;
-							spec->m7sulfur = readNormalNr(i); i+=4;
-							spec->m7crystal = readNormalNr(i); i+=4;
-							spec->m7gems = readNormalNr(i); i+=4;
-							spec->m7gold = readNormalNr(i); i+=4;
-							int limit = readNormalNr(i); i+=4;
-							if(limit == ((int)0xffffffff))
-							{
-								spec->isDayLimit = false;
-								spec->lastDay = -1;
-							}
-							else
-							{
-								spec->isDayLimit = true;
-								spec->lastDay = limit;
-							}
-							break;
-						}
-					case 8:
-						{
-							int heroType = bufor[i]; ++i;
-							spec->m8hero = CGameInfo::mainObj->heroh->heroes[heroType];
-							int limit = readNormalNr(i); i+=4;
-							if(limit == ((int)0xffffffff))
-							{
-								spec->isDayLimit = false;
-								spec->lastDay = -1;
-							}
-							else
-							{
-								spec->isDayLimit = true;
-								spec->lastDay = limit;
-							}
-							break;
-						}
-					case 9:
-						{
-							spec->m9player = bufor[i]; ++i;
-							int limit = readNormalNr(i); i+=4;
-							if(limit == ((int)0xffffffff))
-							{
-								spec->isDayLimit = false;
-								spec->lastDay = -1;
-							}
-							else
-							{
-								spec->isDayLimit = true;
-								spec->lastDay = limit;
-							}
-							break;
-						}
-					}//internal switch end (seer huts)
-
-					int len1 = readNormalNr(i); i+=4;
-					for(int ee=0; ee<len1; ++ee)
-					{
-						spec->firstVisitText += bufor[i]; ++i;
-					}
-
-					int len2 = readNormalNr(i); i+=4;
-					for(int ee=0; ee<len2; ++ee)
-					{
-						spec->nextVisitText += bufor[i]; ++i;
-					}
-
-					int len3 = readNormalNr(i); i+=4;
-					for(int ee=0; ee<len3; ++ee)
-					{
-						spec->completedText += bufor[i]; ++i;
-					}
-				}
-				else //RoE
-				{
-					int artID = bufor[i]; ++i;
-					if(artID!=255) //not none quest
-					{
-						spec->m5arts.push_back(&(CGameInfo::mainObj->arth->artifacts[artID]));
-						spec->missionType = 5;
-					}
-					else
-					{
-						spec->missionType = 255;
-					}
-				}
-
-				if(spec->missionType!=255)
-				{
-					unsigned char rewardType = bufor[i]; ++i;
-					spec->rewardType = rewardType;
-
-					switch(rewardType)
-					{
-					case 1:
-						{
-							spec->r1exp = readNormalNr(i); i+=4;
-							break;
-						}
-					case 2:
-						{
-							spec->r2mana = readNormalNr(i); i+=4;
-							break;
-						}
-					case 3:
-						{
-							spec->r3morale = bufor[i]; ++i;
-							break;
-						}
-					case 4:
-						{
-							spec->r4luck = bufor[i]; ++i;
-							break;
-						}
-					case 5:
-						{
-							spec->r5type = bufor[i]; ++i;
-							spec->r5amount = readNormalNr(i, 3); i+=3;
-							i+=1;
-							break;
-						}
-					case 6:
-						{
-							spec->r6type = bufor[i]; ++i;
-							spec->r6amount = bufor[i]; ++i;
-							break;
-						}
-					case 7:
-						{
-							int abid = bufor[i]; ++i;
-							spec->r7ability = CGameInfo::mainObj->abilh->abilities[abid];
-							spec->r7level = bufor[i]; ++i;
-							break;
-						}
-					case 8:
-						{
-							int artid = readNormalNr(i, (map.version == RoE ? 1 : 2)); i+=(map.version == RoE ? 1 : 2);
-							spec->r8art = &(CGameInfo::mainObj->arth->artifacts[artid]);
-							break;
-						}
-					case 9:
-						{
-							int spellid = bufor[i]; ++i;
-							spec->r9spell = &(CGameInfo::mainObj->spellh->spells[spellid]);
-							break;
-						}
-					case 10:
-						{
-							if(map.version>RoE)
-							{
-								int creid = readNormalNr(i, 2); i+=2;
-								spec->r10creature = &(CGameInfo::mainObj->creh->creatures[creid]);
-								spec->r10amount = readNormalNr(i, 2); i+=2;
-							}
-							else
-							{
-								int creid = bufor[i]; ++i;
-								spec->r10creature = &(CGameInfo::mainObj->creh->creatures[creid]);
-								spec->r10amount = readNormalNr(i, 2); i+=2;
-							}
-							break;
-						}
-					}// end of internal switch
-					i+=2;
-				}
-				else //missionType==255
-				{
-					i+=3;
-				}
-				nobj->info = spec;
-				break;
-			}
-		case WITCHHUT_DEF:
-			{
-				CWitchHutObjInfo * spec = new CWitchHutObjInfo;
-				if(map.version>RoE) //in reo we cannot specify it - all are allowed (I hope)
-				{
-					ist=i; //starting i for loop
-					for(i; i<ist+4; ++i)
-					{
-						unsigned char c = bufor[i];
-						for(int yy=0; yy<8; ++yy)
-						{
-							if((i-ist)*8+yy < CGameInfo::mainObj->abilh->abilities.size())
-							{
-								if(c == (c|((unsigned char)intPow(2, yy))))
-									spec->allowedAbilities.push_back(CGameInfo::mainObj->abilh->abilities[(i-ist)*8+yy]);
-							}
-						}
-					}
-				}
-				else //(RoE map)
-				{
-					for(int gg=0; gg<CGameInfo::mainObj->abilh->abilities.size(); ++gg)
-					{
-						spec->allowedAbilities.push_back(CGameInfo::mainObj->abilh->abilities[gg]);
-					}
-				}
-
-				nobj->info = spec;
-				break;
-			}
-		case SCHOLAR_DEF:
-			{
-				CScholarObjInfo * spec = new CScholarObjInfo;
-				spec->bonusType = bufor[i]; ++i;
-				switch(spec->bonusType)
-				{
-				case 0xff:
-					++i;
-					break;
-				case 0:
-					spec->r0type = bufor[i]; ++i;
-					break;
-				case 1:
-					spec->r1 = CGameInfo::mainObj->abilh->abilities[bufor[i]]; ++i;
-					break;
-				case 2:
-					spec->r2 = &(CGameInfo::mainObj->spellh->spells[bufor[i]]); ++i;
-					break;
-				}
-				i+=6;
-				nobj->info = spec;
-				break;
-			}
-		case GARRISON_DEF:
-			{
-				CGarrisonObjInfo * spec = new CGarrisonObjInfo;
-				spec->player = bufor[i]; ++i;
-				i+=3;
-				spec->units = readCreatureSet(i); i+= (map.version==RoE ? 21 : 28);
-				if(map.version > RoE)
-				{
-					spec->movableUnits = bufor[i]; ++i;
-				}
-				else
-					spec->movableUnits = true;
-				i+=8;
-				nobj->setOwner(spec->player);
-				nobj->info = spec;
-				break;
-			}
-		case ARTIFACT_DEF:
-			{
-				CArtifactObjInfo * spec = new CArtifactObjInfo;
-				bool areSettings = bufor[i]; ++i;
-				if(areSettings)
-				{
-					int messLength = readNormalNr(i, 4); i+=4;
-					for(int hh=0; hh<messLength; ++hh)
-					{
-						spec->message += bufor[i]; ++i;
-					}
-					bool areGuards = bufor[i]; ++i;
-					if(areGuards)
-					{
-						spec->areGuards = true;
-						spec->guards = readCreatureSet(i); i+= (map.version == RoE ? 21 : 28) ;
-					}
-					else
-						spec->areGuards = false;
-					i+=4;
-				}
-				nobj->info = spec;
-				break;
-			}
-		case RESOURCE_DEF:
-			{
-				CResourceObjInfo * spec = new CResourceObjInfo;
-				bool isMessGuard = bufor[i]; ++i;
-				if(isMessGuard)
-				{
-					int messLength = readNormalNr(i); i+=4;
-					for(int mm=0; mm<messLength; ++mm)
-					{
-						spec->message+=bufor[i]; ++i;
-					}
-					spec->areGuards = bufor[i]; ++i;
-					if(spec->areGuards)
-					{
-						spec->guards = readCreatureSet(i); i+= (map.version == RoE ? 21 : 28);
-					}
-					i+=4;
-				}
-				else
-				{
-					spec->areGuards = false;
-				}
-				spec->amount = readNormalNr(i); i+=4;
-				i+=4;
-				nobj->info = spec;
-				break;
-			}
-		case TOWN_DEF:
-			{
-				CCastleObjInfo * spec = new CCastleObjInfo;
-				if(map.version!=RoE)
-				{
-					spec->bytes[0] = bufor[i]; ++i;
-					spec->bytes[1] = bufor[i]; ++i;
-					spec->bytes[2] = bufor[i]; ++i;
-					spec->bytes[3] = bufor[i]; ++i;
-				}
-				else
-				{
-					spec->bytes[0] = 0;
-					spec->bytes[1] = 0;
-					spec->bytes[2] = 0;
-					spec->bytes[3] = 0;
-				}
-				spec->player = bufor[i]; ++i;
-
-				bool hasName = bufor[i]; ++i;
-				if(hasName)
-				{
-					int len = readNormalNr(i); i+=4;
-					for(int gg=0; gg<len; ++gg)
-					{
-						spec->name += bufor[i]; ++i;
-					}
-				}
-				bool stGarr = bufor[i]; ++i; //true if garrison isn't empty
-				if(stGarr)
-				{
-					spec->garrison = readCreatureSet(i); i+=( map.version > RoE ? 28 : 21 );
-				}
-				spec->garrison.formation = bufor[i]; ++i;
-				spec->unusualBuildins = bufor[i]; ++i;
-				if(spec->unusualBuildins)
-				{
-					for(int ff=0; ff<12; ++ff)
-					{
-						spec->buildingSettings[ff] = bufor[i]; ++i;
-					}
-				}
-				else
-				{
-					spec->hasFort = bufor[i]; ++i;
-				}
-
-				int ist = i;
-				if(map.version>RoE)
-				{
-					for(i; i<ist+9; ++i)
-					{
-						unsigned char c = bufor[i];
-						for(int yy=0; yy<8; ++yy)
-						{
-							if((i-ist)*8+yy < CGameInfo::mainObj->spellh->spells.size())
-							{
-								if(c == (c|((unsigned char)intPow(2, yy))))
-									spec->obligatorySpells.push_back(&(CGameInfo::mainObj->spellh->spells[(i-ist)*8+yy]));
-							}
-						}
-					}
-				}
-
-				ist = i;
-				for(i; i<ist+9; ++i)
-				{
-					unsigned char c = bufor[i];
-					for(int yy=0; yy<8; ++yy)
-					{
-						if((i-ist)*8+yy < CGameInfo::mainObj->spellh->spells.size())
-						{
-							if(c != (c|((unsigned char)intPow(2, yy))))
-								spec->possibleSpells.push_back(&(CGameInfo::mainObj->spellh->spells[(i-ist)*8+yy]));
-						}
-					}
-				}
-
-				/////// reading castle events //////////////////////////////////
-
-				int numberOfEvent = readNormalNr(i); i+=4;
-
-				for(int gh = 0; gh<numberOfEvent; ++gh)
-				{
-					CCastleEvent nce;
-					int nameLen = readNormalNr(i); i+=4;
-					for(int ll=0; ll<nameLen; ++ll)
-					{
-						nce.name += bufor[i]; ++i;
-					}
-
-					int messLen = readNormalNr(i); i+=4;
-					for(int ll=0; ll<messLen; ++ll)
-					{
-						nce.message += bufor[i]; ++i;
-					}
-
-					nce.wood = readNormalNr(i); i+=4;
-					nce.mercury = readNormalNr(i); i+=4;
-					nce.ore = readNormalNr(i); i+=4;
-					nce.sulfur = readNormalNr(i); i+=4;
-					nce.crystal = readNormalNr(i); i+=4;
-					nce.gems = readNormalNr(i); i+=4;
-					nce.gold = readNormalNr(i); i+=4;
-
-					nce.players = bufor[i]; ++i;
-					if(map.version > AB)
-					{
-						nce.forHuman = bufor[i]; ++i;
-					}
-					else
-						nce.forHuman = true;
-					nce.forComputer = bufor[i]; ++i;
-					nce.firstShow = readNormalNr(i, 2); i+=2;
-					nce.forEvery = bufor[i]; ++i;
-
-					i+=17;
-
-					for(int kk=0; kk<6; ++kk)
-					{
-						nce.bytes[kk] = bufor[i]; ++i;
-					}
-
-					for(int vv=0; vv<7; ++vv)
-					{
-						nce.gen[vv] = readNormalNr(i, 2); i+=2;
-					}
-					i+=4;
-					spec->events.push_back(nce);
-				}
-				spec->x = nobj->pos.x;
-				spec->y = nobj->pos.y;
-				spec->z = nobj->pos.z;
-
-				/////// castle events have been read ///////////////////////////
-
-				if(map.version > AB)
-				{
-					spec->alignment = bufor[i]; ++i;
-				}
-				else
-					spec->alignment = 0xff;
-				i+=3;
-				nobj->info = spec;
-				//////////// rewriting info to CTownInstance class /////////////////////
-				CGTownInstance * nt = new CGTownInstance();
-				(*(static_cast<CGObjectInstance*>(nt))) = *nobj;
-				delete nobj;
-				nobj = nt;
-				nt->identifier = readInt(spec->bytes,4);;
-				if(spec->unusualBuildins)
-				{
-					for(int byte=0;byte<6;byte++)
-					{
-						for(int bit=0;bit<8;bit++)
-						{
-							if(spec->buildingSettings[byte] & (1<<bit))
-							{
-								nt->h3mbuildings.insert(byte*8+bit);
-							}
-						}
-					}
-					for(int byte=6;byte<12;byte++)
-					{
-						for(int bit=0;bit<8;bit++)
-						{
-							if(spec->buildingSettings[byte] & (1<<bit))
-							{
-								nt->forbiddenBuildings.insert(byte*8+bit);
-							}
-						}
-					}
-					nt->builtBuildings = convertBuildings(nt->h3mbuildings,nt->subID);
-					nt->forbiddenBuildings = convertBuildings(nt->forbiddenBuildings,nt->subID);
-				}
-				else
-				{
-					if(spec->hasFort)
-					{
-						nt->builtBuildings.insert(7);
-					}
-					nt->builtBuildings.insert(10);
-					nt->builtBuildings.insert(5);
-					nt->builtBuildings.insert(30);
-					if(rand()%2)
-						nt->builtBuildings.insert(31);
-				}
-
-				nt->setOwner(spec->player);
-				nt->town = &CGI->townh->towns[nt->defInfo->subid];
-				nt->builded = 0;
-				nt->destroyed = 0;
-				nt->name = spec->name;
-				nt->army = spec->garrison;
-				nt->garrisonHero = NULL;// spec->garnisonHero is not readed - TODO: readit
-				nt->pos = int3(spec->x, spec->y, spec->z);
-				nt->possibleSpells = spec->possibleSpells;
-				nt->obligatorySpells = spec->obligatorySpells;
-				nt->availableSpells = std::vector<CSpell*>();
-				CGI->townh->townInstances.push_back(nt);
-				break;
-			}
-		case PLAYERONLY_DEF:
-			{
-				CPlayerOnlyObjInfo * spec = new CPlayerOnlyObjInfo;
-				spec->player = bufor[i]; ++i;
-				i+=3;
-				nobj->setOwner(spec->player);
-				nobj->info = spec;
-				break;
-			}
-		case SHRINE_DEF:
-			{
-				CShrineObjInfo * spec = new CShrineObjInfo;
-				spec->spell = bufor[i]; i+=4;
-				nobj->info = spec;
-				break;
-			}
-		case SPELLSCROLL_DEF:
-			{
-				CSpellScrollObjinfo * spec = new CSpellScrollObjinfo;
-				bool messg = bufor[i]; ++i;
-				if(messg)
-				{
-					int mLength = readNormalNr(i); i+=4;
-					for(int vv=0; vv<mLength; ++vv)
-					{
-						spec->message += bufor[i]; ++i;
-					}
-					spec->areGuarders = bufor[i]; ++i;
-					if(spec->areGuarders)
-					{
-						spec->guarders = readCreatureSet(i); i+=( map.version == RoE ? 21 : 28 );
-					}
-					i+=4;
-				}
-				spec->spell = &(CGameInfo::mainObj->spellh->spells[bufor[i]]); ++i;
-				i+=3;
-				nobj->info = spec;
-				break;
-			}
-		case PANDORA_DEF:
-			{
-				CPandorasBoxObjInfo * spec = new CPandorasBoxObjInfo;
-				bool messg = bufor[i]; ++i;
-				if(messg)
-				{
-					int mLength = readNormalNr(i); i+=4;
-					for(int vv=0; vv<mLength; ++vv)
-					{
-						spec->message += bufor[i]; ++i;
-					}
-					spec->areGuarders = bufor[i]; ++i;
-					if(spec->areGuarders)
-					{
-						spec->guarders = readCreatureSet(i); i+= (map.version == RoE ? 21 : 28);
-					}
-					i+=4;
-				}
-				////// copied form event handling (seems to be similar)
-				spec->gainedExp = readNormalNr(i, 4); i+=4;
-				spec->manaDiff = readNormalNr(i, 4); i+=4;
-				spec->moraleDiff = readNormalNr(i, 1, true); ++i;
-				spec->luckDiff = readNormalNr(i, 1, true); ++i;
-				spec->wood = readNormalNr(i); i+=4;
-				spec->mercury = readNormalNr(i); i+=4;
-				spec->ore = readNormalNr(i); i+=4;
-				spec->sulfur = readNormalNr(i); i+=4;
-				spec->crystal = readNormalNr(i); i+=4;
-				spec->gems = readNormalNr(i); i+=4;
-				spec->gold = readNormalNr(i); i+=4;
-				spec->attack = readNormalNr(i, 1); ++i;
-				spec->defence = readNormalNr(i, 1); ++i;
-				spec->power = readNormalNr(i, 1); ++i;
-				spec->knowledge = readNormalNr(i, 1); ++i;
-				int gabn; //number of gained abilities
-				gabn = readNormalNr(i, 1); ++i;
-				for(int oo = 0; oo<gabn; ++oo)
-				{
-					spec->abilities.push_back((CGameInfo::mainObj->abilh)->abilities[readNormalNr(i, 1)]); ++i;
-					spec->abilityLevels.push_back(readNormalNr(i, 1)); ++i;
-				}
-				int gart = readNormalNr(i, 1); ++i; //number of gained artifacts
-				for(int oo = 0; oo<gart; ++oo)
-				{
-					if(map.version > RoE)
-					{
-						spec->artifacts.push_back(&(CGameInfo::mainObj->arth->artifacts[readNormalNr(i, 2)])); i+=2;
-					}
-					else
-					{
-						spec->artifacts.push_back(&(CGameInfo::mainObj->arth->artifacts[readNormalNr(i, 1)])); i+=1;
-					}
-				}
-				int gspel = readNormalNr(i, 1); ++i; //number of gained spells
-				for(int oo = 0; oo<gspel; ++oo)
-				{
-					spec->spells.push_back(&(CGameInfo::mainObj->spellh->spells[readNormalNr(i, 1)])); ++i;
-				}
-				int gcre = readNormalNr(i, 1); ++i; //number of gained creatures
-				spec->creatures = readCreatureSet(i, gcre); i+=3*gcre;
-				if(map.version > RoE)
-					i+=gcre;
-				i+=8;
-				nobj->info = spec;
-				///////end of copied fragment
-				break;
-			}
-		case GRAIL_DEF:
-			{
-				CGrailObjInfo * spec = new CGrailObjInfo;
-				spec->radius = readNormalNr(i); i+=4;
-				nobj->info = spec;
-				break;
-			}
-		case CREGEN_DEF:
-			{
-				CCreGenObjInfo * spec = new CCreGenObjInfo;
-				spec->player = readNormalNr(i); i+=4;
-				spec->identifier =  readNormalNr(i); i+=4;
-				if(!spec->identifier)
-				{
-					spec->asCastle = false;
-					spec->castles[0] = bufor[i]; ++i;
-					spec->castles[1] = bufor[i]; ++i;
-				}
-				else
-				{
-					spec->asCastle = true;
-				}
-				nobj->setOwner(spec->player);
-				nobj->info = spec;
-				break;
-			}
-		case CREGEN2_DEF:
-			{
-				CCreGen2ObjInfo * spec = new CCreGen2ObjInfo;
-				spec->player = readNormalNr(i); i+=4;
-				spec->identifier =  readNormalNr(i); i+=4;
-				if(!spec->identifier)
-				{
-					spec->asCastle = false;
-					spec->castles[0] = bufor[i]; ++i;
-					spec->castles[1] = bufor[i]; ++i;
-				}
-				else
-				{
-					spec->asCastle = true;
-				}
-				spec->minLevel = bufor[i]; ++i;
-				spec->maxLevel = bufor[i]; ++i;
-				//if(spec->maxLevel>7)
-				//	spec->maxLevel = 7;
-				//if(spec->minLevel<1)
-				//	spec->minLevel = 1;
-				nobj->setOwner(spec->player);
-				nobj->info = spec;
-				break;
-			}
-		case CREGEN3_DEF:
-			{
-				CCreGen3ObjInfo * spec = new CCreGen3ObjInfo;
-				spec->player = bufor[i]; ++i;
-				i+=3;
-				spec->minLevel = bufor[i]; ++i;
-				spec->maxLevel = bufor[i]; ++i;
-				if(spec->maxLevel>7)
-					spec->maxLevel = 7;
-				if(spec->minLevel<1)
-					spec->minLevel = 1;
-				nobj->setOwner(spec->player);
-				nobj->info = spec;
-				break;
-			}
-		case BORDERGUARD_DEF:
-			{
-				CBorderGuardObjInfo * spec = new CBorderGuardObjInfo;
-				spec->missionType = bufor[i]; ++i;
-				switch(spec->missionType)
-				{
-				case 0:
-					{
-						goto borderguardend;
-						break;
-					}
-				case 1:
-					{
-						spec->m1level = readNormalNr(i); i+=4;
-						int limit = readNormalNr(i); i+=4;
-						if(limit == ((int)0xffffffff))
-						{
-							spec->isDayLimit = false;
-							spec->lastDay = -1;
-						}
-						else
-						{
-							spec->isDayLimit = true;
-							spec->lastDay = limit;
-						}
-						break;
-					}
-				case 2:
-					{
-						spec->m2attack = bufor[i]; ++i;
-						spec->m2defence = bufor[i]; ++i;
-						spec->m2power = bufor[i]; ++i;
-						spec->m2knowledge = bufor[i]; ++i;
-						int limit = readNormalNr(i); i+=4;
-						if(limit == ((int)0xffffffff))
-						{
-							spec->isDayLimit = false;
-							spec->lastDay = -1;
-						}
-						else
-						{
-							spec->isDayLimit = true;
-							spec->lastDay = limit;
-						}
-						break;
-					}
-				case 3:
-					{
-						spec->m3bytes[0] = bufor[i]; ++i;
-						spec->m3bytes[1] = bufor[i]; ++i;
-						spec->m3bytes[2] = bufor[i]; ++i;
-						spec->m3bytes[3] = bufor[i]; ++i;
-						int limit = readNormalNr(i); i+=4;
-						if(limit == ((int)0xffffffff))
-						{
-							spec->isDayLimit = false;
-							spec->lastDay = -1;
-						}
-						else
-						{
-							spec->isDayLimit = true;
-							spec->lastDay = limit;
-						}
-						break;
-					}
-				case 4:
-					{
-						spec->m4bytes[0] = bufor[i]; ++i;
-						spec->m4bytes[1] = bufor[i]; ++i;
-						spec->m4bytes[2] = bufor[i]; ++i;
-						spec->m4bytes[3] = bufor[i]; ++i;
-						int limit = readNormalNr(i); i+=4;
-						if(limit == ((int)0xffffffff))
-						{
-							spec->isDayLimit = false;
-							spec->lastDay = -1;
-						}
-						else
-						{
-							spec->isDayLimit = true;
-							spec->lastDay = limit;
-						}
-						break;
-					}
-				case 5:
-					{
-						int artNumber = bufor[i]; ++i;
-						for(int yy=0; yy<artNumber; ++yy)
-						{
-							int artid = readNormalNr(i, 2); i+=2;
-							spec->m5arts.push_back(&(CGameInfo::mainObj->arth->artifacts[artid]));
-						}
-						int limit = readNormalNr(i); i+=4;
-						if(limit == ((int)0xffffffff))
-						{
-							spec->isDayLimit = false;
-							spec->lastDay = -1;
-						}
-						else
-						{
-							spec->isDayLimit = true;
-							spec->lastDay = limit;
-						}
-						break;
-					}
-				case 6:
-					{
-						int typeNumber = bufor[i]; ++i;
-						for(int hh=0; hh<typeNumber; ++hh)
-						{
-							int creType = readNormalNr(i, 2); i+=2;
-							int creNumb = readNormalNr(i, 2); i+=2;
-							spec->m6cre.push_back(&(CGameInfo::mainObj->creh->creatures[creType]));
-							spec->m6number.push_back(creNumb);
-						}
-						int limit = readNormalNr(i); i+=4;
-						if(limit == ((int)0xffffffff))
-						{
-							spec->isDayLimit = false;
-							spec->lastDay = -1;
-						}
-						else
-						{
-							spec->isDayLimit = true;
-							spec->lastDay = limit;
-						}
-						break;
-					}
-				case 7:
-					{
-						spec->m7wood = readNormalNr(i); i+=4;
-						spec->m7mercury = readNormalNr(i); i+=4;
-						spec->m7ore = readNormalNr(i); i+=4;
-						spec->m7sulfur = readNormalNr(i); i+=4;
-						spec->m7crystal = readNormalNr(i); i+=4;
-						spec->m7gems = readNormalNr(i); i+=4;
-						spec->m7gold = readNormalNr(i); i+=4;
-						int limit = readNormalNr(i); i+=4;
-						if(limit == ((int)0xffffffff))
-						{
-							spec->isDayLimit = false;
-							spec->lastDay = -1;
-						}
-						else
-						{
-							spec->isDayLimit = true;
-							spec->lastDay = limit;
-						}
-						break;
-					}
-				case 8:
-					{
-						int heroType = bufor[i]; ++i;
-						spec->m8hero = CGameInfo::mainObj->heroh->heroes[heroType];
-						int limit = readNormalNr(i); i+=4;
-						if(limit == ((int)0xffffffff))
-						{
-							spec->isDayLimit = false;
-							spec->lastDay = -1;
-						}
-						else
-						{
-							spec->isDayLimit = true;
-							spec->lastDay = limit;
-						}
-						break;
-					}
-				case 9:
-					{
-						spec->m9player = bufor[i]; ++i;
-						int limit = readNormalNr(i); i+=4;
-						if(limit == ((int)0xffffffff))
-						{
-							spec->isDayLimit = false;
-							spec->lastDay = -1;
-						}
-						else
-						{
-							spec->isDayLimit = true;
-							spec->lastDay = limit;
-						}
-						break;
-					}
-				}//internal switch end (seer huts)
-
-				int len1;
-				len1 = readNormalNr(i); i+=4;
-				for(int ee=0; ee<len1; ++ee)
-				{
-					spec->firstVisitText += bufor[i]; ++i;
-				}
-
-				int len2;
-				len2 = readNormalNr(i); i+=4;
-				for(int ee=0; ee<len2; ++ee)
-				{
-					spec->nextVisitText += bufor[i]; ++i;
-				}
-
-				int len3;
-				len3 = readNormalNr(i); i+=4;
-				for(int ee=0; ee<len3; ++ee)
-				{
-					spec->completedText += bufor[i]; ++i;
-				}
-				nobj->info = spec;
-borderguardend:
-				break;
-			}
-		case HEROPLACEHOLDER_DEF:
-			{
-				i+=3; //TODO: handle it more properly
-				break;
-			}
-		} //end of main switch
-		CGameInfo::mainObj->objh->objInstances.push_back(nobj);
-		//TODO - dokoñczyæ, du¿o do zrobienia - trzeba patrzeæ, co def niesie
-	}//*/ //end of loading objects; commented to make application work until it will be finished
-	////objects loaded
-
-	THC std::cout<<"\tReading objects: "<<th.getDif()<<std::endl;
-	//processMap(defsToUnpack);
-	std::vector<CDefHandler *> dhandlers = CGameInfo::mainObj->spriteh->extractManyFiles(defsToUnpack);
-
-	THC std::cout<<"\tUnpacking defs: "<<th.getDif()<<std::endl;
-	for (int i=0;i<dhandlers.size();i++)
-	{
-		map.defy[i]->handler=dhandlers[i];
-		CGDefInfo* pom = CGI->dobjinfo->gobjs[map.defy[i]->id][map.defy[i]->subid];
-		if(pom)
-			pom->handler=dhandlers[i];
-		else
-			std::cout << "Lacking def info for " << map.defy[i]->id << " " << map.defy[i]->subid <<" " << map.defy[i]->name << std::endl;
-	}
-	for(int vv=0; vv<map.defy.size(); ++vv)
-	{
-		if(map.defy[vv]->handler->alphaTransformed)
-			continue;
-		for(int yy=0; yy<map.defy[vv]->handler->ourImages.size(); ++yy)
-		{
-			map.defy[vv]->handler->ourImages[yy].bitmap = CSDL_Ext::alphaTransform(map.defy[vv]->handler->ourImages[yy].bitmap);
-			//SDL_Surface * bufs = CSDL_Ext::secondAlphaTransform(map.defy[vv]->handler->ourImages[yy].bitmap, CSDL_Ext::std32bppSurface);
-			//SDL_FreeSurface(map.defy[vv]->handler->ourImages[yy].bitmap);
-			//map.defy[vv]->handler->ourImages[yy].bitmap = bufs;
-			map.defy[vv]->handler->alphaTransformed = true;
-		}
-	}
-
-	THC std::cout<<"\tHandling defs: "<<th.getDif()<<std::endl;
-
-	//loading events
-	int numberOfEvents = readNormalNr(i); i+=4;
-	for(int yyoo=0; yyoo<numberOfEvents; ++yyoo)
-	{
-		CMapEvent ne;
-		ne.name = std::string();
-		ne.message = std::string();
-		int nameLen = readNormalNr(i); i+=4;
-		for(int qq=0; qq<nameLen; ++qq)
-		{
-			ne.name += bufor[i]; ++i;
-		}
-		int messLen = readNormalNr(i); i+=4;
-		for(int qq=0; qq<messLen; ++qq)
-		{
-			ne.message +=bufor[i]; ++i;
-		}
-		ne.wood = readNormalNr(i); i+=4;
-		ne.mercury = readNormalNr(i); i+=4;
-		ne.ore = readNormalNr(i); i+=4;
-		ne.sulfur = readNormalNr(i); i+=4;
-		ne.crystal = readNormalNr(i); i+=4;
-		ne.gems = readNormalNr(i); i+=4;
-		ne.gold = readNormalNr(i); i+=4;
-		ne.players = bufor[i]; ++i;
-		if(map.version>AB)
-		{
-			ne.humanAffected = bufor[i]; ++i;
-		}
-		else
-			ne.humanAffected = true;
-		ne.computerAffected = bufor[i]; ++i;
-		ne.firstOccurence = bufor[i]; ++i;
-		ne.nextOccurence = bufor[i]; ++i;
-		i+=18;
-		map.events.push_back(ne);
-	}
-}
-int CAmbarCendamo::readNormalNr (int pos, int bytCon, bool cyclic)
-{
-	int ret=0;
-	int amp=1;
-	for (int i=0; i<bytCon; i++)
-	{
-		ret+=bufor[pos+i]*amp;
-		amp*=256;
-	}
-	if(cyclic && bytCon<4 && ret>=amp/2)
-	{
-		ret = ret-amp;
-	}
-	return ret;
-}
-
-void CAmbarCendamo::loadDefs()
-{
-	std::set<int> loadedTypes;
-	for (int i=0; i<map.width; i++)
-	{
-		for (int j=0; j<map.width; j++)
-		{
-			if (loadedTypes.find(map.terrain[i][j].tertype)==loadedTypes.end())
-			{
-				CDefHandler  *sdh = CGI->spriteh->giveDef(CSemiDefHandler::nameFromType(map.terrain[i][j].tertype).c_str());
-				loadedTypes.insert(map.terrain[i][j].tertype);
-				defs.push_back(sdh);
-			}
-			if (map.twoLevel && loadedTypes.find(map.undergroungTerrain[i][j].tertype)==loadedTypes.end())
-			{
-				CDefHandler  *sdh = CGI->spriteh->giveDef(CSemiDefHandler::nameFromType(map.undergroungTerrain[i][j].tertype).c_str());
-				loadedTypes.insert(map.undergroungTerrain[i][j].tertype);
-				defs.push_back(sdh);
-			}
-		}
-	}
-}
-
-EDefType CAmbarCendamo::getDefType(CGDefInfo * a)
-{
-	switch(a->id)
-	{
-	case 5: case 65: case 66: case 67: case 68: case 69:
-		return ARTIFACT_DEF; //handled
-	case 6:
-		return PANDORA_DEF; //hanled
-	case 26:
-		return EVENTOBJ_DEF; //handled
-	case 33:
-		return GARRISON_DEF; //handled
-	case 34: case 70: case 62: //70 - random hero //62 - prison
-		return HERO_DEF; //handled
-	case 36:
-		return GRAIL_DEF; //hanled
-	case 53: case 17: case 18: case 19: case 20: case 42: case 87: case 220://cases 17 - 20 and 42 - tests
-		return PLAYERONLY_DEF; //handled
-	case 54: case 71: case 72: case 73: case 74: case 75: case 162: case 163: case 164:
-		return CREATURES_DEF; //handled
-	case 59:
-		return SIGN_DEF; //handled
-	case 77:
-		return TOWN_DEF; //can be problematic, but handled
-	case 79: case 76:
-		return RESOURCE_DEF; //handled
-	case 81:
-		return SCHOLAR_DEF; //handled
-	case 83:
-		return SEERHUT_DEF; //handled
-	case 91:
-		return SIGN_DEF; //handled
-	case 88: case 89: case 90:
-		return SHRINE_DEF; //handled
-	case 93:
-		return SPELLSCROLL_DEF; //handled
-	case 98:
-		return TOWN_DEF; //handled
-	case 113:
-		return WITCHHUT_DEF; //handled
-	case 214:
-		return HEROPLACEHOLDER_DEF; //partially handled
-	case 215:
-		return BORDERGUARD_DEF; //handled by analogy to seer huts ;]
-	case 216:
-		return CREGEN2_DEF; //handled
-	case 217:
-		return CREGEN_DEF; //handled
-	case 218:
-		return CREGEN3_DEF; //handled
-	case 219:
-		return GARRISON_DEF; //handled
-	default:
-		return TERRAINOBJ_DEF; // nothing to be handled
-	}
-}
-
-CCreatureSet CAmbarCendamo::readCreatureSet(int pos, int number)
-{
-	if(map.version>RoE)
-	{
-		CCreatureSet ret;
-		std::pair<CCreature *, int> ins;
-		if(number>0 && readNormalNr(pos, 2)!=0xffff)
-		{
-			int rettt = readNormalNr(pos, 2);
-			if(rettt>32768)
-				rettt = 65536-rettt+CGameInfo::mainObj->creh->creatures.size()-16;
-			ins.first = &(CGameInfo::mainObj->creh->creatures[rettt]);
-			ins.second = readNormalNr(pos+2, 2);
-			std::pair<int,std::pair<CCreature *, int> > tt(0,ins);
-			ret.slots.insert(tt);
-		}
-		if(number>1 && readNormalNr(pos+4, 2)!=0xffff)
-		{
-			int rettt = readNormalNr(pos+4, 2);
-			if(rettt>32768)
-				rettt = 65536-rettt+CGameInfo::mainObj->creh->creatures.size()-16;
-			ins.first  = &(CGameInfo::mainObj->creh->creatures[rettt]);
-			ins.second = readNormalNr(pos+6, 2);
-			std::pair<int,std::pair<CCreature *, int> > tt(1,ins);
-			ret.slots.insert(tt);
-		}
-		if(number>2 && readNormalNr(pos+8, 2)!=0xffff)
-		{
-			int rettt = readNormalNr(pos+8, 2);
-			if(rettt>32768)
-				rettt = 65536-rettt+CGameInfo::mainObj->creh->creatures.size()-16;
-			ins.first  = &(CGameInfo::mainObj->creh->creatures[rettt]);
-			ins.second = readNormalNr(pos+10, 2);
-			std::pair<int,std::pair<CCreature *, int> > tt(2,ins);
-			ret.slots.insert(tt);
-		}
-		if(number>3 && readNormalNr(pos+12, 2)!=0xffff)
-		{
-			int rettt = readNormalNr(pos+12, 2);
-			if(rettt>32768)
-				rettt = 65536-rettt+CGameInfo::mainObj->creh->creatures.size()-16;
-			ins.first  = &(CGameInfo::mainObj->creh->creatures[rettt]);
-			ins.second = readNormalNr(pos+14, 2);
-			std::pair<int,std::pair<CCreature *, int> > tt(3,ins);
-			ret.slots.insert(tt);
-		}
-		if(number>4 && readNormalNr(pos+16, 2)!=0xffff)
-		{
-			int rettt = readNormalNr(pos+16, 2);
-			if(rettt>32768)
-				rettt = 65536-rettt+CGameInfo::mainObj->creh->creatures.size()-16;
-			ins.first  = &(CGameInfo::mainObj->creh->creatures[rettt]);
-			ins.second = readNormalNr(pos+18, 2);
-			std::pair<int,std::pair<CCreature *, int> > tt(4,ins);
-			ret.slots.insert(tt);
-		}
-		if(number>5 && readNormalNr(pos+20, 2)!=0xffff)
-		{
-			int rettt = readNormalNr(pos+20, 2);
-			if(rettt>32768)
-				rettt = 65536-rettt+CGameInfo::mainObj->creh->creatures.size()-16;
-			ins.first  = &(CGameInfo::mainObj->creh->creatures[rettt]);
-			ins.second = readNormalNr(pos+22, 2);
-			std::pair<int,std::pair<CCreature *, int> > tt(5,ins);
-			ret.slots.insert(tt);
-		}
-		if(number>6 && readNormalNr(pos+24, 2)!=0xffff)
-		{
-			int rettt = readNormalNr(pos+24, 2);
-			if(rettt>32768)
-				rettt = 65536-rettt+CGameInfo::mainObj->creh->creatures.size()-16;
-			ins.first  = &(CGameInfo::mainObj->creh->creatures[rettt]);
-			ins.second = readNormalNr(pos+26, 2);
-			std::pair<int,std::pair<CCreature *, int> > tt(6,ins);
-			ret.slots.insert(tt);
-		}
-		return ret;
-	}
-	else
-	{
-		CCreatureSet ret;
-		std::pair<CCreature *, int> ins;
-		if(number>0 && readNormalNr(pos, 1)!=0xff)
-		{
-			int rettt = readNormalNr(pos, 1);
-			if(rettt>220)
-				rettt = 256-rettt+CGameInfo::mainObj->creh->creatures.size()-16;
-			ins.first = &(CGameInfo::mainObj->creh->creatures[rettt]);
-			ins.second = readNormalNr(pos+1, 2);
-			std::pair<int,std::pair<CCreature *, int> > tt(0,ins);
-			ret.slots.insert(tt);
-		}
-		if(number>1 && readNormalNr(pos+3, 1)!=0xff)
-		{
-			int rettt = readNormalNr(pos+3, 1);
-			if(rettt>220)
-				rettt = 256-rettt+CGameInfo::mainObj->creh->creatures.size()-16;
-			ins.first  = &(CGameInfo::mainObj->creh->creatures[rettt]);
-			ins.second = readNormalNr(pos+4, 2);
-			std::pair<int,std::pair<CCreature *, int> > tt(1,ins);
-			ret.slots.insert(tt);
-		}
-		if(number>2 && readNormalNr(pos+6, 1)!=0xff)
-		{
-			int rettt = readNormalNr(pos+6, 1);
-			if(rettt>220)
-				rettt = 256-rettt+CGameInfo::mainObj->creh->creatures.size()-16;
-			ins.first  = &(CGameInfo::mainObj->creh->creatures[rettt]);
-			ins.second = readNormalNr(pos+7, 2);
-			std::pair<int,std::pair<CCreature *, int> > tt(2,ins);
-			ret.slots.insert(tt);
-		}
-		if(number>3 && readNormalNr(pos+9, 1)!=0xff)
-		{
-			int rettt = readNormalNr(pos+9, 1);
-			if(rettt>220)
-				rettt = 256-rettt+CGameInfo::mainObj->creh->creatures.size()-16;
-			ins.first  = &(CGameInfo::mainObj->creh->creatures[rettt]);
-			ins.second = readNormalNr(pos+10, 2);
-			std::pair<int,std::pair<CCreature *, int> > tt(3,ins);
-			ret.slots.insert(tt);
-		}
-		if(number>4 && readNormalNr(pos+12, 1)!=0xff)
-		{
-			int rettt = readNormalNr(pos+12, 1);
-			if(rettt>220)
-				rettt = 256-rettt+CGameInfo::mainObj->creh->creatures.size()-16;
-			ins.first  = &(CGameInfo::mainObj->creh->creatures[rettt]);
-			ins.second = readNormalNr(pos+13, 2);
-			std::pair<int,std::pair<CCreature *, int> > tt(4,ins);
-			ret.slots.insert(tt);
-		}
-		if(number>5 && readNormalNr(pos+15, 1)!=0xff)
-		{
-			int rettt = readNormalNr(pos+15, 1);
-			if(rettt>220)
-				rettt = 256-rettt+CGameInfo::mainObj->creh->creatures.size()-16;
-			ins.first  = &(CGameInfo::mainObj->creh->creatures[rettt]);
-			ins.second = readNormalNr(pos+16, 2);
-			std::pair<int,std::pair<CCreature *, int> > tt(5,ins);
-			ret.slots.insert(tt);
-		}
-		if(number>6 && readNormalNr(pos+18, 1)!=0xff)
-		{
-			int rettt = readNormalNr(pos+18, 1);
-			if(rettt>220)
-				rettt = 256-rettt+CGameInfo::mainObj->creh->creatures.size()-16;
-			ins.first  = &(CGameInfo::mainObj->creh->creatures[rettt]);
-			ins.second = readNormalNr(pos+19, 2);
-			std::pair<int,std::pair<CCreature *, int> > tt(6,ins);
-			ret.slots.insert(tt);
-		}
-		return ret;
-	}
-}
-
-void CAmbarCendamo::processMap(std::vector<std::string> & defsToUnpack)
-{}
+//#define VCMI_DLL
+//#include "../stdafx.h"
+//#include "CAmbarCendamo.h"
+//#include "CObjectHandler.h"
+//#include "CDefObjInfoHandler.h"
+//#include <set>
+//#include <sstream>
+//#include <fstream>
+//#include "../lib/VCMI_Lib.h"
+//std::string nameFromType (EterrainType typ);
+//int readInt(unsigned char * bufor, int bytCon)
+//{
+//	int ret=0;
+//	int amp=1;
+//	for (int i=0; i<bytCon; i++)
+//	{
+//		ret+=bufor[i]*amp;
+//		amp*=256;
+//	}
+//	return ret;
+//}
+//CAmbarCendamo::CAmbarCendamo (unsigned char * data)
+////:map(data)
+//{}
+////CAmbarCendamo::CAmbarCendamo (const char * tie)
+////{
+////	std::ifstream * is = new std::ifstream();
+////	is -> open(tie,std::ios::binary);
+////	is->seekg(0,std::ios::end); // na koniec
+////	int andame = is->tellg();  // read length
+////	is->seekg(0,std::ios::beg); // wracamy na poczatek
+////	bufor = new unsigned char[andame]; // allocate memory 
+////	is->read((char*)bufor, andame); // read map file to buffer
+////	is->close();
+////	delete is;
+////}
+//CAmbarCendamo::~CAmbarCendamo () 
+//{// free memory
+//	for (int ii=0;ii<map.width;ii++)
+//		delete map.terrain[ii] ; 
+//	delete map.terrain;
+//	delete[] bufor;
+//}

+ 5 - 26
hch/CAmbarCendamo.h

@@ -1,40 +1,19 @@
 #ifndef CAMBARCENDAMO_H
 #define CAMBARCENDAMO_H
 #include <iostream>
-#include <fstream>
 #include <string>
 #include <vector>
 #include "../global.h"
-#include "SDL.h"
 #include "../map.h"
-#include "CSemiDefHandler.h"
-#include "CDefHandler.h"
 #include "CCreatureHandler.h"
 
-enum EDefType {TOWN_DEF, HERO_DEF, CREATURES_DEF, SEERHUT_DEF, RESOURCE_DEF, TERRAINOBJ_DEF, EVENTOBJ_DEF, SIGN_DEF, GARRISON_DEF, ARTIFACT_DEF, WITCHHUT_DEF, SCHOLAR_DEF, PLAYERONLY_DEF, SHRINE_DEF, SPELLSCROLL_DEF, PANDORA_DEF, GRAIL_DEF, CREGEN_DEF, CREGEN2_DEF, CREGEN3_DEF, BORDERGUARD_DEF, HEROPLACEHOLDER_DEF};
-
-class CAmbarCendamo
+class DLL_EXPORT CAmbarCendamo 
 {
 public:
 /////////////////member variables
-	Mapa map;
-	std::ifstream * is; // stream used to read map file
-	int andame; // length of map file
-	unsigned char * bufor; // here we store map bytecode
-	std::vector<CDefHandler*> defs;
-/////////////////member functions
-	CAmbarCendamo (const char * tie); // c-tor; tie is the path of the map file
-	CAmbarCendamo (unsigned char * map); // c-tor; map is pointer to array containing map; it is not copied, so don't delete
-	~CAmbarCendamo (); // d-tor
-	int readNormalNr (int pos, int bytCon=4, bool cyclic = false); //read number from bytCon bytes starting from pos position in buffer ; if cyclic is true, number is treated as it were signed number with bytCon bytes
-	void teceDef (); // create files with info about defs
-	void deh3m(); // decode file, results are stored in map
-	void processMap(std::vector<std::string> & defsToUnpack); //choose castles, creatures, resources, artifacts...
-	////
-	std::vector<std::string> resDefNames;
-	////
-	void loadDefs();
-	EDefType getDefType(CGDefInfo * a); //returns type of object in def
-	CCreatureSet readCreatureSet(int pos, int number = 7); //reads creature set in most recently encountered format; reades number units (default is 7)
+	//Mapa* map;
+
+	//CAmbarCendamo (unsigned char * data); // c-tor; data is pointer to decompressed h3m data
+	//~CAmbarCendamo (); // d-tor
 };
 #endif //CAMBARCENDAMO_H

+ 29 - 128
hch/CArtHandler.cpp

@@ -1,146 +1,47 @@
+#define VCMI_DLL
 #include "../stdafx.h"
 #include "CArtHandler.h"
-#include "../CGameInfo.h"
-#include "CGeneralTextHandler.h"
 #include "CLodHandler.h"
-
+#include <boost/assign/std/vector.hpp>
+#include <boost/assign/list_of.hpp>
+#include "../lib/VCMI_Lib.h"
+void loadToIt(std::string &dest, std::string &src, int &iter, int mode);
+extern CLodHandler *bitmaph;
+using namespace boost::assign;
+CArtHandler::CArtHandler()
+{
+	VLC->arth = this;
+}
 void CArtHandler::loadArtifacts()
 {
-	artDefs = CGI->spriteh->giveDef("ARTIFACT.DEF");
-
-	std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("ARTRAITS.TXT");
+	std::vector<bool CArtifact::*> slots;
+	slots += &CArtifact::spellBook, &CArtifact::warMachine4, &CArtifact::warMachine3, &CArtifact::warMachine2, 
+	  &CArtifact::warMachine1, &CArtifact::misc5, &CArtifact::misc4, &CArtifact::misc3, &CArtifact::misc2, 
+	  &CArtifact::misc1, &CArtifact::feet, &CArtifact::lRing, &CArtifact::rRing, &CArtifact::torso, 
+	  &CArtifact::lHand, &CArtifact::rHand, &CArtifact::neck,	&CArtifact::shoulders, &CArtifact::head;
+	std::map<char,EartClass> classes = 
+	  map_list_of('S',SartClass)('T',TartClass)('N',NartClass)('J',JartClass)('R',RartClass);
+	std::string buf = bitmaph->getTextFile("ARTRAITS.TXT"), dump, pom;
 	int it=0;
-	std::string dump;
 	for(int i=0; i<2; ++i)
 	{
-		CGeneralTextHandler::loadToIt(dump,buf,it,3);
+		loadToIt(dump,buf,it,3);
 	}
 	for (int i=0; i<ARTIFACTS_QUANTITY; i++)
 	{
 		CArtifact nart;
-		std::string pom;
-		CGeneralTextHandler::loadToIt(nart.name,buf,it,4);
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
+		loadToIt(nart.name,buf,it,4);
+		loadToIt(pom,buf,it,4);
 		nart.price=atoi(pom.c_str());
-
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.spellBook=true;
-		else
-			nart.spellBook = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.warMachine4=true;
-		else
-			nart.warMachine4 = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.warMachine3=true;
-		else
-			nart.warMachine3 = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.warMachine2=true;
-		else
-			nart.warMachine2 = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.warMachine1=true;
-		else
-			nart.warMachine1 = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.misc5=true;
-		else
-			nart.misc5 = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.misc4=true;
-		else
-			nart.misc4 = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.misc3=true;
-		else
-			nart.misc3 = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.misc2=true;
-		else
-			nart.misc2 = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.misc1=true;
-		else
-			nart.misc1 = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.feet=true;
-		else
-			nart.feet = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.lRing=true;
-		else
-			nart.lRing = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.rRing=true;
-		else
-			nart.rRing = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.torso=true;
-		else
-			nart.torso = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.lHand=true;
-		else
-			nart.lHand = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.rHand=true;
-		else
-			nart.rHand = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.neck=true;
-		else
-			nart.neck = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.shoulders=true;
-		else
-			nart.shoulders = false;
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		if (pom[0]=='x')
-			nart.head=true;
-		else
-			nart.head = false;
-
-		CGeneralTextHandler::loadToIt(pom,buf,it,4);
-		switch (pom[0])
+		for(int j=0;j<slots.size();j++)
 		{
-		case 'S':
-			nart.aClass=SartClass;
-			break;
-		case 'T':
-			nart.aClass=TartClass;
-			break;
-		case 'N':
-			nart.aClass=NartClass;
-			break;
-		case 'J':
-			nart.aClass=JartClass;
-			break;
-		case 'R':
-			nart.aClass=RartClass;
-			break;
+			loadToIt(pom,buf,it,4);
+			nart.*slots[j] = (pom[0]=='x');
 		}
-		CGeneralTextHandler::loadToIt(nart.description,buf,it,3);
-		nart.id=artifacts.size();
-
+		loadToIt(pom,buf,it,4);
+		nart.aClass = classes[pom[0]];
+		loadToIt(nart.description,buf,it,3);
+		nart.id=i;
 		artifacts.push_back(nart);
 	}
 	for(int i=0;i<144;i++) //do 144, bo nie chcemy bzdurek

+ 4 - 4
hch/CArtHandler.h

@@ -1,13 +1,13 @@
 #ifndef CARTHANDLER_H
 #define CARTHANDLER_H
-
+#include "../global.h"
 #include <string>
 #include <vector>
 
 enum EartClass {SartClass=0, TartClass, NartClass, JartClass, RartClass}; //artifact class (relict, treasure, strong, weak etc.)
 class CDefHandler;
 
-class CArtifact //container for artifacts
+class DLL_EXPORT CArtifact //container for artifacts
 {
 public:
 	bool isAllowed; //true if we can use this artifact (map information)
@@ -21,14 +21,14 @@ public:
 	int id;
 };
 
-class CArtHandler //handles artifacts
+class DLL_EXPORT CArtHandler //handles artifacts
 {
 public:
-	CDefHandler * artDefs;
 	std::vector<CArtifact*> treasures, minors, majors, relics;
 	std::vector<CArtifact> artifacts;
 	void loadArtifacts();
 	bool loadArtEvents();
+	CArtHandler();
 };
 
 #endif // CARTHANDLER_H

+ 7 - 5
hch/CBuildingHandler.cpp

@@ -1,9 +1,10 @@
+#define VCMI_DLL
 #include "../stdafx.h"
-#include "../CGameInfo.h"
 #include "CBuildingHandler.h"
 #include "CLodHandler.h"
 #include <sstream>
 #include <fstream>
+extern CLodHandler * bitmaph;
 std::string readTo(std::string &in, unsigned int &it, char end)
 {
 	int pom = it;
@@ -31,6 +32,7 @@ unsigned int readNr(std::string &in, unsigned int &it)
 CBuilding * readBg(std::string &buf, unsigned int& it)
 {
 	CBuilding * nb = new CBuilding();
+	nb->resources.resize(RESOURCE_QUANTITY);
 	for(int res=0;res<7;res++)
 		nb->resources[res] = readNr(buf,it);
 	nb->refName = readTo(buf,it,'\n');
@@ -38,7 +40,7 @@ CBuilding * readBg(std::string &buf, unsigned int& it)
 }
 void CBuildingHandler::loadBuildings()
 {
-	std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("BUILDING.TXT"), temp;
+	std::string buf = bitmaph->getTextFile("BUILDING.TXT"), temp;
 	unsigned int andame = buf.size(), it=0; //buf iterator
 
 	temp = readTo(buf,it,'\n');temp = readTo(buf,it,'\n');//read 2 lines of file info
@@ -79,7 +81,7 @@ void CBuildingHandler::loadBuildings()
 	}
 	/////done reading BUILDING.TXT*****************************
 
-	buf = CGameInfo::mainObj->bitmaph->getTextFile("BLDGNEUT.TXT");
+	buf = bitmaph->getTextFile("BLDGNEUT.TXT");
 	andame = buf.size(), it=0;
 
 	for(int b=0;b<15;b++)
@@ -109,7 +111,7 @@ void CBuildingHandler::loadBuildings()
 	}
 	/////done reading "BLDGNEUT.TXT"******************************
 
-	buf = CGameInfo::mainObj->bitmaph->getTextFile("BLDGSPEC.TXT");
+	buf = bitmaph->getTextFile("BLDGSPEC.TXT");
 	andame = buf.size(), it=0;
 	for(int f=0;f<F_NUMBER;f++)
 	{
@@ -126,7 +128,7 @@ void CBuildingHandler::loadBuildings()
 	}
 	/////done reading BLDGSPEC.TXT*********************************
 
-	buf = CGameInfo::mainObj->bitmaph->getTextFile("DWELLING.TXT");
+	buf = bitmaph->getTextFile("DWELLING.TXT");
 	andame = buf.size(), it=0;
 	for(int f=0;f<F_NUMBER;f++)
 	{

+ 4 - 3
hch/CBuildingHandler.h

@@ -2,19 +2,20 @@
 #define CBUILDINGHANDLER_H
 #include "../global.h"
 #include <map>
+#include <vector>
 //enum EbuildingType {NEUTRAL=-1, CASTLE, RAMPART, TOWER, INFERNO, NECROPOLIS, DUNGEON, STRONGHOLD, FORTRESS, CONFLUX};
-class CBuilding //a typical building encountered in every castle ;]
+class DLL_EXPORT CBuilding //a typical building encountered in every castle ;]
 {
 public:
 	std::string name;
 	std::string refName; //reference name, for identification
-	int resources[7];
+	std::vector<int> resources;
 	std::string description;
 	//EbuildingType type; //type of building (occures in many castles or is specific for one castle)
 	//bool isDwelling; //true, if this building is a dwelling
 };
 
-class CBuildingHandler
+class DLL_EXPORT CBuildingHandler
 {
 public:
 	std::map<int, std::map<int, CBuilding*> > buildings; ///< first int is the castle ID, second the building ID (in ERM-U format)

+ 0 - 2
hch/CCastleHandler.cpp

@@ -1,2 +0,0 @@
-#include "../stdafx.h"
-#include "CCastleHandler.h"

+ 0 - 51
hch/CCastleHandler.h

@@ -1,51 +0,0 @@
-#ifndef CCASTLEHANDLER_H
-#define CCASTLEHANDLER_H
-
-#include "CBuildingHandler.h"
-#include "CHeroHandler.h"
-#include "CObjectHandler.h"
-#include "CCreatureHandler.h"
-
-class CCastleEvent
-{
-public:
-	std::string name, message;
-	int wood, mercury, ore, sulfur, crystal, gems, gold; //gain / loss of resources
-	unsigned char players; //players for whom this event can be applied
-	bool forHuman, forComputer;
-	int firstShow; //postpone of first encounter time in days
-	int forEvery; //every n days this event will occure
-
-	unsigned char bytes[6]; //build specific buildings (raw format, similar to town's)
-
-	int gen[7]; //additional creatures in i-th level dwelling
-};
-
-class CCastleObjInfo : public CSpecObjInfo //castle class
-{
-public:
-	int x, y, z; //posiotion
-	std::vector<CBuilding> buildings; //buildings we can build in this castle
-	std::vector<bool> isBuild; //isBuild[i] is true, when building buildings[i] has been built
-	std::vector<bool> isLocked; //isLocked[i] is true, when building buildings[i] canot be built
-	bool unusualBuildins; //if true, intrepret bytes below
-	unsigned char buildingSettings[12]; //raw format for two vectors above (greatly depends on town type)
-	bool hasFort; //used only if unusualBuildings is false
-	CHero * visitingHero;
-	CHero * garnisonHero;
-
-	unsigned char bytes[4]; //identifying bytes
-	unsigned char player; //255 - nobody, players 0 - 7
-	std::string name; //town name
-	CCreatureSet garrison;
-
-	std::vector<CSpell *> possibleSpells;
-	std::vector<CSpell *> obligatorySpells;
-	std::vector<CSpell *> availableSpells;
-
-	std::vector<CCastleEvent> events;
-
-	unsigned char alignment; //255 - same as owner/random, 0 - same as red, 1 - same as blue, etc
-};
-
-#endif //CCASTLEHANDLER_H

+ 11 - 458
hch/CCreatureHandler.cpp

@@ -1,6 +1,5 @@
+#define VCMI_DLL
 #include "../stdafx.h"
-#include "../CGameInfo.h"
-#include "CDefHandler.h"
 #include "CCreatureHandler.h"
 #include "CLodHandler.h"
 #include <sstream>
@@ -8,8 +7,12 @@
 #include <boost/algorithm/string.hpp>
 #include <boost/algorithm/string/find.hpp>
 #include <boost/algorithm/string/replace.hpp>
-#include "../SDL_Extensions.h"
-
+#include "../lib/VCMI_Lib.h"
+extern CLodHandler * bitmaph;
+CCreatureHandler::CCreatureHandler()
+{
+	VLC->creh = this;
+}
 int CCreature::getQuantityID(int quantity)
 {
 	if (quantity<5)
@@ -42,25 +45,23 @@ bool CCreature::isFlying()
 {
 	return boost::algorithm::find_first(abilityRefs, "FLYING_ARMY");
 }
-
 bool CCreature::isShooting()
 {
 	return boost::algorithm::find_first(abilityRefs, "SHOOTING_ARMY");
 }
-
-int CCreature::maxAmount(const std::vector<int> &res) const //how many creatures can be bought
+si32 CCreature::maxAmount(const std::vector<si32> &res) const //how many creatures can be bought
 {
 	int ret = 2147483645;
 	int resAmnt = std::min(res.size(),cost.size());
 	for(int i=0;i<resAmnt;i++)
 		if(cost[i])
-			ret = std::min(ret,res[i]/cost[i]);
+			ret = std::min(ret,(int)(res[i]/cost[i]));
 	return ret;
 }
 
 void CCreatureHandler::loadCreatures()
 {
-	std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("ZCRTRAIT.TXT");
+	std::string buf = bitmaph->getTextFile("ZCRTRAIT.TXT");
 	int andame = buf.size();
 	int i=0; //buf iterator
 	int hmcr=0;
@@ -352,19 +353,6 @@ void CCreatureHandler::loadCreatures()
 	ifs.close();
 	ifs.clear();
 
-
-	ifs.open("config/cr_bgs.txt");
-	while(!ifs.eof())
-	{
-		int id;
-		std::string name;
-		ifs >> id >> name;
-		backgrounds[id]=CGI->bitmaph->loadBitmap(name);
-	}
-	ifs.close();
-	ifs.clear();
-
-
 	ifs.open("config/cr_factions.txt");
 	while(!ifs.eof())
 	{
@@ -385,23 +373,6 @@ void CCreatureHandler::loadCreatures()
 	ifs.close();
 	ifs.clear();
 
-	//loading 32x32px imgs
-	CDefHandler *smi = CGI->spriteh->giveDef("CPRSMALL.DEF");
-	smi->notFreeImgs = true;
-	for (int i=0; i<smi->ourImages.size(); i++)
-	{
-		boost::assign::insert(smallImgs)(i-2,smi->ourImages[i].bitmap);
-	}
-	delete smi;
-	smi = CGI->spriteh->giveDef("TWCRPORT.DEF");
-	smi->notFreeImgs = true;
-	for (int i=0; i<smi->ourImages.size(); i++)
-	{
-		boost::assign::insert(bigImgs)(i-2,smi->ourImages[i].bitmap);
-	}
-	delete smi;
-	//
-
 	//loading unit animation def names
 	std::ifstream inp("config/CREDEFS.TXT", std::ios::in | std::ios::binary); //this file is not in lod
 	inp.seekg(0,std::ios::end); // na koniec
@@ -472,7 +443,7 @@ void CCreatureHandler::loadCreatures()
 
 void CCreatureHandler::loadAnimationInfo()
 {
-	std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("CRANIM.TXT");
+	std::string buf = bitmaph->getTextFile("CRANIM.TXT");
 	int andame = buf.size();
 	int i=0; //buf iterator
 	int hmcr=0;
@@ -642,421 +613,3 @@ void CCreatureHandler::loadUnitAnimInfo(CCreature & unit, std::string & src, int
 	}
 	i+=2;
 }
-
-void CCreatureHandler::loadUnitAnimations()
-{
-	//std::ifstream inp("config/CREDEFS.TXT", std::ios::in | std::ios::binary); //this file is not in lod
-	//inp.seekg(0,std::ios::end); // na koniec
-	//int andame = inp.tellg();  // read length
-	//inp.seekg(0,std::ios::beg); // wracamy na poczatek
-	//char * bufor = new char[andame]; // allocate memory
-	//inp.read((char*)bufor, andame); // read map file to buffer
-	//inp.close();
-	//std::string buf = std::string(bufor);
-	//delete [andame] bufor;
-
-	//int i = 0; //buf iterator
-	//int hmcr = 0;
-	//for(i; i<andame; ++i) //omitting rubbish
-	//{
-	//	if(buf[i]=='\r')
-	//		break;
-	//}
-	//i+=2;
-	//for(int s=0; s<creatures.size(); ++s)
-	//{
-	//	int befi=i;
-	//	std::string rub;
-	//	for(i; i<andame; ++i)
-	//	{
-	//		if(buf[i]==' ')
-	//			break;
-	//	}
-	//	rub = buf.substr(befi, i-befi);
-	//	++i;
-
-	//	befi=i;
-	//	for(i; i<andame; ++i)
-	//	{
-	//		if(buf[i]=='\r')
-	//			break;
-	//	}
-	//	std::string defName = buf.substr(befi, i-befi);
-	//	if(defName != std::string("x"))
-	//		creatures[s].battleAnimation = CGameInfo::mainObj->spriteh->giveDef(defName);
-	//	else
-	//		creatures[s].battleAnimation = NULL;
-	//	i+=2;
-	//}
-}
-
-int CCreatureAnimation::getType() const
-{
-	return type;
-}
-
-void CCreatureAnimation::setType(int type)
-{
-	this->type = type;
-	curFrame = 0;
-	if(type!=-1)
-	{
-		if(SEntries[curFrame].group!=type) //rewind
-		{
-			int j=-1; //first frame in displayed group
-			for(int g=0; g<SEntries.size(); ++g)
-			{
-				if(SEntries[g].group==type && j==-1)
-				{
-					j = g;
-					break;
-				}
-			}
-			if(curFrame!=-1)
-				curFrame = j;
-		}
-	}
-	else
-	{
-		if(curFrame>=frames)
-			curFrame = 0;
-	}
-}
-
-CCreatureAnimation::CCreatureAnimation(std::string name) : RLEntries(NULL), RWEntries(NULL)
-{
-	//load main file
-	std::string data2 = CGI->spriteh->getTextFile(name);
-	if(data2.size()==0)
-		throw new std::string("no such def!");
-	FDef = new unsigned char[data2.size()];
-	for(int g=0; g<data2.size(); ++g)
-	{
-		FDef[g] = data2[g];
-	}
-
-	//init anim data
-	int i,j, totalInBlock;
-	char Buffer[13];
-	defName=name;
-	int andame = data2.size();
-	i = 0;
-	DEFType = readNormalNr(i,4); i+=4;
-	fullWidth = readNormalNr(i,4); i+=4;
-	fullHeight = readNormalNr(i,4); i+=4;
-	i=0xc;
-	totalBlocks = readNormalNr(i,4); i+=4;
-
-	i=0x10;
-	for (int it=0;it<256;it++)
-	{
-		palette[it].R = FDef[i++];
-		palette[it].G = FDef[i++];
-		palette[it].B = FDef[i++];
-		palette[it].F = 0;
-	}
-	i=0x310;
-	totalEntries=0;
-	for (int z=0; z<totalBlocks; z++)
-	{
-		int unknown1 = readNormalNr(i,4); i+=4;
-		totalInBlock = readNormalNr(i,4); i+=4;
-		for (j=SEntries.size(); j<totalEntries+totalInBlock; j++)
-			SEntries.push_back(SEntry());
-		int unknown2 = readNormalNr(i,4); i+=4;
-		int unknown3 = readNormalNr(i,4); i+=4;
-		for (j=0; j<totalInBlock; j++)
-		{
-			for (int k=0;k<13;k++) Buffer[k]=FDef[i+k];
-			i+=13;
-			SEntries[totalEntries+j].name=Buffer;
-		}
-		for (j=0; j<totalInBlock; j++)
-		{
-			SEntries[totalEntries+j].offset = readNormalNr(i,4);
-			int unknown4 = readNormalNr(i,4); i+=4;
-		}
-		//totalEntries+=totalInBlock;
-		for(int hh=0; hh<totalInBlock; ++hh)
-		{
-			SEntries[totalEntries].group = z;
-			++totalEntries;
-		}
-	}
-	for(j=0; j<SEntries.size(); ++j)
-	{
-		SEntries[j].name = SEntries[j].name.substr(0, SEntries[j].name.find('.')+4);
-	}
-	//pictures don't have to be readed here
-	//for(int i=0; i<SEntries.size(); ++i)
-	//{
-	//	Cimage nimg;
-	//	nimg.bitmap = getSprite(i);
-	//	nimg.imName = SEntries[i].name;
-	//	nimg.groupNumber = SEntries[i].group;
-	//	ourImages.push_back(nimg);
-	//}
-	//delete FDef;
-	//FDef = NULL;
-
-	//init vars
-	curFrame = 0;
-	type = -1;
-	frames = totalEntries;
-}
-
-int CCreatureAnimation::readNormalNr (int pos, int bytCon, unsigned char * str, bool cyclic)
-{
-	int ret=0;
-	int amp=1;
-	if (str)
-	{
-		for (int i=0; i<bytCon; i++)
-		{
-			ret+=str[pos+i]*amp;
-			amp*=256;
-		}
-	}
-	else
-	{
-		for (int i=0; i<bytCon; i++)
-		{
-			ret+=FDef[pos+i]*amp;
-			amp*=256;
-		}
-	}
-	if(cyclic && bytCon<4 && ret>=amp/2)
-	{
-		ret = ret-amp;
-	}
-	return ret;
-}
-int CCreatureAnimation::nextFrameMiddle(SDL_Surface *dest, int x, int y, bool attacker, bool incrementFrame, bool yellowBorder, SDL_Rect * destRect)
-{
-	return nextFrame(dest,x-fullWidth/2,y-fullHeight/2,attacker,incrementFrame,yellowBorder,destRect);
-}
-int CCreatureAnimation::nextFrame(SDL_Surface *dest, int x, int y, bool attacker, bool incrementFrame, bool yellowBorder, SDL_Rect * destRect)
-{
-	if(dest->format->BytesPerPixel<3)
-		return -1; //not enough depth
-
-	//increasing frame numer
-	int SIndex = -1;
-	if(incrementFrame)
-	{
-		SIndex = curFrame++;
-		if(type!=-1)
-		{
-			if(SEntries[curFrame].group!=type) //rewind
-			{
-				int j=-1; //first frame in displayed group
-				for(int g=0; g<SEntries.size(); ++g)
-				{
-					if(SEntries[g].group==type && j==-1)
-					{
-						j = g;
-						break;
-					}
-				}
-				if(curFrame!=-1)
-					curFrame = j;
-			}
-		}
-		else
-		{
-			if(curFrame>=frames)
-				curFrame = 0;
-		}
-	}
-	else
-	{
-		SIndex = curFrame;
-	}
-	//frame number increased
-
-	long BaseOffset,
-		SpriteWidth, SpriteHeight, //sprite format
-		LeftMargin, RightMargin, TopMargin,BottomMargin,
-		i, add, FullHeight,FullWidth,
-		TotalRowLength, // length of read segment
-		RowAdd;
-	unsigned char SegmentType, SegmentLength;
-
-	i=BaseOffset=SEntries[SIndex].offset;
-	int prSize=readNormalNr(i,4,FDef);i+=4;
-	int defType2 = readNormalNr(i,4,FDef);i+=4;
-	FullWidth = readNormalNr(i,4,FDef);i+=4;
-	FullHeight = readNormalNr(i,4,FDef);i+=4;
-	SpriteWidth = readNormalNr(i,4,FDef);i+=4;
-	SpriteHeight = readNormalNr(i,4,FDef);i+=4;
-	LeftMargin = readNormalNr(i,4,FDef);i+=4;
-	TopMargin = readNormalNr(i,4,FDef);i+=4;
-	RightMargin = FullWidth - SpriteWidth - LeftMargin;
-	BottomMargin = FullHeight - SpriteHeight - TopMargin;
-
-	add = 4 - FullWidth%4;
-
-	int BaseOffsetor = BaseOffset = i;
-
-	int ftcp = 0;
-
-	if (defType2==1) //as it should be allways in creature animations
-	{
-		if (TopMargin>0)
-		{
-			for (int i=0;i<TopMargin;i++)
-			{
-				ftcp+=FullWidth+add;
-			}
-		}
-		RLEntries = new int[SpriteHeight];
-		for (int i=0;i<SpriteHeight;i++)
-		{
-			RLEntries[i]=readNormalNr(BaseOffset,4,FDef);BaseOffset+=4;
-		}
-		for (int i=0;i<SpriteHeight;i++)
-		{
-			BaseOffset=BaseOffsetor+RLEntries[i];
-			if (LeftMargin>0)
-			{
-				ftcp+=LeftMargin;
-			}
-			TotalRowLength=0;
-			do
-			{
-				SegmentType=FDef[BaseOffset++];
-				SegmentLength=FDef[BaseOffset++];
-				if (SegmentType==0xFF)
-				{
-					for (int k=0;k<=SegmentLength;k++)
-					{
-						int xB = (attacker ? ftcp%(FullWidth+add) : (FullWidth+add) - ftcp%(FullWidth+add) - 1) + x;
-						int yB = ftcp/(FullWidth+add) + y;
-						if(xB>=0 && yB>=0 && xB<dest->w && yB<dest->h)
-						{
-							if(!destRect || (destRect->x <= xB && destRect->x + destRect->w > xB && destRect->y <= yB && destRect->y + destRect->h > yB))
-								putPixel(dest, xB + yB*dest->w, palette[FDef[BaseOffset+k]], FDef[BaseOffset+k], yellowBorder);
-						}
-						ftcp++; //increment pos
-						if ((TotalRowLength+k+1)>=SpriteWidth)
-							break;
-					}
-					BaseOffset+=SegmentLength+1;////
-					TotalRowLength+=SegmentLength+1;
-				}
-				else
-				{
-					for (int k=0;k<SegmentLength+1;k++)
-					{
-						int xB = (attacker ? ftcp%(FullWidth+add) : (FullWidth+add) - ftcp%(FullWidth+add) - 1) + x;
-						int yB = ftcp/(FullWidth+add) + y;
-						if(xB>=0 && yB>=0 && xB<dest->w && yB<dest->h)
-						{
-							if(!destRect || (destRect->x <= xB && destRect->x + destRect->w > xB && destRect->y <= yB && destRect->y + destRect->h > yB))
-								putPixel(dest, xB + yB*dest->w, palette[SegmentType], SegmentType, yellowBorder);
-						}
-						ftcp++; //increment pos
-					}
-					TotalRowLength+=SegmentLength+1;
-				}
-			}while(TotalRowLength<SpriteWidth);
-			RowAdd=SpriteWidth-TotalRowLength;
-			if (RightMargin>0)
-			{
-				ftcp+=RightMargin;
-			}
-			if (add>0)
-			{
-				ftcp+=add+RowAdd;
-			}
-		}
-		delete [] RLEntries;
-		RLEntries = NULL;
-		if (BottomMargin>0)
-		{
-			ftcp += BottomMargin * (FullWidth+add);
-		}
-	}
-
-	//SDL_UpdateRect(dest, x, y, FullWidth+add, FullHeight);
-
-	return 0;
-}
-
-int CCreatureAnimation::framesInGroup(int group) const
-{
-	int ret = 0; //number of frames in given group
-	for(int g=0; g<SEntries.size(); ++g)
-	{
-		if(SEntries[g].group == group)
-			++ret;
-	}
-	return ret;
-}
-
-CCreatureAnimation::~CCreatureAnimation()
-{
-	delete [] FDef;
-	if (RWEntries)
-		delete [] RWEntries;
-	if (RLEntries)
-		delete [] RLEntries;
-}
-
-void CCreatureAnimation::putPixel(SDL_Surface * dest, const int & ftcp, const BMPPalette & color, const unsigned char & palc, const bool & yellowBorder) const
-{
-	if(palc!=0)
-	{
-		Uint8 * p = (Uint8*)dest->pixels + ftcp*3;
-		if(palc > 7) //normal color
-		{
-			p[0] = color.B;
-			p[1] = color.G;
-			p[2] = color.R;
-		}
-		else if(yellowBorder && (palc == 6 || palc == 7)) //dark yellow border
-		{
-			p[0] = 0;
-			p[1] = 0xff;
-			p[2] = 0xff;
-		}
-		else if(yellowBorder && (palc == 5)) //yellow border
-		{
-			p[0] = color.B;
-			p[1] = color.G;
-			p[2] = color.R;
-		}
-		else if(palc < 5) //shadow
-		{
-			Uint16 alpha;
-			switch(color.G)
-			{
-			case 0:
-				alpha = 128;
-				break;
-			case 50:
-				alpha = 50+32;
-				break;
-			case 100:
-				alpha = 100+64;
-				break;
-			case 125:
-				alpha = 125+64;
-				break;
-			case 128:
-				alpha = 128+64;
-				break;
-			case 150:
-				alpha = 150+64;
-				break;
-			default:
-				alpha = 255;
-				break;
-			}
-			//alpha counted
-			p[0] = (p[0] * alpha)>>8;
-			p[1] = (p[1] * alpha)>>8;
-			p[2] = (p[2] * alpha)>>8;
-		}
-	}
-}

+ 11 - 67
hch/CCreatureHandler.h

@@ -1,16 +1,14 @@
 #ifndef CCREATUREHANDLER_H
 #define CCREATUREHANDLER_H
-
-#include "../CPlayerInterface.h"
+#include "../global.h"
 #include <string>
 #include <vector>
 #include <map>
-#include "CDefHandler.h"
+#include <set>
 
-class CDefHandler;
-struct SDL_Surface;
+class CLodHandler;
 
-class CCreature
+class DLL_EXPORT CCreature
 {
 public:
 	std::string namePl, nameSing, nameRef; //name in singular and plural form; and reference name
@@ -23,7 +21,7 @@ public:
 	std::string abilityText; //description of abilities
 	std::string abilityRefs; //references to abilities, in textformat
 	std::string animDefName;
-	int idNumber;
+	ui32 idNumber;
 	int faction; //-1 = neutral
 
 	///animation info
@@ -37,32 +35,20 @@ public:
 	bool isDefinite; //if the creature type is wotn dependent, it should be true
 	int indefLevel; //only if indefinite
 	bool indefUpgraded; //onlu if inddefinite
-	//end
-	//CDefHandler * battleAnimation;
-	//TODO - zdolnoœci - na typie wyliczeniowym czy czymœ
 
-	static int getQuantityID(int quantity); //0 - a few, 1 - several, 2 - pack, 3 - lots, 4 - horde, 5 - throng, 6 - swarm, 7 - zounds, 8 - legion
+	//TODO - zdolnoœci (abilities) - na typie wyliczeniowym czy czymœ - albo lepiej secie czegoœ
+
 	bool isDoubleWide(); //returns true if unit is double wide on battlefield
 	bool isFlying(); //returns true if it is a flying unit
 	bool isShooting(); //returns true if unit can shoot
-	int maxAmount(const std::vector<int> &res) const; //how many creatures can be bought
+	si32 maxAmount(const std::vector<si32> &res) const; //how many creatures can be bought
+	static int getQuantityID(int quantity); //0 - a few, 1 - several, 2 - pack, 3 - lots, 4 - horde, 5 - throng, 6 - swarm, 7 - zounds, 8 - legion
 };
 
-class CCreatureSet //seven combined creatures
-{
-public:
-	std::map<int,std::pair<CCreature*,int> > slots;
-	//CCreature * slot1, * slot2, * slot3, * slot4, * slot5, * slot6, * slot7; //types of creatures on each slot
-	//unsigned int s1, s2, s3, s4, s5, s6, s7; //amounts of units in slots
-	bool formation; //false - wide, true - tight
-};
 
-class CCreatureHandler
+class DLL_EXPORT CCreatureHandler
 {
 public:
-	std::map<int,SDL_Surface*> smallImgs; //creature ID -> small 32x32 img of creature; //ID=-2 is for blank (black) img; -1 for the border
-	std::map<int,SDL_Surface*> bigImgs; //creature ID -> big 58x64 img of creature; //ID=-2 is for blank (black) img; -1 for the border
-	std::map<int,SDL_Surface*> backgrounds; //castle ID -> 100x130 background creature image // -1 is for neutral
 	std::vector<CCreature> creatures; //creature ID -> creature info
 	std::map<int,std::vector<CCreature*> > levelCreatures; //level -> list of creatures
 	std::map<std::string,int> nameToID;
@@ -71,48 +57,6 @@ public:
 	void loadCreatures();
 	void loadAnimationInfo();
 	void loadUnitAnimInfo(CCreature & unit, std::string & src, int & i);
-	void loadUnitAnimations();
+	CCreatureHandler();
 };
-
-class CCreatureAnimation : public CIntObject
-{
-private:
-	int totalEntries, DEFType, totalBlocks;
-	bool allowRepaint;
-	int length;
-	BMPPalette palette[256];
-	unsigned int * RWEntries;
-	int * RLEntries;
-	struct SEntry
-	{
-		std::string name;
-		int offset;
-		int group;
-	} ;
-	std::vector<SEntry> SEntries ;
-	char id[2];
-	std::string defName, curDir;
-	int readNormalNr (int pos, int bytCon, unsigned char * str=NULL, bool cyclic=false);
-	void putPixel(SDL_Surface * dest, const int & ftcp, const BMPPalette & color, const unsigned char & palc, const bool & yellowBorder) const;
-
-	////////////
-
-	unsigned char * FDef; //animation raw data
-	unsigned int curFrame; //number of currently displayed frame
-	unsigned int frames; //number of frames
-	int type; //type of animation being displayed (-1 - whole animation, >0 - specified part [default: -1])
-public:
-	int fullWidth, fullHeight; //read-only, please!
-	CCreatureAnimation(std::string name); //c-tor
-	~CCreatureAnimation(); //d-tor
-
-	void setType(int type); //sets type of animation and cleares framecount
-	int getType() const; //returns type of animation
-
-	int nextFrame(SDL_Surface * dest, int x, int y, bool attacker, bool incrementFrame = true, bool yellowBorder = false, SDL_Rect * destRect = NULL); //0 - success, any other - error //print next
-	int nextFrameMiddle(SDL_Surface * dest, int x, int y, bool attacker, bool incrementFrame = true, bool yellowBorder = false, SDL_Rect * destRect = NULL); //0 - success, any other - error //print next
-
-	int framesInGroup(int group) const; //retirns number of fromes in given group
-};
-
 #endif //CCREATUREHANDLER_H

+ 24 - 21
hch/CDefHandler.cpp

@@ -1,7 +1,9 @@
 #include "../stdafx.h"
+#include "SDL.h"
 #include "CDefHandler.h"
 #include <sstream>
-
+#include "CLodHandler.h"
+CLodHandler* CDefHandler::Spriteh = NULL;
 long long pow(long long a, int b)
 {
 	if (!b) return 1;
@@ -10,24 +12,6 @@ long long pow(long long a, int b)
 		a*=c;
 	return a;
 }
-void BMPHeader::print(std::ostream & out)
-{
-	CDefHandler::print(out,fullSize,4);
-	CDefHandler::print(out,_h1,4);
-	CDefHandler::print(out,_c1,4);
-	CDefHandler::print(out,_c2,4);
-	CDefHandler::print(out,x,4);
-	CDefHandler::print(out,y,4);
-	CDefHandler::print(out,_c3,2);
-	CDefHandler::print(out,_c4,2);
-	CDefHandler::print(out,_h2,4);
-	CDefHandler::print(out,_h3,4);
-	CDefHandler::print(out,dataSize1,4);
-	CDefHandler::print(out,dataSize2,4);
-	for (int i=0;i<8;i++)
-		out << _c5[i];
-	out.flush();
-}
 CDefHandler::CDefHandler()
 {
 	//FDef = NULL;
@@ -133,12 +117,11 @@ void CDefHandler::openDef(std::string name)
 	FDef = NULL;
 }
 
-void CDefHandler::openFromMemory(unsigned char *table, int size, std::string name)
+void CDefHandler::openFromMemory(unsigned char *table, std::string name)
 {
 	int i,j, totalInBlock;
 	char Buffer[13];
 	defName=name;
-	int andame = size;
 	i = 0;
 	DEFType = readNormalNr(i,4,table); i+=4;
 	fullWidth = readNormalNr(i,4,table); i+=4;
@@ -576,3 +559,23 @@ CDefEssential * CDefHandler::essentialize()
 	notFreeImgs = true;
 	return ret;
 }
+
+CDefHandler * CDefHandler::giveDef(std::string defName, CLodHandler * spriteh)
+{
+	if(!spriteh) spriteh=Spriteh;
+	unsigned char * data = spriteh->giveFile(defName);
+	CDefHandler * nh = new CDefHandler();
+	nh->openFromMemory(data, defName);
+	nh->alphaTransformed = false;
+	delete [] data;
+	return nh;
+}
+CDefEssential * CDefHandler::giveDefEss(std::string defName, CLodHandler * spriteh)
+{
+	CDefEssential * ret;
+	CDefHandler * temp = giveDef(defName,spriteh);
+	ret = temp->essentialize();
+	delete temp;
+	return ret;
+}
+

+ 63 - 76
hch/CDefHandler.h

@@ -1,76 +1,63 @@
-#ifndef CDEFHANDLER_H
-#define CDEFHANDLER_H
-
-#include "SDL.h"
-#include "CSemiDefHandler.h"
-
-class CDefEssential;
-
-struct BMPHeader
-{
-	int fullSize, _h1, _h2, _h3, _c1, _c2, _c3, _c4, x, y,
-		dataSize1, dataSize2; //DataSize=X*Y+2*Y
-	unsigned char _c5[8];
-	void print(std::ostream & out);
-	BMPHeader(){_h1=_h2=0;for(int i=0;i<8;i++)_c5[i]=0;};
-};/*
-struct DEFHeader
-{
-	int type, width, height, groups;
-	unsigned char palette[767];
-};
-struct DEFGroup
-{
-	int ID, items, unknown1, unknown2;
-};*/
-
-struct BMPPalette
-{
-	unsigned char R,G,B,F;
-};
-
-class CDefHandler
-{
-private:
-	int totalEntries, DEFType, totalBlocks, fullWidth, fullHeight;
-	bool allowRepaint;
-	int length;
-	BMPPalette palette[256];
-	unsigned int * RWEntries;
-	int * RLEntries;
-	struct SEntry
-	{
-		std::string name;
-		int offset;
-		int group;
-	} ;
-	std::vector<SEntry> SEntries ;
-	char id[2];
-
-
-public:
-	std::string defName, curDir;
-	std::vector<Cimage> ourImages;
-	bool alphaTransformed;
-	bool notFreeImgs;
-
-	CDefHandler();
-	~CDefHandler();
-	static void print (std::ostream & stream, int nr, int bytcon);
-	int readNormalNr (int pos, int bytCon, unsigned char * str=NULL, bool cyclic=false);
-	static unsigned char *writeNormalNr (int nr, int bytCon);
-	SDL_Surface * getSprite (int SIndex, unsigned char * FDef); //zapisuje klatke o zadanym numerze do "testtt.bmp"
-	void openDef(std::string name);
-	void expand(unsigned char N,unsigned char & BL, unsigned char & BR);
-	void openFromMemory(unsigned char * table, int size, std::string name);
-	CDefEssential * essentialize();
-};
-
-class CDefEssential //DefHandler with images only
-{
-public:
-	std::vector<Cimage> ourImages;
-	~CDefEssential();
-};
-
-#endif // CDEFHANDLER_H
+#ifndef CDEFHANDLER_H
+#define CDEFHANDLER_H
+#include "../client/CBitmapHandler.h"
+struct SDL_Surface;
+class CDefEssential;
+class CLodHandler;
+
+struct Cimage
+{
+	int groupNumber;
+	std::string imName; //name without extension
+	SDL_Surface * bitmap;
+};
+
+class CDefHandler
+{
+private:
+	int totalEntries, DEFType, totalBlocks, fullWidth, fullHeight;
+	bool allowRepaint;
+	int length;
+	BMPPalette palette[256];
+	unsigned int * RWEntries;
+	int * RLEntries;
+	struct SEntry
+	{
+		std::string name;
+		int offset;
+		int group;
+	} ;
+	std::vector<SEntry> SEntries ;
+	char id[2];
+
+
+public:
+	static CLodHandler * Spriteh;
+	std::string defName, curDir;
+	std::vector<Cimage> ourImages;
+	bool alphaTransformed;
+	bool notFreeImgs;
+
+	CDefHandler();
+	~CDefHandler();
+	static void print (std::ostream & stream, int nr, int bytcon);
+	int readNormalNr (int pos, int bytCon, unsigned char * str=NULL, bool cyclic=false);
+	static unsigned char *writeNormalNr (int nr, int bytCon);
+	SDL_Surface * getSprite (int SIndex, unsigned char * FDef); //zapisuje klatke o zadanym numerze do "testtt.bmp"
+	void openDef(std::string name);
+	void expand(unsigned char N,unsigned char & BL, unsigned char & BR);
+	void openFromMemory(unsigned char * table, std::string name);
+	CDefEssential * essentialize();
+
+	static CDefHandler * giveDef(std::string defName, CLodHandler * spriteh=NULL);
+	static CDefEssential * giveDefEss(std::string defName, CLodHandler * spriteh=NULL);
+};
+
+class CDefEssential //DefHandler with images only
+{
+public:
+	std::vector<Cimage> ourImages;
+	~CDefEssential();
+};
+
+#endif // CDEFHANDLER_H

+ 8 - 20
hch/CDefObjInfoHandler.cpp

@@ -1,9 +1,11 @@
+#define VCMI_DLL
 #include "../stdafx.h"
 #include "CDefObjInfoHandler.h"
 #include "../CGameInfo.h"
 #include "CLodHandler.h"
 #include <sstream>
-
+#include "../lib/VCMI_Lib.h"
+extern CLodHandler * bitmaph;
 bool CGDefInfo::isVisitable()
 {
 	for (int i=0; i<6; i++)
@@ -17,15 +19,11 @@ CGDefInfo::CGDefInfo()
 {
 	visitDir = (8|16|32|64|128); //4,5,6,7,8 - any not-from-up direction
 }
-bool DefObjInfo::operator==(const std::string & por) const
-{
-	return this->defName == por;
-}
-
 void CDefObjInfoHandler::load()
 {
+	VLC->dobjinfo = this;
 	nodrze<int> ideki;
-	std::istringstream inp(CGameInfo::mainObj->bitmaph->getTextFile("ZOBJCTS.TXT"));
+	std::istringstream inp(bitmaph->getTextFile("ZOBJCTS.TXT"));
 	int objNumber;
 	inp>>objNumber;
 	for(int hh=0; hh<objNumber; ++hh)
@@ -62,8 +60,8 @@ void CDefObjInfoHandler::load()
 			}
 		}
 
-		for(int yy=0; yy<2; ++yy)
-			inp>>dump;
+		for(int yy=0; yy<2; ++yy) //first - on which types of terrain object can be placed; 
+			inp>>dump; //second -in which terrains' menus object in the editor will be available (?)
 		inp>>nobj->id;
 		inp>>nobj->subid;
 		inp>>nobj->type;
@@ -72,14 +70,4 @@ void CDefObjInfoHandler::load()
 		if(nobj->id==98)
 			castles[nobj->subid]=nobj;
 	}
-}
-
-bool DefObjInfo::isVisitable() const
-{
-	for(int g=0; g<6; ++g)
-	{
-		if(visitMap[g]!=0)
-			return true;
-	}
-	return false;
-}
+}

+ 6 - 15
hch/CDefObjInfoHandler.h

@@ -2,8 +2,10 @@
 #define COBJINFOECTHANDLER_H
 #include <vector>
 #include <map>
+#include "../global.h"
 class CDefHandler;
-class CGDefInfo
+class CLodHandler;
+class DLL_EXPORT CGDefInfo
 {
 public:
 	std::string name;
@@ -14,7 +16,8 @@ public:
 	int id, subid; //of object described by this defInfo
 	int terrainAllowed, //on which terrain it is possible to place object
 		 terrainMenu; //in which menus in map editor object will be showed
-	int type; //(0- ground, 1- towns, 2-creatures, 3- heroes, 4-artifacts, 5- resources)
+	int width, height; //tiles
+	int type; //(0- ground, 1- towns, 2-creatures, 3- heroes, 4-artifacts, 5- resources)   
 	CDefHandler * handler;
 	int printPriority;
 	bool isVisitable();
@@ -27,19 +30,7 @@ public:
 	}
 	CGDefInfo();
 };
-struct DefObjInfo
-{
-	std::string defName;
-	int priority;
-	int type, subtype;
-	int objType;
-	unsigned char visitMap[6];
-	unsigned char blockMap[6];
-	bool operator==(const std::string & por) const;
-	bool isVisitable() const;
-};
-
-class CDefObjInfoHandler
+class DLL_EXPORT CDefObjInfoHandler
 {
 public:
 	std::map<int,std::map<int,CGDefInfo*> > gobjs;

+ 6 - 115
hch/CGeneralTextHandler.cpp

@@ -6,7 +6,7 @@
 
 void CGeneralTextHandler::load()
 {
-	std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("GENRLTXT.TXT");
+	std::string buf = CGI->bitmaph->getTextFile("GENRLTXT.TXT");
 	int andame = buf.size();
 	int i=0; //buf iterator
 	for(i; i<andame; ++i)
@@ -29,7 +29,7 @@ void CGeneralTextHandler::load()
 	while(itr<strs.length()-1)
 	{
 		std::string tmp;
-		CGeneralTextHandler::loadToIt(tmp, strs, itr, 3);
+		loadToIt(tmp, strs, itr, 3);
 		arraytxt.push_back(tmp);
 	}
 
@@ -38,7 +38,7 @@ void CGeneralTextHandler::load()
 	for(int hh=0; hh<4; ++hh)
 	{
 		std::string tmp;
-		CGeneralTextHandler::loadToIt(tmp, strin, itr, 3);
+		loadToIt(tmp, strin, itr, 3);
 		primarySkillNames.push_back(tmp);
 	}
 
@@ -47,7 +47,7 @@ void CGeneralTextHandler::load()
 	for(int hh=0; hh<45; ++hh)
 	{
 		std::string tmp;
-		CGeneralTextHandler::loadToIt(tmp, strin2, itr, 3);
+		loadToIt(tmp, strin2, itr, 3);
 		jktexts.push_back(tmp);
 	}
 
@@ -56,116 +56,7 @@ void CGeneralTextHandler::load()
 	for(int hh=0; hh<33; ++hh)
 	{
 		std::string tmp;
-		CGeneralTextHandler::loadToIt(tmp, strin3, itr, 3);
+		loadToIt(tmp, strin3, itr, 3);
 		heroscrn.push_back(tmp);
 	}
-}
-
-
-void CGeneralTextHandler::loadToIt(std::string &dest, std::string &src, int &iter, int mode)
-{
-	switch(mode)
-	{
-	case 0:
-		{
-			int hmcr = 0;
-			for(iter; iter<src.size(); ++iter)
-			{
-				if(src[iter]=='\t')
-					++hmcr;
-				if(hmcr==1)
-					break;
-			}
-			++iter;
-
-			int befi=iter;
-			for(iter; iter<src.size(); ++iter)
-			{
-				if(src[iter]=='\t')
-					break;
-			}
-			dest = src.substr(befi, iter-befi);
-			++iter;
-
-			hmcr = 0;
-			for(iter; iter<src.size(); ++iter)
-			{
-				if(src[iter]=='\r')
-					++hmcr;
-				if(hmcr==1)
-					break;
-			}
-			iter+=2;
-			break;
-		}
-	case 1:
-		{
-			int hmcr = 0;
-			for(iter; iter<src.size(); ++iter)
-			{
-				if(src[iter]=='\t')
-					++hmcr;
-				if(hmcr==1)
-					break;
-			}
-			++iter;
-
-			int befi=iter;
-			for(iter; iter<src.size(); ++iter)
-			{
-				if(src[iter]=='\r')
-					break;
-			}
-			dest = src.substr(befi, iter-befi);
-			iter+=2;
-			break;
-		}
-	case 2:
-		{
-			int befi=iter;
-			for(iter; iter<src.size(); ++iter)
-			{
-				if(src[iter]=='\t')
-					break;
-			}
-			dest = src.substr(befi, iter-befi);
-			++iter;
-
-			int hmcr = 0;
-			for(iter; iter<src.size(); ++iter)
-			{
-				if(src[iter]=='\r')
-					++hmcr;
-				if(hmcr==1)
-					break;
-			}
-			iter+=2;
-			break;
-		}
-	case 3:
-		{
-			int befi=iter;
-			for(iter; iter<src.size(); ++iter)
-			{
-				if(src[iter]=='\r')
-					break;
-			}
-			dest = src.substr(befi, iter-befi);
-			iter+=2;
-			break;
-		}
-	case 4:
-		{
-			int befi=iter;
-			for(iter; iter<src.size(); ++iter)
-			{
-				if(src[iter]=='\t')
-					break;
-			}
-			dest = src.substr(befi, iter-befi);
-			iter++;
-			break;
-		}
-	}
-}
-
+}

+ 2 - 17
hch/CGeneralTextHandler.h

@@ -1,9 +1,9 @@
 #ifndef CGENERALTEXTHANDLER_H
 #define CGENERALTEXTHANDLER_H
-
+#include "../global.h"
 #include <string>
 #include <vector>
-
+DLL_EXPORT void loadToIt(std::string &dest, std::string &src, int &iter, int mode);
 class CGeneralTextHandler //Handles general texts
 {
 public:
@@ -13,21 +13,6 @@ public:
 	std::vector<std::string> primarySkillNames;
 	std::vector<std::string> jktexts;
 	std::vector<std::string> heroscrn;
-	/*std::string cantAddManager, experienceLimitScenarioReached, heroExperienceInfo, perDay, or, somethingVanquished, lastTownLostInfo, heroesAbandonedYou, heroesAbandonedHim;
-	std::string couldNotSaveGame, errorOpeningFile, newgameUppercase, sureToDismissArmy, playersTurn, errorReceivingDataKeepTrying, somethingTheSomething, recruit, noRoomInGarrision, numberOFAdventuringHeroes, heroWithoutCreatures;
-	std::string videoQuality, itemCantBeTraded, sureDismissHero, selectSpellTarget, invalidTeleportDestination, teleportHere, castSomething, castSomethingOnSomething, sureRetreat, notEnoughGold, capturedEnemyArtifact, none;
-	std::string surrenderProposal, highMoraleNextAttack, lowMoraleFreeze, makeRoomInArmyForSomething, attackSomethingSomethingDamage, shootSomethingOneShootLeftSomethingDamage;
-	std::string campaignDescription, somethingIsActive, sessionName, userName, creature, creatures, badLuckOnSomething, goodLuckOnSomething, treasure, somethingSomethingsUnderAttack, town, hero, townScreen, cannotBuildBoat, requires, systemUppercase;
-	std::string worldMapHelp, sureEndTurnHeroMayMove, diggingArtifactWholeDay, noRoomForArtifact, heroUncoveredThe, diggingNothing, tryLookingOnLand, unchartedTerritory;
-	std::string month, week, day, enemyViewTip, pingInfo, sureToRestart, sureToStartNewGame, sureQuit, dimensionDoorFiled, chooseBonus, ping, pingSomething, pingEveryone, score, autosaveUppercase;
-	std::string startingHeroB, heroSpecialityB, associatedCreaturesB, townAlignmentB, errorSendingDataKeepTrying, tooFewPalyersForMultiGame, artifactBonusB, goldBonusB, resourceBonusB, randomBonusB;
-	std::string fiveHundredToOneThousand, armageddonDamages, woodOreBonus, randomlyChoosenArtifact, disruptingRayReducesDefence, goldStartingBonus, woodOreStartingBonus, randomStartingBonus;
-	std::string youEliminatedFormGame, scoreToHallOfFame, trySearchingOnClearGround, sendingData, receivingData, chaosMp2, randomHeroB, randomStartingHeroInfo, randomTownB, randomStartingTownInfo, somethingSurrendersInfo;
-	std::string heroesCDNotFound, autosaving, playerexitUppercase, statusWindowTip, border, somethingAbsorbsMana, somethingsAbsorbMana, unableChangeHeroesDirectory, unableFindHeoresDataFiles, victoryAchievementText;
-	std::string somethingsRiseFromDeath, somethingRisesFormDeath, somethingDiesUnderGaze, somethingsDieUnderGaze, somethingTakesDefensiveStance, somethingsTakeDefensiveStance, somethingExp, nearestTownOccupied, noAvailableTown, heroTooTiredSpell, townGateCannotBeUsed, youHaveNoHeroes, heroHasCastSpell;
-	std::string doYouWishToSaveSomethingsArmy, problemsWithInputDevices, problemsWithSound, problemsWithMouse, problemsWithWindows, abandonedShipyard, spellFailed, somethingPauses, somethingsPause, somethingLevelSomething, somethingStudiedMagic, learnsSpeced, andSpaced, fromSomethingSpaced;*/
-
-	static void loadToIt(std::string & dest, std::string & src, int & iter, int mode = 0); //mode 0 - dump to tab, dest to tab, dump to eol //mode 1 - dump to tab, src to eol //mode 2 - copy to tab, dump to eol //mode 3 - copy to eol //mode 4 - copy to tab
 	void load();
 };
 

+ 43 - 147
hch/CHeroHandler.cpp

@@ -1,81 +1,60 @@
+#define VCMI_DLL
 #include "../stdafx.h"
 #include "CHeroHandler.h"
-#include "../CGameInfo.h"
 #include <sstream>
-#include "../CGameInfo.h"
-#include "CGeneralTextHandler.h"
 #include "CLodHandler.h"
-#include "CAbilityHandler.h"
-#include "../SDL_Extensions.h"
-#include <cmath>
-#include <iomanip>
+#include "../lib/VCMI_Lib.h"
+extern CLodHandler * bitmaph;
+void loadToIt(std::string &dest, std::string &src, int &iter, int mode);
 
-CHeroHandler::~CHeroHandler()
+CHeroClass::CHeroClass()
 {
-	for (int j=0;j<heroes.size();j++)
-	{
-		delete heroes[j];
-	}
-	for(std::map<int, SDL_Surface*>::iterator it = smallPortraits.begin(); it!=smallPortraits.end(); ++it)
+	skillLimit = 8;
+}
+CHeroClass::~CHeroClass()
+{
+}
+int CHeroClass::chooseSecSkill(std::set<int> possibles) //picks secondary skill out from given possibilities
+{
+	if(possibles.size()==1)
+		return *possibles.begin();
+	int totalProb = 0;
+	for(std::set<int>::iterator i=possibles.begin(); i!=possibles.end(); i++)
 	{
-		delete it->second;
+		totalProb += proSec[*i];
 	}
-	for(std::map<int, SDL_Surface*>::iterator it = largePortraits.begin(); it!=largePortraits.end(); ++it)
+	int ran = rand()%totalProb;
+	for(std::set<int>::iterator i=possibles.begin(); i!=possibles.end(); i++)
 	{
-		delete it->second;
+		ran -= proSec[*i];
+		if(ran<0)
+			return *i;
 	}
 }
+
+CHeroHandler::~CHeroHandler()
+{}
 void CHeroHandler::loadPortraits()
 {
-	std::ifstream of("config/portrety.txt");
-	int numberOfPortraits;
-	of>>numberOfPortraits;
-	for (int j=0; j<numberOfPortraits; j++)
-	{
-		int ID;
-		of>>ID;
-		std::string path;
-		of>>path;
-		smallPortraits[ID] = CGI->bitmaph->loadBitmap(path);
-		if (!smallPortraits[ID])
-			std::cout<<"Can't read small portrait for "<<ID<<" ("<<path<<")\n";
-		for(int ff=0; ff<path.size(); ++ff) //size letter is usually third one, but there are exceptions an it should fix the problem
-		{
-			if(path[ff]=='S')
-			{
-				path[ff]='L';
-				break;
-			}
-		}
-		largePortraits[ID] = CGI->bitmaph->loadBitmap(path);
-		if (!largePortraits[ID])
-			std::cout<<"Can't read large portrait for "<<ID<<" ("<<path<<")\n";	
-		SDL_SetColorKey(largePortraits[ID],SDL_SRCCOLORKEY,SDL_MapRGB(largePortraits[ID]->format,0,255,255));
-
-	}
-	of.close();
-	pskillsb = CGI->spriteh->giveDef("PSKILL.DEF");
-	resources = CGI->spriteh->giveDef("RESOUR82.DEF");
-	un44 = CGI->spriteh->giveDef("UN44.DEF");
-
-	std::string  strs = CGI->bitmaph->getTextFile("PRISKILL.TXT");
+	std::string  strs = bitmaph->getTextFile("PRISKILL.TXT");
 	int itr=0;
 	for (int i=0; i<PRIMARY_SKILLS; i++)
 	{
 		std::string tmp;
-		CGeneralTextHandler::loadToIt(tmp, strs, itr, 3);
+		loadToIt(tmp, strs, itr, 3);
 		pskillsn.push_back(tmp);
 	}
 }
 void CHeroHandler::loadHeroes()
 {
+	VLC->heroh = this;
 	int ID=0;
-	std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("HOTRAITS.TXT");
+	std::string buf = bitmaph->getTextFile("HOTRAITS.TXT");
 	int it=0;
 	std::string dump;
 	for(int i=0; i<2; ++i)
 	{
-		CGeneralTextHandler::loadToIt(dump,buf,it,3);
+		loadToIt(dump,buf,it,3);
 	}
 
 	int numberOfCurrentClassHeroes = 0;
@@ -115,15 +94,15 @@ void CHeroHandler::loadHeroes()
 		}
 
 		std::string pom ;
-		CGeneralTextHandler::loadToIt(nher->name,buf,it,4);
+		loadToIt(nher->name,buf,it,4);
 
 		for(int x=0;x<3;x++)
 		{
-			CGeneralTextHandler::loadToIt(pom,buf,it,4);
+			loadToIt(pom,buf,it,4);
 			nher->lowStack[x] = atoi(pom.c_str());
-			CGeneralTextHandler::loadToIt(pom,buf,it,4);
+			loadToIt(pom,buf,it,4);
 			nher->highStack[x] = atoi(pom.c_str());
-			CGeneralTextHandler::loadToIt(nher->refTypeStack[x],buf,it,(x==2) ? (3) : (4));
+			loadToIt(nher->refTypeStack[x],buf,it,(x==2) ? (3) : (4));
 			int hlp = nher->refTypeStack[x].find_first_of(' ',0);
 			if(hlp>=0)
 				nher->refTypeStack[x].replace(hlp,1,"");
@@ -156,34 +135,34 @@ void CHeroHandler::loadHeroes()
 }
 void CHeroHandler::loadSpecialAbilities()
 {
-	std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("HEROSPEC.TXT");
+	std::string buf = bitmaph->getTextFile("HEROSPEC.TXT");
 	int it=0;
 	std::string dump;
 	for(int i=0; i<2; ++i)
 	{
-		CGeneralTextHandler::loadToIt(dump,buf,it,3);
+		loadToIt(dump,buf,it,3);
 	}
 	for (int i=0;i<heroes.size();i++)
 	{
-		CGeneralTextHandler::loadToIt(heroes[i]->bonusName,buf,it,4);
-		CGeneralTextHandler::loadToIt(heroes[i]->shortBonus,buf,it,4);
-		CGeneralTextHandler::loadToIt(heroes[i]->longBonus,buf,it,3);
+		loadToIt(heroes[i]->bonusName,buf,it,4);
+		loadToIt(heroes[i]->shortBonus,buf,it,4);
+		loadToIt(heroes[i]->longBonus,buf,it,3);
 	}
 }
 
 void CHeroHandler::loadBiographies()
 {	
-	std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("HEROBIOS.TXT");
+	std::string buf = bitmaph->getTextFile("HEROBIOS.TXT");
 	int it=0;
 	for (int i=0;i<heroes.size();i++)
 	{
-		CGeneralTextHandler::loadToIt(heroes[i]->biography,buf,it,3);
+		loadToIt(heroes[i]->biography,buf,it,3);
 	}
 }
 
 void CHeroHandler::loadHeroClasses()
 {
-	std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("HCTRAITS.TXT");
+	std::string buf = bitmaph->getTextFile("HCTRAITS.TXT");
 	int andame = buf.size();
 	for(int y=0; y<andame; ++y)
 		if(buf[y]==',')
@@ -281,7 +260,7 @@ void CHeroHandler::loadHeroClasses()
 
 		//CHero kkk = heroes[0];
 
-		for(int dd=0; dd<CGameInfo::mainObj->abilh->abilities.size(); ++dd)
+		for(int dd=0; dd<SKILL_QUANTITY; ++dd)
 		{
 			befi=i;
 			for(i; i<andame; ++i)
@@ -306,89 +285,6 @@ void CHeroHandler::loadHeroClasses()
 			++i;
 		}
 		++i;
-		std::stringstream nm;
-		nm<<"AH";
-		nm<<std::setw(2);
-		nm<<std::setfill('0');
-		nm<<heroClasses.size();
-		nm<<"_.DEF";
-		hc->moveAnim = CGI->spriteh->giveDef(nm.str());
-
-		for(int o=0; o<hc->moveAnim->ourImages.size(); ++o)
-		{
-			if(hc->moveAnim->ourImages[o].groupNumber==6)
-			{
-				for(int e=0; e<8; ++e)
-				{
-					Cimage nci;
-					nci.bitmap = CSDL_Ext::rotate01(hc->moveAnim->ourImages[o+e].bitmap);
-					nci.groupNumber = 10;
-					nci.imName = std::string();
-					hc->moveAnim->ourImages.push_back(nci);
-				}
-				o+=8;
-			}
-			if(hc->moveAnim->ourImages[o].groupNumber==7)
-			{
-				for(int e=0; e<8; ++e)
-				{
-					Cimage nci;
-					nci.bitmap = CSDL_Ext::rotate01(hc->moveAnim->ourImages[o+e].bitmap);
-					nci.groupNumber = 11;
-					nci.imName = std::string();
-					hc->moveAnim->ourImages.push_back(nci);
-				}
-				o+=8;
-			}
-			if(hc->moveAnim->ourImages[o].groupNumber==8)
-			{
-				for(int e=0; e<8; ++e)
-				{
-					Cimage nci;
-					nci.bitmap = CSDL_Ext::rotate01(hc->moveAnim->ourImages[o+e].bitmap);
-					nci.groupNumber = 12;
-					nci.imName = std::string();
-					hc->moveAnim->ourImages.push_back(nci);
-				}
-				o+=8;
-			}
-		}
-		for(int o=0; o<hc->moveAnim->ourImages.size(); ++o)
-		{
-			if(hc->moveAnim->ourImages[o].groupNumber==1)
-			{
-				Cimage nci;
-				nci.bitmap = CSDL_Ext::rotate01(hc->moveAnim->ourImages[o].bitmap);
-				nci.groupNumber = 13;
-				nci.imName = std::string();
-				hc->moveAnim->ourImages.push_back(nci);
-				//o+=1;
-			}
-			if(hc->moveAnim->ourImages[o].groupNumber==2)
-			{
-				Cimage nci;
-				nci.bitmap = CSDL_Ext::rotate01(hc->moveAnim->ourImages[o].bitmap);
-				nci.groupNumber = 14;
-				nci.imName = std::string();
-				hc->moveAnim->ourImages.push_back(nci);
-				//o+=1;
-			}
-			if(hc->moveAnim->ourImages[o].groupNumber==3)
-			{
-				Cimage nci;
-				nci.bitmap = CSDL_Ext::rotate01(hc->moveAnim->ourImages[o].bitmap);
-				nci.groupNumber = 15;
-				nci.imName = std::string();
-				hc->moveAnim->ourImages.push_back(nci);
-				//o+=1;
-			}
-		}
-
-		for(int ff=0; ff<hc->moveAnim->ourImages.size(); ++ff)
-		{
-			CSDL_Ext::alphaTransform(hc->moveAnim->ourImages[ff].bitmap);
-		}
-		hc->moveAnim->alphaTransformed = true;
 		heroClasses.push_back(hc);
 	}
 }

+ 10 - 24
hch/CHeroHandler.h

@@ -1,19 +1,14 @@
 #ifndef CHEROHANDLER_H
 #define CHEROHANDLER_H
-
+#include "../global.h"
 #include <string>
 #include <vector>
-#include "CCreatureHandler.h"
-#include "SDL.h"
-#include "../int3.h"
-#include "CAmbarCendamo.h"
-#include "../CGameInterface.h"
-
+#include <set>
 class CHeroClass;
 class CDefHandler;
 class CGameInfo;
 class CGHeroInstance;
-class CHero
+class DLL_EXPORT CHero
 {
 public:
 	std::string name;
@@ -28,9 +23,10 @@ public:
 	//bool operator<(CHero& drugi){if (ID < drugi.ID) return true; else return false;}
 };
 
-class CHeroClass
+class DLL_EXPORT CHeroClass
 {
 public:
+	ui32 skillLimit; //how many secondary skills can hero learn
 	std::string name;
 	float aggression;
 	int initialAttack, initialDefence, initialPower, initialKnowledge;
@@ -39,18 +35,16 @@ public:
 	int selectionProbability[9]; //probability of selection in towns
 	std::vector<int> terrCosts; //default costs of going through terrains: dirt, sand, grass, snow, swamp, rough, subterrain, lava, water, rock; -1 means terrain is imapassable
 	CDefHandler * moveAnim; //added group 10: up - left, 11 - left and 12 - left down // 13 - up-left standing; 14 - left standing; 15 - left down standing
+	int chooseSecSkill(std::set<int> possibles); //picks secondary skill out from given possibilities
+	CHeroClass();
+	~CHeroClass();
 };
 
-class CHeroHandler
+class DLL_EXPORT CHeroHandler
 {
 public:
-	std::vector<CGHeroInstance *> heroInstances;
 	std::vector<CHero*> heroes; //by³o nodrze
 	std::vector<CHeroClass *> heroClasses;
-	std::vector<CDefHandler *> flags1, flags2, flags3, flags4; //flags blitted on heroes when ,
-	std::map<int, SDL_Surface *> smallPortraits, largePortraits; //there are more portraits than playable heroes! ; small - 48x32 px ; large - 58x64 px
-	CDefHandler * pskillsb, *resources; //82x93
-	CDefHandler * un44; //many things
 	std::vector<std::string> pskillsn;
 	std::vector<int> expPerLevel; //expPerLEvel[i] is amount of exp needed to reach level i; if it is not in this vector, multiplicate last value by 1,2 to get next value
 	unsigned int level(unsigned int experience);
@@ -59,17 +53,9 @@ public:
 	void loadSpecialAbilities();
 	void loadBiographies();
 	void loadHeroClasses();
-	void loadPortraits(); //loads also imgs and names of primary skills
+	void loadPortraits(); //loads names of primary skills
 	void initHeroClasses();
 	~CHeroHandler();
 	void initTerrainCosts();
-
-	friend void CAmbarCendamo::deh3m();
-	friend void initGameState(CGameInfo * cgi);
-	//friend class CConsoleHandler;
-
-	//friend void CPlayerInterface::heroMoved(const HeroMoveDetails & details); //TODO: wywalic, wstretne!!!
 };
-
-
 #endif //CHEROHANDLER_H

+ 56 - 549
hch/CLodHandler.cpp

@@ -1,14 +1,16 @@
+#define VCMI_DLL
 #include "../stdafx.h"
+#include "zlib.h"
 #include "CLodHandler.h"
-#include "../SDL_Extensions.h"
-#include "CDefHandler.h"
 #include <sstream>
 #include <algorithm>
 #include <cctype>
 #include <cstring>
-#include "boost/filesystem.hpp"   // includes all needed Boost.Filesystem declarations
-#include "SDL_image.h"
-int readNormalNr (int pos, int bytCon, unsigned char * str)
+#include "boost/filesystem/operations.hpp"
+#include <boost/algorithm/string.hpp>
+#include <boost/algorithm/string/replace.hpp>
+#include <boost/thread.hpp>
+DLL_EXPORT int readNormalNr (int pos, int bytCon, unsigned char * str)
 {
 	int ret=0;
 	int amp=1;
@@ -23,505 +25,50 @@ int readNormalNr (int pos, int bytCon, unsigned char * str)
 	else return -1;
 	return ret;
 }
-void CPCXConv::openPCX(char * PCX, int len)
-{
-	pcxs=len;
-	pcx=(unsigned char*)PCX;
-	/*pcx = new unsigned char[len];
-	for (int i=0;i<len;i++)
-		pcx[i]=PCX[i];*/
-}
-void CPCXConv::fromFile(std::string path)
-{
-	std::ifstream * is = new std::ifstream();
-	is -> open(path.c_str(),std::ios::binary);
-	is->seekg(0,std::ios::end); // to the end
-	pcxs = is->tellg();  // read length
-	is->seekg(0,std::ios::beg); // wracamy na poczatek
-	pcx = new unsigned char[pcxs]; // allocate memory
-	is->read((char*)pcx, pcxs); // read map file to buffer
-	is->close();
-	delete is;
-}
-void CPCXConv::saveBMP(std::string path)
-{
-	std::ofstream os;
-	os.open(path.c_str(), std::ios::binary);
-	os.write((char*)bmp,bmps);
-	os.close();
-}
-void CPCXConv::convert()
-{
-	BMPHeader bh;
-	BMPPalette pal[256];
-	Epcxformat format;
-	int fSize,i,y;
-	bool check1, check2;
-	unsigned char add;
-	int it=0;
-
-	std::stringstream out;
-
-	fSize = readNormalNr(it,4,pcx);it+=4;
-	bh.x = readNormalNr(it,4,pcx);it+=4;
-	bh.y = readNormalNr(it,4,pcx);it+=4;
-	if (fSize==bh.x*bh.y*3)
-		check1=true;
-	else
-		check1=false;
-	if (fSize==bh.x*bh.y)
-		check2=true;
-	else
-		check2=false;
-	if (check1)
-		format=PCX24B;
-	else if (check2)
-		format=PCX8B;
-	else
-		return;
-	add = 4 - bh.x%4;
-	if (add==4)
-		add=0;
-	bh._h3=bh.x*bh.y;
-	if (format==PCX8B)
-	{
-		bh._c1=0x436;
-		bh._c2=0x28;
-		bh._c3=1;
-		bh._c4=8;
-		//bh.dataSize2=bh.dataSize1=maxx*maxy;
-		bh.dataSize1=bh.x;
-		bh.dataSize2=bh.y;
-		bh.fullSize = bh.dataSize1+436;
-	}
-	else
-	{
-		bh._c1=0x36;
-		bh._c2=0x28;
-		bh._c3=1;
-		bh._c4=0x18;
-		//bh.dataSize2=bh.dataSize1=0xB12;
-		bh.dataSize1=bh.x;
-		bh.dataSize2=bh.y;
-		bh.fullSize=(bh.x+add)*bh.y*3+36+18;
-		bh._h3*=3;
-	}
-	if (format==PCX8B)
-	{
-		it = pcxs-256*3;
-		for (int i=0;i<256;i++)
-		{
-			pal[i].R=pcx[it++];
-			pal[i].G=pcx[it++];
-			pal[i].B=pcx[it++];
-			pal[i].F='\0';
-		}
-	}
-	out<<"BM";
-	bh.print(out);
-	if (format==PCX8B)
-	{
-		for (int i=0;i<256;i++)
-		{
-			out<<pal[i].B;
-			out<<pal[i].G;
-			out<<pal[i].R;
-			out<<pal[i].F;
-		}
-		for (y=bh.y;y>0;y--)
-		{
-			it=0xC+(y-1)*bh.x;
-			for (int j=0;j<bh.x;j++)
-				out<<pcx[it+j];
-			if (add>0)
-			{
-				for (int j=0;j<add;j++)
-					out<<'\0'; //bylo z buforu, ale onnie byl incjalizowany (?!)
-			}
-		}
-	}
-	else
-	{
-		for (y=bh.y; y>0; y--)
-		{
-			it=0xC+(y-1)*bh.x*3;
-			for (int j=0;j<bh.x*3;j++)
-				out<<pcx[it+j];
-			if (add>0)
-			{
-				for (int j=0;j<add*3;j++)
-					out<<'\0'; //bylo z buforu, ale onnie byl incjalizowany (?!)
-			}
-		}
-	}
-	std::string temp = out.str();
-	bmp = new unsigned char[temp.length()];
-	bmps=temp.length();
-	for (int a=0;a<temp.length();a++)
-	{
-		bmp[a]=temp[a];
-	}
-}
-
-SDL_Surface * CPCXConv::getSurface()
-{
-	SDL_Surface * ret;
-
-	BMPHeader bh;
-	Epcxformat format;
-	int fSize,i,y;
-	bool check1, check2;
-	unsigned char add;
-	int it=0;
-
-	fSize = readNormalNr(it,4,pcx);it+=4;
-	bh.x = readNormalNr(it,4,pcx);it+=4;
-	bh.y = readNormalNr(it,4,pcx);it+=4;
-	if (fSize==bh.x*bh.y*3)
-		check1=true;
-	else
-		check1=false;
-	if (fSize==bh.x*bh.y)
-		check2=true;
-	else
-		check2=false;
-	if (check1)
-		format=PCX24B;
-	else if (check2)
-		format=PCX8B;
-	else
-		return NULL;
-	add = 4 - bh.x%4;
-	if (add==4)
-		add=0;
-	if (format==PCX8B)
-	{
-		ret = SDL_CreateRGBSurface(SDL_SWSURFACE, bh.x+add, bh.y, 8, 0, 0, 0, 0);
-	}
-	else
-	{
-#if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
-		int bmask = 0xff0000;
-		int gmask = 0x00ff00;
-		int rmask = 0x0000ff;
-#else
-		int bmask = 0x0000ff;
-		int gmask = 0x00ff00;
-		int rmask = 0xff0000;
-#endif
-		ret = SDL_CreateRGBSurface(SDL_SWSURFACE, bh.x+add, bh.y, 24, rmask, gmask, bmask, 0);
-	}
-	if (format==PCX8B)
-	{
-		it = pcxs-256*3;
-		for (int i=0;i<256;i++)
-		{
-			SDL_Color tp;
-#if (SDL_BYTEORDER == SDL_BIG_ENDIAN)
-			tp.b = pcx[it++];
-			tp.g = pcx[it++];
-			tp.r = pcx[it++];
-#else
-			tp.r = pcx[it++];
-			tp.g = pcx[it++];
-			tp.b = pcx[it++];
-#endif
-			tp.unused = 0;
-			*(ret->format->palette->colors+i) = tp;
-		}
-		for (y=bh.y;y>0;y--)
-		{
-			it=0xC+(y-1)*bh.x;
-			for (int j=0;j<bh.x;j++)
-			{
-				*((char*)ret->pixels + ret->pitch * (y-1) + ret->format->BytesPerPixel * j) = pcx[it+j];
-			}
-			if (add>0)
-			{
-				for (int j=0;j<add;j++)
-				{
-					*((char*)ret->pixels + ret->pitch * (y-1) + ret->format->BytesPerPixel * (j+bh.x)) = 0;
-				}
-			}
-		}
-	}
-	else
-	{
-		for (y=bh.y; y>0; y--)
-		{
-			it=0xC+(y-1)*bh.x*3;
-			for (int j=0;j<bh.x*3;j++)
-			{
-				*((char*)ret->pixels + ret->pitch * (y-1) + j) = pcx[it+j];
-			}
-			if (add>0)
-			{
-				for (int j=0;j<add*3;j++)
-				{
-					*((char*)ret->pixels + ret->pitch * (y-1) + (j+bh.x*3)) = 0;
-				}
-			}
-		}
-	}
-	return ret;
-}
-
-SDL_Surface * CLodHandler::loadBitmap(std::string fname)
-{
-	if(!fname.size())
-		return NULL;
-	unsigned char * pcx;
-	std::transform(fname.begin(),fname.end(),fname.begin(),toupper);
-	fname.replace(fname.find_first_of('.'),fname.find_first_of('.')+4,".PCX");
-	Entry *e = entries.znajdz(fname);
-	if(!e)
-	{
-		std::cout<<"File "<<fname<<" not found"<<std::endl;
-		return NULL;
-	}
-	if(e->offset<0)
-	{
-		fname.replace(fname.find_first_of('.'),fname.find_first_of('.')+4,".BMP");
-		fname = "Data/"+fname;
-		FILE * f = fopen(fname.c_str(),"r");
-		if(f)
-		{
-			fclose(f);
-			return SDL_LoadBMP(fname.c_str());
-		}
-		else  //file .bmp not present, check .pcx
-		{
-			char sign[3];
-			fname.replace(fname.find_first_of('.'),fname.find_first_of('.')+4,".PCX");
-			f = fopen(fname.c_str(),"r");
-			if(!f)
-				return NULL;
-			fread(sign,1,3,f);
-			if(sign[0]=='B' && sign[1]=='M') //BMP named as PCX - people (eg. Kulex) sometimes use such files
-			{
-				fclose(f);
-				return SDL_LoadBMP(fname.c_str());
-			}
-			else //PCX - but we don't know which
-			{
-				if((sign[0]==10) && (sign[1]<6) && (sign[2]==1)) //ZSoft PCX
-				{
-					fclose(f);
-					return IMG_Load(fname.c_str());
-				}
-				else //H3-style PCX
-				{
-					CPCXConv cp;
-					pcx = new unsigned char[e->realSize];
-					memcpy(pcx,sign,3);
-					int res = fread((char*)pcx+3, 1, e->realSize-3, f);
-					fclose(f);
-					cp.openPCX((char*)pcx,e->realSize);
-					return cp.getSurface();
-				}
-			}
-		}
-	}
-	fseek(FLOD, e->offset, 0);
-	if (e->size==0) //file is not compressed
-	{
-		pcx = new unsigned char[e->realSize];
-		fread((char*)pcx, 1, e->realSize, FLOD);
-	}
-	else
-	{
-		unsigned char * pcd = new unsigned char[e->size];
-		fread((char*)pcd, 1, e->size, FLOD);
-		int res=infs2(pcd,e->size,e->realSize,pcx);
-		if(res!=0)
-		{
-			std::cout<<"an error "<<res<<" occured while extracting file "<<fname<<std::endl;
-		}
-		delete [] pcd;
-	}
-	CPCXConv cp;
-	cp.openPCX((char*)pcx,e->realSize);
-	return cp.getSurface();
-}
-
-int CLodHandler::decompress (unsigned char * source, int size, int realSize, std::string & dest)
-{
-	std::ofstream lb;
-	lb.open(DATADIR "lodbuf" PATHSEPARATOR "buf.gz", std::ios::out|std::ios::binary);
-	for(int i=0; i<size; ++i)
-	{
-		lb<<source[i];
-	}
-	lb.close();
-
-	FILE * inputf = fopen(DATADIR "lodbuf" PATHSEPARATOR "buf.gz", "rb+");
-	FILE * outputf = fopen(dest.c_str(), "wb+");
-
-	int ret = infm(inputf, outputf);
-	fclose(inputf);
-	fclose(outputf);
-	return ret;
-}
-
-int CLodHandler::infm(FILE *source, FILE *dest, int wBits)
-{
-	int ret;
-	unsigned have;
-	z_stream strm;
-	unsigned char in[NLoadHandlerHelp::fCHUNK];
-	unsigned char out[NLoadHandlerHelp::fCHUNK];
-
-	/* allocate inflate state */
-	strm.zalloc = Z_NULL;
-	strm.zfree = Z_NULL;
-	strm.opaque = Z_NULL;
-	strm.avail_in = 0;
-	strm.next_in = Z_NULL;
-	ret = inflateInit2(&strm, wBits);
-	if (ret != Z_OK)
-		return ret;
-
-	/* decompress until deflate stream ends or end of file */
-	do
-	{
-		strm.avail_in = fread(in, 1, NLoadHandlerHelp::fCHUNK, source);
-		if (ferror(source)) {
-			(void)inflateEnd(&strm);
-			return Z_ERRNO;
-		}
-		if (strm.avail_in == 0)
-			break;
-		strm.next_in = in;
-
-		/* run inflate() on input until output buffer not full */
-		do
-		{
-			strm.avail_out = NLoadHandlerHelp::fCHUNK;
-			strm.next_out = out;
-			ret = inflate(&strm, Z_NO_FLUSH);
-			//assert(ret != Z_STREAM_ERROR);  /* state not clobbered */
-			switch (ret)
-			{
-				case Z_NEED_DICT:
-					ret = Z_DATA_ERROR;	 /* and fall through */
-				case Z_DATA_ERROR:
-				case Z_MEM_ERROR:
-					(void)inflateEnd(&strm);
-					return ret;
-			}
-			have = NLoadHandlerHelp::fCHUNK - strm.avail_out;
-			if (fwrite(out, 1, have, dest) != have || ferror(dest))
-			{
-				(void)inflateEnd(&strm);
-				return Z_ERRNO;
-			}
-		} while (strm.avail_out == 0);
-
-		/* done when inflate() says it's done */
-	} while (ret != Z_STREAM_END);
-
-	/* clean up and return */
-	(void)inflateEnd(&strm);
-	return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
-}
-CDefHandler * CLodHandler::giveDef(std::string defName)
+unsigned char * CLodHandler::giveFile(std::string defName, int * length)
 {
 	std::transform(defName.begin(), defName.end(), defName.begin(), (int(*)(int))toupper);
 	Entry * ourEntry = entries.znajdz(Entry(defName));
 	if(!ourEntry) //nothing's been found
 	{
-		std::cerr<<"No def: "<<defName;
-		throw(std::string("Bad def name!"));
+		std::cerr<<"Cannot find file: "<<defName;
+		return NULL;
 	}
-	CDefHandler * ret;
+	if(length) *length = ourEntry->realSize;
+	mutex->lock();
 	fseek(FLOD, ourEntry->offset, 0);
 	unsigned char * outp;
-	if (ourEntry->offset<0) //file in the sprites/ folder
+	if (ourEntry->offset<0) //file is in the sprites/ folder; no compression
 	{
-		char * outp = new char[ourEntry->realSize];
-		char name[120];for(int i=0;i<120;i++) name[i]='\0';
+		unsigned char * outp = new unsigned char[ourEntry->realSize];
+		char name[30];memset(name,0,30);
 		strcat(name,"Sprites/");
 		strcat(name,(char*)ourEntry->name);
 		FILE * f = fopen(name,"rb");
 		int result = fread(outp,1,ourEntry->realSize,f);
+		mutex->unlock();
 		if(result<0) {std::cout<<"Error in file reading: "<<name<<std::endl;delete[] outp; return NULL;}
-		CDefHandler * nh = new CDefHandler();
-		nh->openFromMemory((unsigned char*)outp, ourEntry->realSize, std::string((char*)ourEntry->name));
-		nh->alphaTransformed = false;
-		ret = nh;
-		delete[] outp;
+		else
+			return outp;
 	}
 	else if (ourEntry->size==0) //file is not compressed
 	{
 		outp = new unsigned char[ourEntry->realSize];
 		fread((char*)outp, 1, ourEntry->realSize, FLOD);
-		CDefHandler * nh = new CDefHandler();
-		nh->openFromMemory(outp, ourEntry->realSize, std::string((char*)ourEntry->name));
-		nh->alphaTransformed = false;
-		ret = nh;
-		delete[] outp;
+		mutex->unlock();
+		return outp;
 	}
 	else //we will decompress file
 	{
 		outp = new unsigned char[ourEntry->size];
 		fread((char*)outp, 1, ourEntry->size, FLOD);
-		fseek(FLOD, 0, 0);
+		mutex->unlock();
 		unsigned char * decomp = NULL;
 		int decRes = infs2(outp, ourEntry->size, ourEntry->realSize, decomp);
-		CDefHandler * nh = new CDefHandler();
-		nh->openFromMemory(decomp, ourEntry->realSize, std::string((char*)ourEntry->name));
-		nh->alphaTransformed = false;
-		ret = nh;
-		delete[] decomp;
 		delete[] outp;
+		return decomp;
 	}
-	return ret;
-}
-CDefEssential * CLodHandler::giveDefEss(std::string defName)
-{
-	CDefEssential * ret;
-	CDefHandler * temp = giveDef(defName);
-	ret = temp->essentialize();
-	delete temp;
-	return ret;
-}
-std::vector<CDefHandler *> CLodHandler::extractManyFiles(std::vector<std::string> defNamesIn)
-{
-	std::vector<CDefHandler *> ret(defNamesIn.size());
-	for(int hh=0; hh<defNamesIn.size(); ++hh)
-	{
-		//std::transform(defNamesIn[hh].begin(), defNamesIn[hh].end(), defNamesIn[hh].begin(), (int(*)(int))toupper);
-		Entry * e = entries.znajdz(defNamesIn[hh]);
-		if(!e)
-			continue;
-
-		fseek(FLOD, e->offset, 0);
-		unsigned char * outp;
-		if (e->size==0) //file is not compressed
-		{
-			outp = new unsigned char[e->realSize];
-			fread((char*)outp, 1, e->realSize, FLOD);
-			CDefHandler * nh = new CDefHandler;
-			nh->openFromMemory(outp, e->realSize, std::string((char*)e->name));
-			nh->alphaTransformed = false;
-			ret[hh] = nh;
-		}
-		else //we will decompressing file
-		{
-			outp = new unsigned char[e->size];
-			fread((char*)outp, 1, e->size, FLOD);
-			fseek(FLOD, 0, 0);
-			unsigned char * decomp = NULL;
-			int decRes = infs2(outp, e->size, e->realSize, decomp);
-			CDefHandler * nh = new CDefHandler;
-			nh->openFromMemory(decomp, e->realSize, std::string((char*)e->name));
-			nh->alphaTransformed = false;
-			delete [] decomp;
-			ret[hh] = nh;
-		}
-		delete[] outp;
-	}
-	return ret;
+	return NULL;
 }
 int CLodHandler::infs(unsigned char * in, int size, int realSize, std::ofstream & out, int wBits)
 {
@@ -599,7 +146,7 @@ int CLodHandler::infs(unsigned char * in, int size, int realSize, std::ofstream
 	return ret == Z_STREAM_END ? Z_OK : Z_DATA_ERROR;
 }
 
-int CLodHandler::infs2(unsigned char * in, int size, int realSize, unsigned char *& out, int wBits)
+DLL_EXPORT int CLodHandler::infs2(unsigned char * in, int size, int realSize, unsigned char *& out, int wBits)
 {
 	int ret;
 	unsigned have;
@@ -629,12 +176,6 @@ int CLodHandler::infs2(unsigned char * in, int size, int realSize, unsigned char
 		}
 		++chunkNumber;
 		strm.avail_in = readBytes;
-		//strm.avail_in = fread(inx, 1, NLoadHandlerHelp::fCHUNK, source);
-		/*if (in.bad())
-		{
-			(void)inflateEnd(&strm);
-			return Z_ERRNO;
-		}*/
 		if (strm.avail_in == 0)
 			break;
 		strm.next_in = inx;
@@ -656,22 +197,11 @@ int CLodHandler::infs2(unsigned char * in, int size, int realSize, unsigned char
 					return ret;
 			}
 			have = NLoadHandlerHelp::fCHUNK - strm.avail_out;
-			/*if (fwrite(out, 1, have, dest) != have || ferror(dest))
-			{
-				(void)inflateEnd(&strm);
-				return Z_ERRNO;
-			}*/
-			//out.write((char*)outx, have);
 			for(int oo=0; oo<have; ++oo)
 			{
 				out[latPosOut] = outx[oo];
 				++latPosOut;
 			}
-			/*if(out.bad())
-			{
-				(void)inflateEnd(&strm);
-				return Z_ERRNO;
-			}*/
 		} while (strm.avail_out == 0);
 
 		/* done when inflate() says it's done */
@@ -684,15 +214,11 @@ int CLodHandler::infs2(unsigned char * in, int size, int realSize, unsigned char
 
 void CLodHandler::extract(std::string FName)
 {
-
 	std::ofstream FOut;
-	int i;
-
-	//std::cout<<" done\n";
 	for (int i=0;i<totalFiles;i++)
 	{
 		fseek(FLOD, entries[i].offset, 0);
-		std::string bufff = (DATADIR + FName.substr(0, FName.size()-4) + PATHSEPARATOR + (char*)entries[i].name);
+		std::string bufff = (DATA_DIR + FName.substr(0, FName.size()-4) + PATHSEPARATOR + (char*)entries[i].name);
 		unsigned char * outp;
 		if (entries[i].size==0) //file is not compressed
 		{
@@ -799,8 +325,9 @@ int CLodHandler::readNormalNr (unsigned char* bufor, int bytCon, bool cyclic)
 	return ret;
 }
 
-void CLodHandler::init(std::string lodFile)
+void CLodHandler::init(std::string lodFile, std::string dirName)
 {
+	mutex = new boost::mutex;
 	std::string Ts;
 	FLOD = fopen(lodFile.c_str(), "rb");
 	fseek(FLOD, 8, 0);
@@ -844,56 +371,36 @@ void CLodHandler::init(std::string lodFile)
 		}
 		entries.push_back(entry);
 	}
+	boost::filesystem::directory_iterator enddir;
+	if(boost::filesystem::exists(dirName))
+	{
+		for (boost::filesystem::directory_iterator dir(dirName);dir!=enddir;dir++)
+		{
+			if(boost::filesystem::is_regular(dir->status()))
+			{
+				std::string name = dir->path().leaf();
+				std::transform(name.begin(), name.end(), name.begin(), (int(*)(int))toupper);
+				boost::algorithm::replace_all(name,".BMP",".PCX");
+				Entry * e = entries.znajdz(name);
+				if(e)
+				{
+					e->offset = -1;
+					e->realSize = e->size = boost::filesystem::file_size(dir->path());
+				}
+			}
+		}
+	}
+	else
+		std::cout<<"Warning: No "+dirName+"/ folder!"<<std::endl;
 }
-
 std::string CLodHandler::getTextFile(std::string name)
 {
-	std::string ret0;
-	std::transform(name.begin(), name.end(), name.begin(), (int(*)(int))toupper);
-	Entry *e;
-	e = entries.znajdz(name);
-	if(!e)
-	{
-		std::cout << "Error: cannot load "<<name<<" from the .lod file!"<<std::endl;
-		return ret0;
-	}
-	if(e->offset<0)
-	{
-		char * outp = new char[e->realSize];
-		char name[120];for(int i=0;i<120;i++) name[i]='\0';
-		strcat(name,"Data/");
-		strcat(name,(char*)e->name);
-		FILE * f = fopen(name,"rb");
-		int result = fread(outp,1,e->realSize,f);
-		if(result<0) {std::cout<<"Error in file reading: "<<name<<std::endl;return ret0;}
-		for (int itr=0;itr<e->realSize;itr++)
-			ret0+= *(outp+itr);
-		delete[] outp;
-		return ret0;
-	}
-	fseek(FLOD, e->offset, 0);
-	unsigned char * outp;
-	if (e->size==0) //file is not compressed
-	{
-		outp = new unsigned char[e->realSize];
-		fread((char*)outp, 1, e->realSize, FLOD);
-		std::string ret = std::string((char*)outp);
-		delete[] outp;
-		return ret;
-	}
-	else //we will decompressing file
-	{
-		outp = new unsigned char[e->size];
-		fread((char*)outp, 1, e->size, FLOD);
-		fseek(FLOD, 0, 0);
-		unsigned char * decomp = NULL;
-		int decRes = infs2(outp, e->size, e->realSize, decomp);
-		std::string ret;
-		for (int itr=0;itr<e->realSize;itr++)
-			ret+= *((char*)decomp+itr);
-		delete[] outp;
-		delete[] decomp;
-		return ret;
-	}
-	return ret0;
+	int length=-1;
+	unsigned char* data = giveFile(name,&length);
+	std::string ret;
+	ret.reserve(length);
+	for(int i=0;i<length;i++)
+		ret+=data[i];
+	delete [] data;
+	return ret;
 }

+ 8 - 33
hch/CLodHandler.h

@@ -1,20 +1,16 @@
 #ifndef CLODHANDLER_H
 #define CLODHANDLER_H
-
-#include <iostream>
+#include "../global.h"
 #include <fstream>
 #include <vector>
 #include <string>
-#include "zlib.h"
 #include "../nodrze.h"
-#include "SDL.h"
-
 
+struct SDL_Surface;
 class CDefHandler;
 class CDefEssential;
-
-enum Epcxformat {PCX8B, PCX24B};
-
+namespace boost
+{class mutex;};
 namespace NLoadHandlerHelp
 {
 	const int dmHelp=0, dmNoExtractingMask=1;
@@ -43,43 +39,22 @@ struct Entry
 	//Entry(unsigned char ): nameStr(con){};
 	Entry(){};
 };
-class CPCXConv
+ class DLL_EXPORT CLodHandler
 {
 public:
-	unsigned char * pcx, *bmp;
-	int pcxs, bmps;
-	void fromFile(std::string path);
-	void saveBMP(std::string path);
-	void openPCX(char * PCX, int len);
-	void openPCX();
-	void convert();
-	SDL_Surface * getSurface(); //for standard H3 PCX
-	//SDL_Surface * getSurfaceZ(); //for ZSoft PCX
-	CPCXConv(){pcx=bmp=NULL;pcxs=bmps=0;};
-	~CPCXConv(){if (pcxs) delete[] pcx; if(bmps) delete[] bmp;}
-};
-class CLodHandler
-{
-private:
 	FILE* FLOD;
-public:
 	nodrze<Entry> entries;
 	unsigned int totalFiles;
+	boost::mutex *mutex;
 
 	int readNormalNr (unsigned char* bufor, int bytCon, bool cyclic=false); //lod header reading helper
-	int decompress (unsigned char * source, int size, int realSize, std::ofstream & dest); //main decompression function
-	int decompress (unsigned char * source, int size, int realSize, std::string & dest); //main decompression function
-	int infm(FILE *source, FILE *dest, int wBits = 15); //zlib handler
 	int infs(unsigned char * in, int size, int realSize, std::ofstream & out, int wBits=15); //zlib fast handler
 	int infs2(unsigned char * in, int size, int realSize, unsigned char*& out, int wBits=15); //zlib fast handler
-	std::vector<CDefHandler *> extractManyFiles(std::vector<std::string> defNamesIn); //extrats given files (defs only)
-	CDefHandler * giveDef(std::string defName);
-	CDefEssential * giveDefEss(std::string defName);
+	unsigned char * giveFile(std::string defName, int * length=NULL); //returns pointer to the decompressed data - it must be deleted when no longer needed!
 	std::string getTextFile(std::string name); //extracts one file
 	void extract(std::string FName);
 	void extractFile(std::string FName, std::string name); //extracts a specific file
-	void init(std::string lodFile);
-	SDL_Surface * loadBitmap(std::string fname);
+	void init(std::string lodFile, std::string dirName);
 };
 
 #endif //CLODHANDLER_H

+ 45 - 45
hch/CMusicHandler.cpp

@@ -12,53 +12,53 @@ void CMusicHandler::initMusics()
 	}
 	atexit(Mix_CloseAudio);
 
-	AITheme0 = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "AITheme0.mp3");
-	AITheme1 = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "AITHEME1.mp3");
-	AITheme2 = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "AITHEME2.mp3");
-	buildTown = Mix_LoadWAV("MP3" PATHSEPARATOR "BUILDTWN.wav");
-	combat1 = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "COMBAT01.mp3");
-	combat2 = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "COMBAT02.mp3");
-	combat3 = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "COMBAT03.mp3");
-	combat4 = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "COMBAT04.mp3");
-	castleTown = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "CstleTown.mp3");
-	defendCastle = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "Defend Castle.mp3");
-	dirt = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "DIRT.mp3");
-	dungeon = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "DUNGEON.mp3");
-	elemTown = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "ElemTown.mp3");
-	evilTheme = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "EvilTheme.mp3");
-	fortressTown = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "FortressTown.mp3");
-	goodTheme = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "GoodTheme.mp3");
-	grass = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "GRASS.mp3");
-	infernoTown = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "InfernoTown.mp3");
-	lava = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "LAVA.mp3");
-	loopLepr = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "LoopLepr.mp3");
-	loseCampain = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "Lose Campain.mp3");
-	loseCastle = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "LoseCastle.mp3");
-	loseCombat = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "LoseCombat.mp3");
-	mainMenu = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "MAINMENU.mp3");
-	mainMenuWoG = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "MainMenuWoG.mp3");
-	necroTown = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "necroTown.mp3");
-	neutralTheme = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "NeutralTheme.mp3");
-	rampart = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "RAMPART.mp3");
-	retreatBattle = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "Retreat Battle.mp3");
-	rough = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "ROUGH.mp3");
-	sand = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "SAND.mp3");
-	secretTheme = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "SecretTheme.mp3");
-	snow = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "SNOW.mp3");
-	stronghold = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "StrongHold.mp3");
-	surrenderBattle = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "Surrender Battle.mp3");
-	swamp = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "SWAMP.mp3");
-	towerTown = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "TowerTown.mp3");
-	ultimateLose = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "UltimateLose.mp3");
-	underground = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "Underground.mp3");
-	water = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "WATER.mp3");
-	winBattle = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "Win Battle.mp3");
-	winScenario = Mix_LoadMUS(DATADIR "MP3" PATHSEPARATOR "Win Scenario.mp3");
+	//AITheme0 = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "AITheme0.mp3");
+	//AITheme1 = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "AITHEME1.mp3");
+	//AITheme2 = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "AITHEME2.mp3");
+	//buildTown = Mix_LoadWAV("MP3" PATHSEPARATOR "BUILDTWN.wav");
+	//combat1 = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "COMBAT01.mp3");
+	//combat2 = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "COMBAT02.mp3");
+	//combat3 = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "COMBAT03.mp3");
+	//combat4 = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "COMBAT04.mp3");
+	//castleTown = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "CstleTown.mp3");
+	//defendCastle = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "Defend Castle.mp3");
+	//dirt = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "DIRT.mp3");
+	//dungeon = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "DUNGEON.mp3");
+	//elemTown = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "ElemTown.mp3");
+	//evilTheme = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "EvilTheme.mp3");
+	//fortressTown = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "FortressTown.mp3");
+	//goodTheme = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "GoodTheme.mp3");
+	//grass = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "GRASS.mp3");
+	//infernoTown = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "InfernoTown.mp3");
+	//lava = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "LAVA.mp3");
+	//loopLepr = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "LoopLepr.mp3");
+	//loseCampain = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "Lose Campain.mp3");
+	//loseCastle = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "LoseCastle.mp3");
+	//loseCombat = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "LoseCombat.mp3");
+	//mainMenu = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "MAINMENU.mp3");
+	//mainMenuWoG = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "MainMenuWoG.mp3");
+	//necroTown = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "necroTown.mp3");
+	//neutralTheme = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "NeutralTheme.mp3");
+	//rampart = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "RAMPART.mp3");
+	//retreatBattle = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "Retreat Battle.mp3");
+	//rough = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "ROUGH.mp3");
+	//sand = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "SAND.mp3");
+	//secretTheme = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "SecretTheme.mp3");
+	//snow = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "SNOW.mp3");
+	//stronghold = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "StrongHold.mp3");
+	//surrenderBattle = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "Surrender Battle.mp3");
+	//swamp = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "SWAMP.mp3");
+	//towerTown = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "TowerTown.mp3");
+	//ultimateLose = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "UltimateLose.mp3");
+	//underground = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "Underground.mp3");
+	//water = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "WATER.mp3");
+	//winBattle = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "Win Battle.mp3");
+	//winScenario = Mix_LoadMUS(DATA_DIR "MP3" PATHSEPARATOR "Win Scenario.mp3");
 
-	click = Mix_LoadWAV(DATADIR "MP3" PATHSEPARATOR "snd1.wav");
+	click = Mix_LoadWAV(DATA_DIR "MP3" PATHSEPARATOR "snd1.wav");
 	click->volume = 30;
 
-	this->sndh = new CSndHandler(std::string(DATADIR "Data" PATHSEPARATOR "Heroes3.snd"));
+	this->sndh = new CSndHandler(std::string(DATA_DIR "Data" PATHSEPARATOR "Heroes3.snd"));
 }
 
 void CMusicHandler::playClick()
@@ -90,7 +90,7 @@ void CMusicHandler::playLodSnd(std::string sndname)
 	channel = Mix_PlayChannel(-1, chunk, 0);
 	if(channel == -1)
 	{
-		fprintf(stderr, "Unable to play WAV file("DATADIR "Data" PATHSEPARATOR "Heroes3.wav::%s): %s\n",
+		fprintf(stderr, "Unable to play WAV file("DATA_DIR "Data" PATHSEPARATOR "Heroes3.wav::%s): %s\n",
 			sndname.c_str(),Mix_GetError());
 	}
 	ops->close(ops);

+ 43 - 40
hch/CObjectHandler.cpp

@@ -1,72 +1,74 @@
+#define VCMI_DLL
 #include "../stdafx.h"
 #include "CObjectHandler.h"
-#include "../CGameInfo.h"
-#include "CGeneralTextHandler.h"
+#include "CDefObjInfoHandler.h"
 #include "CLodHandler.h"
-#include "CAmbarCendamo.h"
-#include "../mapHandler.h"
 #include "CDefObjInfoHandler.h"
-#include "../CLua.h"
 #include "CHeroHandler.h"
 #include <boost/algorithm/string/replace.hpp>
 #include "CTownHandler.h"
+#include "CArtHandler.h"
+#include "../lib/VCMI_Lib.h"
+DLL_EXPORT void loadToIt(std::string &dest, std::string &src, int &iter, int mode);
+extern CLodHandler * bitmaph;
 void CObjectHandler::loadObjects()
 {
+	VLC->objh = this;
 	int ID=0;
-	std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("OBJNAMES.TXT");
+	std::string buf = bitmaph->getTextFile("OBJNAMES.TXT");
 	int it=0;
 	while (it<buf.length()-1)
 	{
-		CObject nobj;
-		CGeneralTextHandler::loadToIt(nobj.name,buf,it,3);
-		if(nobj.name.size() && (nobj.name[nobj.name.size()-1]==(char)10 || nobj.name[nobj.name.size()-1]==(char)13 || nobj.name[nobj.name.size()-1]==(char)9))
-			nobj.name = nobj.name.substr(0, nobj.name.size()-1);
-		objects.push_back(nobj);
+		std::string nobj;
+		loadToIt(nobj,buf,it,3);
+		if(nobj.size() && (nobj[nobj.size()-1]==(char)10 || nobj[nobj.size()-1]==(char)13 || nobj[nobj.size()-1]==(char)9))
+			nobj = nobj.substr(0, nobj.size()-1);
+		names.push_back(nobj);
 	}
 
-	buf = CGameInfo::mainObj->bitmaph->getTextFile("ADVEVENT.TXT");
+	buf = bitmaph->getTextFile("ADVEVENT.TXT");
 	it=0;
 	std::string temp;
 	while (it<buf.length()-1)
 	{
-		CGeneralTextHandler::loadToIt(temp,buf,it,3);
+		loadToIt(temp,buf,it,3);
 		if (temp[0]=='\"')
 			temp = temp.substr(1,temp.length()-2);
 		boost::algorithm::replace_all(temp,"\"\"","\"");
 		advobtxt.push_back(temp);
 	}
 
-	buf = CGameInfo::mainObj->bitmaph->getTextFile("XTRAINFO.TXT");
+	buf = bitmaph->getTextFile("XTRAINFO.TXT");
 	it=0;
 	while (it<buf.length()-1)
 	{
-		CGeneralTextHandler::loadToIt(temp,buf,it,3);
+		loadToIt(temp,buf,it,3);
 		xtrainfo.push_back(temp);
 	}
 
-	buf = CGameInfo::mainObj->bitmaph->getTextFile("MINENAME.TXT");
+	buf = bitmaph->getTextFile("MINENAME.TXT");
 	it=0;
 	while (it<buf.length()-1)
 	{
-		CGeneralTextHandler::loadToIt(temp,buf,it,3);
+		loadToIt(temp,buf,it,3);
 		mines.push_back(std::pair<std::string,std::string>(temp,""));
 	}
 
-	buf = CGameInfo::mainObj->bitmaph->getTextFile("MINEEVNT.TXT");
+	buf = bitmaph->getTextFile("MINEEVNT.TXT");
 	it=0;
 	int i=0;
 	while (it<buf.length()-1)
 	{
-		CGeneralTextHandler::loadToIt(temp,buf,it,3);
+		loadToIt(temp,buf,it,3);
 		temp = temp.substr(1,temp.length()-2);
 		mines[i++].second = temp;
 	}
 
-	buf = CGameInfo::mainObj->bitmaph->getTextFile("RESTYPES.TXT");
+	buf = bitmaph->getTextFile("RESTYPES.TXT");
 	it=0;
 	while (it<buf.length()-1)
 	{
-		CGeneralTextHandler::loadToIt(temp,buf,it,3);
+		loadToIt(temp,buf,it,3);
 		restypes.push_back(temp);
 	}
 
@@ -82,11 +84,11 @@ void CObjectHandler::loadObjects()
 	}
 	ifs.close();
 	ifs.clear();
-	buf = CGameInfo::mainObj->bitmaph->getTextFile("ZCRGN1.TXT");
+	buf = bitmaph->getTextFile("ZCRGN1.TXT");
 	it=0;
 	while (it<buf.length()-1)
 	{
-		CGeneralTextHandler::loadToIt(temp,buf,it,3);
+		loadToIt(temp,buf,it,3);
 		creGens.push_back(temp);
 	}
 
@@ -113,11 +115,11 @@ void CGObjectInstance::setOwner(int ow)
 }
 int CGObjectInstance::getWidth() const//returns width of object graphic in tiles
 {
-	return defInfo->handler->ourImages[0].bitmap->w/32;
+	return defInfo->width;
 }
 int CGObjectInstance::getHeight() const //returns height of object graphic in tiles
 {
-	return defInfo->handler->ourImages[0].bitmap->h/32;
+	return defInfo->width;
 }
 bool CGObjectInstance::visitableAt(int x, int y) const //returns true if ibject is visitable at location (x, y) form left top tile of image (x, y in tiles)
 {
@@ -145,10 +147,6 @@ bool CGObjectInstance::operator<(const CGObjectInstance & cmp) const  //screen p
 		return true;
 	if(!cmp.defInfo->isVisitable() && defInfo->isVisitable())
 		return false;
-	//if(defInfo->isOnDefList && !(cmp.defInfo->isOnDefList))
-	//	return true;
-	//if(cmp.defInfo->isOnDefList && !(defInfo->isOnDefList))
-	//	return false;
 	if(this->pos.x<cmp.pos.x)
 		return true;
 	return false;
@@ -181,8 +179,8 @@ unsigned int CGHeroInstance::getLowestCreatureSpeed()
 	unsigned int sl = 100;
 	for(int h=0; h<army.slots.size(); ++h)
 	{
-		if(army.slots[h].first->speed<sl)
-			sl = army.slots[h].first->speed;
+		if(VLC->creh->creatures[army.slots[h].first].speed<sl)
+			sl = VLC->creh->creatures[army.slots[h].first].speed;
 	}
 	return sl;
 }
@@ -239,7 +237,13 @@ int CGHeroInstance::getSecSkillLevel(const int & ID) const
 			return secSkills[i].second;
 	return -1;
 }
-
+const CArtifact * CGHeroInstance::getArt(int pos)
+{
+	if(artifWorn.find(pos)!=artifWorn.end())
+		return &VLC->arth->artifacts[artifWorn[pos]];
+	else 
+		return NULL;
+}
 
 int CGTownInstance::getSightDistance() const //returns sight distance
 {
@@ -277,7 +281,7 @@ int CGTownInstance::getHordeLevel(const int & HID)  const//HID - 0 or 1; returns
 }
 int CGTownInstance::creatureGrowth(const int & level) const
 {
-	int ret = CGI->creh->creatures[town->basicCreatures[level]].growth;
+	int ret = VLC->creh->creatures[town->basicCreatures[level]].growth;
 	switch(fortLevel())
 	{
 	case 3:
@@ -286,13 +290,13 @@ int CGTownInstance::creatureGrowth(const int & level) const
 		ret*=(1.5); break;
 	}
 	if(builtBuildings.find(26)!=builtBuildings.end()) //grail
-		ret+=CGI->creh->creatures[town->basicCreatures[level]].growth;
+		ret+=VLC->creh->creatures[town->basicCreatures[level]].growth;
 	if(getHordeLevel(0)==level)
 		if((builtBuildings.find(18)!=builtBuildings.end()) || (builtBuildings.find(19)!=builtBuildings.end()))
-			ret+=CGI->creh->creatures[town->basicCreatures[level]].hordeGrowth;
+			ret+=VLC->creh->creatures[town->basicCreatures[level]].hordeGrowth;
 	if(getHordeLevel(1)==level)
 		if((builtBuildings.find(24)!=builtBuildings.end()) || (builtBuildings.find(25)!=builtBuildings.end()))
-			ret+=CGI->creh->creatures[town->basicCreatures[level]].hordeGrowth;
+			ret+=VLC->creh->creatures[town->basicCreatures[level]].hordeGrowth;
 	return ret;
 }
 int CGTownInstance::dailyIncome() const
@@ -324,9 +328,7 @@ CGTownInstance::CGTownInstance()
 	builded=-1;
 	destroyed=-1;
 	garrisonHero=NULL;
-	//state->owner=-1;
 	town=NULL;
-	income = 500;
 	visitingHero = NULL;
 }
 
@@ -334,7 +336,7 @@ CGObjectInstance::CGObjectInstance(): animPhaseShift(rand()%0xff)
 {
 	//std::cout << "Tworze obiekt "<<this<<std::endl;
 	//state = new CLuaObjectScript();
-	//state = NULL;
+	state = NULL;
 	tempOwner = 254;
 	blockVisit = false;
 }
@@ -347,11 +349,12 @@ CGObjectInstance::~CGObjectInstance()
 }
 CGHeroInstance::CGHeroInstance()
 {
-	level = exp = -1;
+	portrait = level = exp = -1;
 	isStanding = true;
 	moveDir = 4;
 	mana = 0;
 	visitedTown = NULL;
+	type = NULL;
 }
 
 CGHeroInstance::~CGHeroInstance()

+ 57 - 304
hch/CObjectHandler.h

@@ -1,13 +1,12 @@
 #ifndef COBJECTHANDLER_H
 #define COBJECTHANDLER_H
+#include "../global.h"
 #include <string>
 #include <vector>
 #include <set>
+#include <map>
 #include "CCreatureHandler.h"
-#include "CArtHandler.h"
-#include "CAbilityHandler.h"
-#include "CSpellHandler.h"
-//#include "CHeroHandler.h"
+
 using boost::logic::tribool;
 class CCPPObjectScript;
 class CGObjectInstance;
@@ -18,301 +17,45 @@ class CTown;
 class CHero;
 class CBuilding;
 class CSpell;
-class CSpecObjInfo //class with object - specific info (eg. different information for creatures and heroes); use inheritance to make object - specific classes
-{
-};
-
-class CEventObjInfo : public CSpecObjInfo
-{
-public:
-	bool areGuarders; //true if there are
-	CCreatureSet guarders;
-	bool isMessage; //true if there is a message
-	std::string message;
-	unsigned int gainedExp;
-	int manaDiff; //amount of gained / lost mana
-	int moraleDiff; //morale modifier
-	int luckDiff; //luck modifier
-	int wood, mercury, ore, sulfur, crystal, gems, gold; //gained / lost resources
-	unsigned int attack; //added attack points
-	unsigned int defence; //added defence points
-	unsigned int power; //added power points
-	unsigned int knowledge; //added knowledge points
-	std::vector<CAbility *> abilities; //gained abilities
-	std::vector<int> abilityLevels; //levels of gained abilities
-	std::vector<CArtifact *> artifacts; //gained artifacts
-	std::vector<CSpell *> spells; //gained spells
-	CCreatureSet creatures; //gained creatures
-	unsigned char availableFor; //players whom this event is available for
-	bool computerActivate; //true if computre player can activate this event
-	bool humanActivate; //true if human player can activate this event
-};
-
-class CHeroObjInfo : public CSpecObjInfo
-{
-public:
-	unsigned char bytes[4]; //mysterius bytes identifying hero in a strange way
-	int player;
-	CHero * type;
-	std::string name; //if nonstandard
-	bool standardGarrison; //true if hero has standard garrison
-	CCreatureSet garrison; //hero's army
-	std::vector<CArtifact *> artifacts; //hero's artifacts from bag
-	//CArtifact * artHead, * artLRing, * artRRing, * artLHand, * artRhand, * artFeet, * artSpellBook, * artMach1, * artMach2, * artMach3, * artMach4, * artMisc1, * artMisc2, * artMisc3, * artMisc4, * artMisc5, * artTorso, * artNeck, * artShoulders; //working artifactsstd::vector<CArtifact *> artifWorn; // 0 - head; 1 - shoulders; 2 - neck; 3 - right hand; 4 - left hand; 5 - torso; 6 - right ring; 7 - left ring; 8 - feet; 9 - misc1; 10 - misc2; 11 - misc3; 12 - misc4; 13 - mach1; 14 - mach2; 15 - mach3; 16 - mach4; 17 - spellbook; 18 - misc5
-	std::vector<CArtifact *> artifWorn; // 0 - head; 1 - shoulders; 2 - neck; 3 - right hand; 4 - left hand; 5 - torso; 6 - right ring; 7 - left ring; 8 - feet; 9 - misc1; 10 - misc2; 11 - misc3; 12 - misc4; 13 - mach1; 14 - mach2; 15 - mach3; 16 - mach4; 17 - spellbook; 18 - misc5
-	bool isGuarding;
-	int guardRange; //range of hero's guard
-	std::string biography; //if nonstandard
-	bool sex; //if true, reverse hero's sex
-	std::vector<CSpell *> spells; //hero's spells
-	int attack, defence, power, knowledge; //main hero's attributes
-	unsigned int experience; //hero's experience points
-	std::vector<CAbility *> abilities; //hero's abilities
-	std::vector<int> abilityLevels; //hero ability levels
-	bool defaultMainStats; //if true attack, defence, power and knowledge are typical
-	CGHeroInstance * myInstance; //pointer to appropriate hero instance
-};
-
-class CCreatureObjInfo : public CSpecObjInfo
-{
-public:
-	unsigned char bytes[4]; //mysterious bytes identifying creature
-	unsigned int number; //number of units (0 - random)
-	unsigned char character; //chracter of this set of creatures (0 - the most friendly, 4 - the most hostile)
-	std::string message; //message printed for attacking hero
-	int wood, mercury, ore, sulfur, crytal, gems, gold; //resources gained to hero that has won with monsters
-	CArtifact * gainedArtifact; //artifact gained to hero
-	bool neverFlees; //if true, the troops will never flee
-	bool notGrowingTeam; //if true, number of units won't grow
-};
-
-class CSignObjInfo : public CSpecObjInfo
-{
-public:
-	std::string message; //message
-};
-
-class CSeerHutObjInfo : public CSpecObjInfo
-{
-public:
-	unsigned char missionType; //type of mission: 0 - no mission; 1 - reach level; 2 - reach main statistics values; 3 - win with a certain hero; 4 - win with a certain creature; 5 - collect some atifacts; 6 - have certain troops in army; 7 - collect resources; 8 - be a certain hero; 9 - be a certain player
-	bool isDayLimit; //if true, there is a day limit
-	int lastDay; //after this day (first day is 0) mission cannot be completed
-	//for mission 1
-	int m1level;
-	//for mission 2
-	int m2attack, m2defence, m2power, m2knowledge;
-	//for mission 3
-	unsigned char m3bytes[4];
-	//for mission 4
-	unsigned char m4bytes[4];
-	//for mission 5
-	std::vector<CArtifact *> m5arts;
-	//for mission 6
-	std::vector<CCreature *> m6cre;
-	std::vector<int> m6number;
-	//for mission 7
-	int m7wood, m7mercury, m7ore, m7sulfur, m7crystal, m7gems, m7gold;
-	//for mission 8
-	CHero * m8hero;
-	//for mission 9
-	int m9player; //number; from 0 to 7
-
-	std::string firstVisitText, nextVisitText, completedText;
-
-	char rewardType; //type of reward: 0 - no reward; 1 - experience; 2 - mana points; 3 - morale bonus; 4 - luck bonus; 5 - resources; 6 - main ability bonus (attak, defence etd.); 7 - secondary ability gain; 8 - artifact; 9 - spell; 10 - creature
-	//for reward 1
-	int r1exp;
-	//for reward 2
-	int r2mana;
-	//for reward 3
-	int r3morale;
-	//for reward 4
-	int r4luck;
-	//for reward 5
-	unsigned char r5type; //0 - wood, 1 - mercury, 2 - ore, 3 - sulfur, 4 - crystal, 5 - gems, 6 - gold
-	int r5amount;
-	//for reward 6
-	unsigned char r6type; //0 - attack, 1 - defence, 2 - power, 3 - knowledge
-	int r6amount;
-	//for reward 7
-	CAbility * r7ability;
-	unsigned char r7level; //1 - basic, 2 - advanced, 3 - expert
-	//for reward 8
-	CArtifact * r8art;
-	//for reward 9
-	CSpell * r9spell;
-	//for reward 10
-	CCreature * r10creature;
-	int r10amount;
-};
-
-class CWitchHutObjInfo : public CSpecObjInfo
-{
-public:
-	std::vector<CAbility *> allowedAbilities;
-};
-
-class CScholarObjInfo : public CSpecObjInfo
-{
-public:
-	unsigned char bonusType; //255 - random, 0 - primary skill, 1 - secondary skill, 2 - spell
-
-	unsigned char r0type;
-	CAbility * r1;
-	CSpell * r2;
-};
-
-class CGarrisonObjInfo : public CSpecObjInfo
-{
-public:
-	unsigned char player; //255 - nobody; 0 - 7 - players
-	CCreatureSet units;
-	bool movableUnits; //if true, units can be moved
-};
-
-class CArtifactObjInfo : public CSpecObjInfo
-{
-public:
-	bool areGuards;
-	std::string message;
-	CCreatureSet guards;
-};
-
-class CResourceObjInfo : public CSpecObjInfo
-{
-public:
-	bool randomAmount;
-	int amount; //if not random
-	bool areGuards;
-	CCreatureSet guards;
-	std::string message;
-};
-
-class CPlayerOnlyObjInfo : public CSpecObjInfo
-{
-public:
-	unsigned char player; //FF - nobody, 0 - 7
-};
-
-class CShrineObjInfo : public CSpecObjInfo
-{
-public:
-	unsigned char spell; //number of spell or 255
-};
-
-class CSpellScrollObjinfo : public CSpecObjInfo
-{
-public:
-	std::string message;
-	CSpell * spell;
-	bool areGuarders;
-	CCreatureSet guarders;
-};
-
-class CPandorasBoxObjInfo : public CSpecObjInfo
-{
-public:
-	std::string message;
-	bool areGuarders;
-	CCreatureSet guarders;
-
-	//gained things:
-	unsigned int gainedExp;
-	int manaDiff;
-	int moraleDiff;
-	int luckDiff;
-	int wood, mercury, ore, sulfur, crystal, gems, gold;
-	int attack, defence, power, knowledge;
-	std::vector<CAbility *> abilities;
-	std::vector<int> abilityLevels;
-	std::vector<CArtifact *> artifacts;
-	std::vector<CSpell *> spells;
-	CCreatureSet creatures;
-};
-
-class CGrailObjInfo : public CSpecObjInfo
-{
-public:
-	int radius; //place grail at the distance lesser or equal radius from this place
-};
-
-class CCreGenObjInfo : public CSpecObjInfo
-{
-public:
-	unsigned char player; //owner
-	bool asCastle;
-	int identifier;
-	unsigned char castles[2]; //allowed castles
-};
-
-class CCreGen2ObjInfo : public CSpecObjInfo
-{
-public:
-	unsigned char player; //owner
-	bool asCastle;
-	int identifier;
-	unsigned char castles[2]; //allowed castles
-	unsigned char minLevel, maxLevel; //minimal and maximal level of creature in dwelling: <0, 6>
-};
+class CGTownInstance;
+class CArtifact;
+class CGDefInfo;
+class CSpecObjInfo;
 
-class CCreGen3ObjInfo : public CSpecObjInfo
+class DLL_EXPORT CCastleEvent
 {
 public:
-	unsigned char player; //owner
-	unsigned char minLevel, maxLevel; //minimal and maximal level of creature in dwelling: <0, 6>
-};
+	std::string name, message;
+	int wood, mercury, ore, sulfur, crystal, gems, gold; //gain / loss of resources
+	unsigned char players; //players for whom this event can be applied
+	bool forHuman, forComputer;
+	int firstShow; //postpone of first encounter time in days
+	int forEvery; //every n days this event will occure
 
-class CBorderGuardObjInfo : public CSpecObjInfo //copied form seer huts, seems to be similar
-{
-public:
-	char missionType; //type of mission: 0 - no mission; 1 - reach level; 2 - reach main statistics values; 3 - win with a certain hero; 4 - win with a certain creature; 5 - collect some atifacts; 6 - have certain troops in army; 7 - collect resources; 8 - be a certain hero; 9 - be a certain player
-	bool isDayLimit; //if true, there is a day limit
-	int lastDay; //after this day (first day is 0) mission cannot be completed
-	//for mission 1
-	int m1level;
-	//for mission 2
-	int m2attack, m2defence, m2power, m2knowledge;
-	//for mission 3
-	unsigned char m3bytes[4];
-	//for mission 4
-	unsigned char m4bytes[4];
-	//for mission 5
-	std::vector<CArtifact *> m5arts;
-	//for mission 6
-	std::vector<CCreature *> m6cre;
-	std::vector<int> m6number;
-	//for mission 7
-	int m7wood, m7mercury, m7ore, m7sulfur, m7crystal, m7gems, m7gold;
-	//for mission 8
-	CHero * m8hero;
-	//for mission 9
-	int m9player; //number; from 0 to 7
+	unsigned char bytes[6]; //build specific buildings (raw format, similar to town's)
 
-	std::string firstVisitText, nextVisitText, completedText;
-};
+	int gen[7]; //additional creatures in i-th level dwelling
 
-class CObject //typical object that can be encountered on a map
-{
-public:
-	std::string name; //object's name
+	bool operator<(const CCastleEvent &drugie) const
+	{
+		return firstShow<drugie.firstShow;
+	}
 };
 
-class CGDefInfo;
-
-class CGObjectInstance
+class DLL_EXPORT CGObjectInstance
 {
 public:
 	int3 pos; //h3m pos
 	int ID, subID; //normal ID (this one from OH3 maps ;]) - eg. town=98; hero=34
-	int id;//number of object in CObjectHandler's vector
+	si32 id;//number of object in CObjectHandler's vector		
 	CGDefInfo * defInfo;
 	CCPPObjectScript * state;
 	CSpecObjInfo * info;
 	unsigned char animPhaseShift;
+	std::string hoverName;
 
 	int tempOwner; //uzywane dla szybkosci, skrypt ma obowiazek aktualizowac te zmienna
-	bool blockVisit;
+	int blockVisit; //if non-zero then blocks the tile but is visitable from neighbouring tile
 
 	virtual bool isHero() const;
 	int getOwner() const;
@@ -327,22 +70,21 @@ public:
 	CGObjectInstance& operator=(const CGObjectInstance & right);
 };
 
-class  CArmedInstance: public CGObjectInstance
+class  DLL_EXPORT CArmedInstance: public CGObjectInstance
 {
 public:
 	CCreatureSet army; //army
 };
 
-class CGHeroInstance : public CArmedInstance
+class DLL_EXPORT CGHeroInstance : public CArmedInstance
 {
 public:
 	int moveDir; //format:	123
 					//		8 4
 					//		765
 	bool isStanding;
-	bool flagPrinted;
 	CHero * type;
-	int exp; //experience point
+	ui32 exp; //experience point
 	int level; //current level of hero
 	std::string name; //may be custom
 	std::string biography; //may be custom
@@ -351,12 +93,23 @@ public:
 	std::vector<int> primSkills; //0-attack, 1-defence, 2-spell power, 3-knowledge
 	std::vector<std::pair<int,int> > secSkills; //first - ID of skill, second - level of skill (0 - basic, 1 - adv., 2 - expert)
 	int movement; //remaining movement points
+	int identifier; //from the map file
+	bool sex;
+
+	struct DLL_EXPORT Patrol
+	{
+		Patrol(){patrolling=false;patrolRadious=-1;};
+		bool patrolling;
+		int patrolRadious;
+	} patrol;
 
-	bool inTownGarrison; // if hero is in town garrison
+
+	bool inTownGarrison; // if hero is in town garrison 
 	CGTownInstance * visitedTown; //set if hero is visiting town or in the town garrison
 
-	std::vector<CArtifact *> artifacts; //hero's artifacts from bag
-	std::vector<CArtifact *> artifWorn; // 0 - head; 1 - shoulders; 2 - neck; 3 - right hand; 4 - left hand; 5 - torso; 6 - right ring; 7 - left ring; 8 - feet; 9 - misc1; 10 - misc2; 11 - misc3; 12 - misc4; 13 - mach1; 14 - mach2; 15 - mach3; 16 - mach4; 17 - spellbook; 18 - misc5
+	std::vector<int> artifacts; //hero's artifacts from bag
+	std::map<int,int> artifWorn; //map<position,artifact_id>; positions: 0 - head; 1 - shoulders; 2 - neck; 3 - right hand; 4 - left hand; 5 - torso; 6 - right ring; 7 - left ring; 8 - feet; 9 - misc1; 10 - misc2; 11 - misc3; 12 - misc4; 13 - mach1; 14 - mach2; 15 - mach3; 16 - mach4; 17 - spellbook; 18 - misc5
+	std::set<int> spells; //known spells (spell IDs)
 
 	virtual bool isHero() const;
 	unsigned int getTileCost(const EterrainType & ttype, const Eroad & rdtype, const Eriver & rvtype) const;
@@ -372,41 +125,42 @@ public:
 	int getCurrentLuck() const;
 	int getCurrentMorale() const;
 	int getSecSkillLevel(const int & ID) const; //-1 - no skill
+	const CArtifact * getArt(int pos);
 	CGHeroInstance();
 	virtual ~CGHeroInstance();
 };
 
-class CGTownInstance : public CArmedInstance
+class DLL_EXPORT CGTownInstance : public CArmedInstance
 {
 public:
 	CTown * town;
 	std::string name; // name of town
 	int builded; //how many buildings has been built this turn
 	int destroyed; //how many buildings has been destroyed this turn
-	int identifier;
-
-	int income;
+	const CGHeroInstance * garrisonHero, *visitingHero;
+	int identifier; //special identifier from h3m (only > RoE maps)
+	int alignment;
+	std::set<si32> forbiddenBuildings, builtBuildings;
+	std::vector<int> possibleSpells, obligatorySpells, availableSpells;
 
 	struct StrInfo
 	{
-	public:
-		std::map<int,int> creatures; //level - available amount
-	} strInfo;
-
-	std::set<int> forbiddenBuildings, builtBuildings, h3mbuildings;
+		std::map<si32,ui32> creatures; //level - available amount
 
-	const CGHeroInstance * garrisonHero, *visitingHero;
+		template <typename Handler> void serialize(Handler &h, const int version)
+		{
+			h & creatures;
+		}
+	} strInfo;
+	std::set<CCastleEvent> events;
 
-	std::vector<CSpell *> possibleSpells, obligatorySpells, availableSpells;
 
 	int getSightDistance() const; //returns sight distance
-
 	int fortLevel() const; //0 - none, 1 - fort, 2 - citadel, 3 - castle
 	int hallLevel() const; // -1 - none, 0 - village, 1 - town, 2 - city, 3 - capitol
 	bool creatureDwelling(const int & level, bool upgraded=false) const;
 	int getHordeLevel(const int & HID) const; //HID - 0 or 1; returns creature level or -1 if that horde structure is not present
 	int creatureGrowth(const int & level) const;
-
 	bool hasFort() const;
 	bool hasCapitol() const;
 	int dailyIncome() const;
@@ -415,11 +169,10 @@ public:
 	virtual ~CGTownInstance();
 };
 
-class CObjectHandler
+class DLL_EXPORT CObjectHandler
 {
 public:
-	std::vector<CObject> objects; //vector of objects; i-th object in vector has subnumber i
-	std::vector<CGObjectInstance*> objInstances; //vector with objects on map
+	std::vector<std::string> names; //vector of objects; i-th object in vector has subnumber i
 	std::vector<int> cregens; //type 17. dwelling subid -> creature ID
 	void loadObjects();
 

+ 3 - 3
hch/CPreGameTextHandler.cpp

@@ -25,7 +25,7 @@ std::string CPreGameTextHandler::getDescr(std::string text)
 }
 void CPreGameTextHandler::loadTexts()
 {
-	std::string buf1 = CGameInfo::mainObj->bitmaph->getTextFile("ZELP.TXT");
+	std::string buf1 = CGI->bitmaph->getTextFile("ZELP.TXT");
 	int itr=0, eol=-1, eolnext=-1, pom;
 	eolnext = buf1.find_first_of('\r',itr);
 	while(itr<buf1.size())
@@ -48,7 +48,7 @@ void CPreGameTextHandler::loadTexts()
 		}
 		itr=eol+2;
 	}
-	std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("VCDESC.TXT");
+	std::string buf = CGI->bitmaph->getTextFile("VCDESC.TXT");
 	int andame = buf.size();
 	int i=0; //buf iterator
 	for(int gg=0; gg<14; ++gg)
@@ -62,7 +62,7 @@ void CPreGameTextHandler::loadTexts()
 		victoryConditions[gg] = buf.substr(befi, i-befi);
 		i+=2;
 	}
-	buf = CGameInfo::mainObj->bitmaph->getTextFile("LCDESC.TXT");
+	buf = CGI->bitmaph->getTextFile("LCDESC.TXT");
 	andame = buf.size();
 	i=0; //buf iterator
 	for(int gg=0; gg<4; ++gg)

+ 0 - 148
hch/CSemiDefHandler.cpp

@@ -1,148 +0,0 @@
-#include "../stdafx.h"
-#include "CSemiDefHandler.h"
-#include <fstream>
-#include "SDL_image.h"
-extern SDL_Surface * screen;
-std::string CSemiDefHandler::nameFromType (EterrainType typ)
-{
-	switch(typ)
-	{
-		case dirt:
-		{
-			return std::string("DIRTTL.DEF");
-			break;
-		}
-		case sand:
-		{
-			return std::string("SANDTL.DEF");
-			break;
-		}
-		case grass:
-		{
-			return std::string("GRASTL.DEF");
-			break;
-		}
-		case snow:
-		{
-			return std::string("SNOWTL.DEF");
-			break;
-		}
-		case swamp:
-		{
-			return std::string("SWMPTL.DEF");			
-			break;
-		}
-		case rough:
-		{
-			return std::string("ROUGTL.DEF");		
-			break;
-		}
-		case subterranean:
-		{
-			return std::string("SUBBTL.DEF");		
-			break;
-		}
-		case lava:
-		{
-			return std::string("LAVATL.DEF");		
-			break;
-		}
-		case water:
-		{
-			return std::string("WATRTL.DEF");
-			break;
-		}
-		case rock:
-		{
-			return std::string("ROCKTL.DEF");		
-			break;
-		}
-	}
-	return std::string();
-}
-void CSemiDefHandler::openDef(std::string name, std::string lodName, int dist)
-{
-	std::ifstream * is = new std::ifstream();
-	is -> open((lodName+"\\"+name).c_str(),std::ios::binary);
-	is->seekg(0,std::ios::end); // na koniec
-	int andame = is->tellg();  // read length
-	is->seekg(0,std::ios::beg); // wracamy na poczatek
-	buforD = new unsigned char[andame]; // allocate memory 
-	is->read((char*)buforD, andame); // read map file to buffer
-	defName = name;
-	int gdzie = defName.find_last_of("\\");
-	defName = defName.substr(gdzie+1, gdzie-defName.length());
-	delete is;
-
-	readFileList(dist);
-	loadImages(lodName);
-
-}
-CSemiDefHandler::~CSemiDefHandler()
-{
-	for (int i=0;i<ourImages.size();i++)
-		SDL_FreeSurface(ourImages[i].bitmap);
-}
-void CSemiDefHandler::readFileList(int dist)
-{
-	howManyImgs = buforD[788];
-	int i = 800;
-	for (int pom=0;pom<howManyImgs;pom++)
-	{
-		std::string temp;
-		while (buforD[i]!=0)
-		{
-			temp+=buforD[i++];
-		}
-		i+=dist; //by³o zwiêkszenie tylko o jedno
-		if (temp!="")
-		{
-			temp = temp.substr(0,temp.length()-4) + ".BMP";
-			namesOfImgs.push_back(temp);
-		}
-		else pom--;
-	}
-	delete buforD;
-}
-void CSemiDefHandler::loadImages(std::string path)
-{
-	for (int i=0; i<namesOfImgs.size(); i++)
-	{
-		openImg((path+"\\_"+defName+"\\"+namesOfImgs[i]).c_str());
-	}
-}
- void SDL_DisplayBitmap(const char *file, SDL_Surface *ekran, int x, int y)
-{
-	SDL_Surface *image;
-	SDL_Rect dest;
-	image = SDL_LoadBMP(file);
-	if ( image == NULL )
-	{
-		fprintf(stderr, "Nie mo¿na wczytaæ %s: %s\n", file, SDL_GetError());
-		return;
-	}
-	dest.x = x;
-	dest.y = y;
-	dest.w = image->w;
-	dest.h = image->h;
-	SDL_BlitSurface(image, NULL, ekran, &dest);
-	SDL_UpdateRects(ekran, 1, &dest);
-	SDL_FreeSurface(image);
-}
-void CSemiDefHandler::openImg(const char *name)
-{
-	SDL_Surface *image;
-	image=IMG_Load(name); 
-	//SDL_DisplayBitmap(name,image, 0,0);
-	if(!image) 
-	{
-		printf("IMG_Load: %s\n", IMG_GetError());
-		return;
-		// handle error
-	}
-	Cimage vinya;
-	vinya.bitmap = image;
-	SDL_SetColorKey(vinya.bitmap,SDL_SRCCOLORKEY,SDL_MapRGB(vinya.bitmap->format,0,255,255));
-	vinya.imName = name;
-	ourImages.push_back(vinya);
-}

+ 0 - 31
hch/CSemiDefHandler.h

@@ -1,31 +0,0 @@
-#ifndef SEMIDEF_H
-#define SEMIDEF_H
-#include "../global.h"
-#include <string>
-#include "SDL.h"
-//#include "SDL_image.h"
-#include <vector>
-
-struct Cimage
-{
-	int groupNumber;
-	std::string imName; //name without extension
-	SDL_Surface * bitmap;
-};
-class CSemiDefHandler
-{
-public:
-	int howManyImgs;
-	std::string defName;
-	std::vector<Cimage> ourImages;
-	std::vector<std::string> namesOfImgs;
-	unsigned char * buforD;
-
-	static std::string nameFromType(EterrainType typ);
-	void openImg(const char *name);
-	void openDef(std::string name, std::string lodName, int dist=1);
-	void readFileList(int dist = 1);
-	void loadImages(std::string path);
-	~CSemiDefHandler();
-};
-#endif // SEMIDEF_H

+ 0 - 12
hch/CSemiLodHandler.cpp

@@ -1,12 +0,0 @@
-#include "../stdafx.h"
-#include "CSemiLodHandler.h"
-void CSemiLodHandler::openLod(std::string path)
-{
-	ourName = path;
-};
-CSemiDefHandler * CSemiLodHandler::giveDef(std::string name, int dist)
-{
-	CSemiDefHandler * ret = new CSemiDefHandler();
-	ret->openDef(name, ourName, dist);
-	return ret;
-};

+ 0 - 13
hch/CSemiLodHandler.h

@@ -1,13 +0,0 @@
-#ifndef CSEMILODHANDLER_H
-#define CSEMILODHANDLER_H
-
-#include "CSemiDefHandler.h"
-class CSemiLodHandler
-{
-public:
-	std::string ourName; // name of our lod
-	void openLod(std::string path);
-	CSemiDefHandler * giveDef(std::string name, int dist=1); //loads def from our lod
-};
-
-#endif //CSEMILODHANDLER_H

+ 2 - 2
hch/CSpellHandler.cpp

@@ -1,11 +1,11 @@
-#include "../stdafx.h"
+  #include "../stdafx.h"
 #include "CSpellHandler.h"
 #include "../CGameInfo.h"
 #include "CLodHandler.h"
 
 void CSpellHandler::loadSpells()
 {
-	std::string buf = CGameInfo::mainObj->bitmaph->getTextFile("SPTRAITS.TXT");
+	std::string buf = CGI->bitmaph->getTextFile("SPTRAITS.TXT");
 	int andame = buf.size();
 	int i=0; //buf iterator
 	int hmcr=0;

+ 12 - 46
hch/CTownHandler.cpp

@@ -1,24 +1,22 @@
+#define VCMI_DLL
 #include "../stdafx.h"
 #include "CTownHandler.h"
-#include "../CGameInfo.h"
 #include "CLodHandler.h"
 #include <sstream>
-#include "CGeneralTextHandler.h"
+#include "../lib/VCMI_Lib.h"
+extern CLodHandler * bitmaph;
+void loadToIt(std::string &dest, std::string &src, int &iter, int mode);
 CTownHandler::CTownHandler()
 {
-	smallIcons = CGI->spriteh->giveDef("ITPA.DEF");
-	resources = CGI->spriteh->giveDef("RESOURCE.DEF");
+	VLC->townh = this;
 }
 CTownHandler::~CTownHandler()
-{
-	delete smallIcons;
-	//todo - delete structures info
-}
+{}
 void CTownHandler::loadNames()
 {
 	std::istringstream ins, names;
-	ins.str(CGI->bitmaph->getTextFile("TOWNTYPE.TXT"));
-	names.str(CGI->bitmaph->getTextFile("TOWNNAME.TXT"));
+	ins.str(bitmaph->getTextFile("TOWNTYPE.TXT"));
+	names.str(bitmaph->getTextFile("TOWNNAME.TXT"));
 	int si=0;
 	char bufname[75];
 	while (!ins.eof())
@@ -40,21 +38,21 @@ void CTownHandler::loadNames()
 			towns.push_back(town);
 	}
 
-	std::string  strs = CGI->bitmaph->getTextFile("TCOMMAND.TXT");
+	std::string  strs = bitmaph->getTextFile("TCOMMAND.TXT");
 	int itr=0;
 	while(itr<strs.length()-1)
 	{
 		std::string tmp;
-		CGeneralTextHandler::loadToIt(tmp, strs, itr, 3);
+		loadToIt(tmp, strs, itr, 3);
 		tcommands.push_back(tmp);
 	}
 
-	strs = CGI->bitmaph->getTextFile("HALLINFO.TXT");
+	strs = bitmaph->getTextFile("HALLINFO.TXT");
 	itr=0;
 	while(itr<strs.length()-1)
 	{
 		std::string tmp;
-		CGeneralTextHandler::loadToIt(tmp, strs, itr, 3);
+		loadToIt(tmp, strs, itr, 3);
 		hcommands.push_back(tmp);
 	}
 
@@ -277,35 +275,3 @@ void CTownHandler::loadNames()
 		of.clear();
 	}
 }
-SDL_Surface * CTownHandler::getPic(int ID, bool fort, bool builded)
-{
-	if (ID==-1)
-		return smallIcons->ourImages[0].bitmap;
-	else if (ID==-2)
-		return smallIcons->ourImages[1].bitmap;
-	else if (ID==-3)
-		return smallIcons->ourImages[2+F_NUMBER*4].bitmap;
-	else if (ID>F_NUMBER || ID<-3)
-#ifndef __GNUC__
-		throw new std::exception("Invalid ID");
-#else
-		throw new std::exception();
-#endif
-	else
-	{
-		int pom = 3;
-		if(!fort)
-			pom+=F_NUMBER*2;
-		pom += ID*2;
-		if (!builded)
-			pom--;
-		return smallIcons->ourImages[pom].bitmap;
-	}
-}
-
-int CTownHandler::getTypeByDefName(std::string name)
-{
-	//TODO
-	return 0;
-}
-

+ 7 - 19
hch/CTownHandler.h

@@ -1,18 +1,12 @@
 #ifndef CTOWNHANDLER_H
 #define CTOWNHANDLER_H
-
-#include "CDefHandler.h"
-#include "CCreatureHandler.h"
-#include "SDL.h"
-#include "../int3.h"
-#include <string>
-#include <vector>
+#include "../global.h"
 #include <set>
 class CBuilding;
 class CSpell;
 class CHero;
 class CGTownInstance;
-class CTown
+class DLL_EXPORT CTown
 {
 public:
 	std::string name; //name of type
@@ -24,7 +18,7 @@ public:
 	int typeID;
 };
 
-struct Structure
+struct DLL_EXPORT Structure
 {
 	int ID;
 	int3 pos;
@@ -39,23 +33,17 @@ struct Structure
 	}
 };
 
-class CTownHandler
+class DLL_EXPORT CTownHandler
 {
 public:
-	CDefHandler * smallIcons, *resources; //resources 32x32
-	CTownHandler();
-	~CTownHandler();
 	std::vector<CTown> towns;
 	std::vector<std::string> tcommands, hcommands;
-	void loadNames();
-	SDL_Surface * getPic(int ID, bool fort=true, bool builded=false); //ID=-1 - blank; -2 - border; -3 - random
-	static int getTypeByDefName(std::string name);
-
 	std::map<int,std::map<int, Structure*> > structures; // <town ID, <structure ID, structure>>
 	std::map<int, std::map<int,std::set<int> > > requirements; //requirements[town_id][structure_id] -> set of required buildings
 
-	std::vector<CGTownInstance *> townInstances;
-
+	CTownHandler();
+	~CTownHandler();
+	void loadNames();
 };
 
 #endif //CTOWNHANDLER_H

+ 24 - 8
int3.h

@@ -1,22 +1,34 @@
 #ifndef INT3_H
 #define INT3_H
+#include <map>
+class CCreature;
+class CCreatureSet //seven combined creatures
+{
+public:
+	std::map<si32,std::pair<ui32,si32> > slots; //slots[slot_id]=> pair(creature_id,creature_quantity)
+	bool formation; //false - wide, true - tight	
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & slots & formation;
+	}
+};
 
 class int3
 {
 public:
-	int x,y,z;
+	si32 x,y,z;
 	inline int3():x(0),y(0),z(0){}; //c-tor, x/y/z initialized to 0
-	inline int3(const int & X, const int & Y, const int & Z):x(X),y(Y),z(Z){}; //c-tor
+	inline int3(const si32 & X, const si32 & Y, const si32 & Z):x(X),y(Y),z(Z){}; //c-tor
 	inline ~int3(){} // d-tor - does nothing
 	inline int3 operator+(const int3 & i) const
 		{return int3(x+i.x,y+i.y,z+i.z);}
-	inline int3 operator+(const int i) const //increases all components by int
+	inline int3 operator+(const si32 i) const //increases all components by si32
 		{return int3(x+i,y+i,z+i);}
 	inline int3 operator-(const int3 & i) const
 		{return int3(x-i.x,y-i.y,z-i.z);}
-	inline int3 operator-(const int i) const
+	inline int3 operator-(const si32 i) const
 		{return int3(x-i,y-i,z-i);}
-	inline int3 operator-() const //increases all components by int
+	inline int3 operator-() const //increases all components by si32
 		{return int3(-x,-y,-z);}
 	inline void operator+=(const int3 & i)
 	{
@@ -24,7 +36,7 @@ public:
 		y+=i.y;
 		z+=i.z;
 	}
-	inline void operator+=(const int & i)
+	inline void operator+=(const si32 & i)
 	{
 		x+=i;
 		y+=i;
@@ -36,7 +48,7 @@ public:
 		y-=i.y;
 		z-=i.z;
 	}
-	inline void operator-=(const int & i)
+	inline void operator-=(const si32 & i)
 	{
 		x+=i;
 		y+=i;
@@ -62,13 +74,17 @@ public:
 			return false;
 		return false;
 	}
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & x & y & z;
+	}
 };
 inline std::istream & operator>>(std::istream & str, int3 & dest)
 {
 	str>>dest.x>>dest.y>>dest.z;
 	return str;
 }
-inline std::ostream & operator<<(std::ostream & str, int3 & sth)
+inline std::ostream & operator<<(std::ostream & str, const int3 & sth)
 {
 	return str<<sth.x<<' '<<sth.y<<' '<<sth.z;
 }

+ 13 - 0
lib/BattleAction.h

@@ -0,0 +1,13 @@
+#pragma once
+struct BattleAction
+{
+	ui8 side; //who made this action: false - left, true - right player
+	ui32 stackNumber;//stack ID, -1 left hero, -2 right hero,
+	ui8 actionType; //    0 = Cancel BattleAction   1 = Hero cast a spell   2 = Walk   3 = Defend   4 = Retreat from the battle   5 = Surrender   6 = Walk and Attack   7 = Shoot    8 = Wait   9 = Catapult 10 = Monster casts a spell (i.e. Faerie Dragons)
+	ui16 destinationTile;
+	si32 additionalInfo; // e.g. spell number if type is 1 || 10
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & side & stackNumber & actionType & destinationTile & additionalInfo;
+	}
+};

+ 13 - 0
lib/CondSh.h

@@ -0,0 +1,13 @@
+#pragma once
+#include <boost/thread.hpp>
+template <typename T> struct CondSh
+{
+	T data;
+	boost::condition_variable cond;
+	boost::mutex mx;
+	CondSh(){};
+	CondSh(T t){data = t;};
+	void set(T t){mx.lock();data=t;mx.unlock();}; //set data
+	void setn(T t){mx.lock();data=t;mx.unlock();cond.notify_all();}; //set data and notify
+	T get(){boost::unique_lock<boost::mutex> lock(mx); return data;};
+};

+ 104 - 0
lib/Connection.cpp

@@ -0,0 +1,104 @@
+#define VCMI_DLL
+#pragma warning(disable:4355)
+#include "Connection.h"
+#include <boost/asio.hpp>
+#include <boost/thread.hpp>
+using namespace boost;
+using namespace boost::asio::ip;
+
+#define LOG(a) \
+	if(logging)\
+		out << a
+#if defined(__hppa__) || \
+    defined(__m68k__) || defined(mc68000) || defined(_M_M68K) || \
+    (defined(__MIPS__) && defined(__MISPEB__)) || \
+    defined(__ppc__) || defined(__POWERPC__) || defined(_M_PPC) || \
+    defined(__sparc__)
+#define BIG_ENDIAN
+#else
+#define LIL_ENDIAN
+#endif
+
+void CConnection::init()
+{
+#ifdef LIL_ENDIAN
+	myEndianess = true;
+#else
+	myEndianess = false;
+#endif
+	connected = true;
+	std::string pom;
+	//we got connection
+	(*this) << std::string("Aiya!\n") << name << myEndianess; //identify ourselves
+	(*this) >> pom >> pom >> contactEndianess;
+	out << "Established connection with "<<pom<<std::endl;
+	wmx = new boost::mutex;
+	rmx = new boost::mutex;
+}
+
+CConnection::CConnection(std::string host, std::string port, std::string Name, std::ostream & Out)
+:io_service(new asio::io_service), name(Name), out(Out)//, send(this), rec(this)
+{
+	boost::system::error_code error = asio::error::host_not_found;
+	socket = new tcp::socket(*io_service);
+    tcp::resolver resolver(*io_service);
+    tcp::resolver::iterator endpoint_iterator = resolver.resolve(tcp::resolver::query(host,port));
+    socket->connect(*endpoint_iterator, error);
+	if (error){ delete socket;	throw "Can't establish connection :("; }
+	init();
+}
+CConnection::CConnection(
+			boost::asio::basic_stream_socket<boost::asio::ip::tcp , boost::asio::stream_socket_service<boost::asio::ip::tcp>  > * Socket, 
+			std::string Name, 
+			std::ostream & Out	)
+			:socket(Socket),io_service(&Socket->io_service()), out(Out), name(Name)//, send(this), rec(this)
+{
+	init();
+}
+CConnection::CConnection(boost::asio::basic_socket_acceptor<boost::asio::ip::tcp, boost::asio::socket_acceptor_service<boost::asio::ip::tcp> > * acceptor, boost::asio::io_service *Io_service, std::string Name, std::ostream & Out)
+: out(Out), name(Name)//, send(this), rec(this)
+{
+	boost::system::error_code error = asio::error::host_not_found;
+	socket = new tcp::socket(*io_service);
+	acceptor->accept(*socket,error);
+	if (error){ delete socket;	throw "Can't establish connection :("; }
+	init();
+}
+int CConnection::write(const void * data, unsigned size)
+{
+	LOG("Sending " << size << " byte(s) of data" <<std::endl);
+	int ret;
+	ret = asio::write(*socket,asio::const_buffers_1(asio::const_buffer(data,size)));
+	return ret;
+}
+int CConnection::read(void * data, unsigned size)
+{
+	LOG("Receiving " << size << " byte(s) of data" <<std::endl);
+	int ret = asio::read(*socket,asio::mutable_buffers_1(asio::mutable_buffer(data,size)));
+	return ret;
+}
+CConnection::~CConnection(void)
+{
+	if(socket)
+		socket->close();
+	delete socket;
+	delete io_service;
+	delete wmx;
+	delete rmx;
+}
+
+template <>
+void CConnection::saveSerializable<std::string>(const std::string &data)
+{
+	*this << ui32(data.size());
+	write(data.c_str(),data.size());
+}
+
+template <>
+void CConnection::loadSerializable<std::string>(std::string &data)
+{
+	ui32 l;
+	*this >> l;
+	data.resize(l);
+	read((void*)data.c_str(),l);
+}

+ 382 - 0
lib/Connection.h

@@ -0,0 +1,382 @@
+#pragma once
+#include "../global.h"
+#include <string>
+#include <vector>
+#include <set>
+
+#include <boost/type_traits/is_fundamental.hpp>
+#include <boost/type_traits/is_enum.hpp>
+#include <boost/type_traits/is_pointer.hpp> 
+#include  <boost/type_traits/remove_pointer.hpp>
+
+#include <boost/mpl/eval_if.hpp>
+#include <boost/mpl/equal_to.hpp>
+#include <boost/mpl/int.hpp>
+#include <boost/mpl/identity.hpp>
+
+const int version = 63;
+class CConnection;
+
+namespace mpl = boost::mpl;
+
+namespace boost
+{
+	namespace asio
+	{
+		namespace ip
+		{
+			class tcp;
+		}
+		class io_service;
+
+		template <typename Protocol> class stream_socket_service;
+		template <typename Protocol,typename StreamSocketService>
+		class basic_stream_socket;
+
+		template <typename Protocol> class socket_acceptor_service;
+		template <typename Protocol,typename SocketAcceptorService>
+		class basic_socket_acceptor;
+	}
+	class mutex;
+};
+
+enum SerializationLvl
+{
+	Wrong=0,
+	Primitive,
+	Pointer,
+	Serializable
+};
+
+template<typename T>
+struct SerializationLevel
+{    
+	typedef mpl::integral_c_tag tag;
+	typedef
+		typename mpl::eval_if<
+			boost::is_fundamental<T>,
+			mpl::int_<Primitive>,
+		//else
+		typename mpl::eval_if<
+			boost::is_class<T>,
+			mpl::int_<Serializable>,
+		//else
+		typename mpl::eval_if<
+			boost::is_array<T>,
+			mpl::int_<Primitive>,
+		//else
+		typename mpl::eval_if<
+			boost::is_pointer<T>,
+			mpl::int_<Pointer>,
+		//else
+		typename mpl::eval_if<
+			boost::is_enum<T>,
+			mpl::int_<Primitive>,
+		//else
+			mpl::int_<Wrong>
+		>
+		>
+		>
+		>
+		>::type type;
+	static const int value = SerializationLevel::type::value;
+};
+
+template <typename Serializer> class DLL_EXPORT COSer
+{
+public:
+	bool saving;
+	COSer(){saving=true;};
+    Serializer * This()
+	{
+		return static_cast<Serializer*>(this);
+	}
+
+	template<class T>
+	Serializer & operator<<(const T &t)
+	{
+		this->This()->save(t);
+		return * this->This();
+	}
+	
+	template<class T>
+	COSer & operator&(T & t){
+		return * this->This() << t;
+	}
+};
+template <typename Serializer> class DLL_EXPORT CISer
+{
+public:
+	bool saving;
+	CISer(){saving = false;};
+    Serializer * This()
+	{
+		return static_cast<Serializer*>(this);
+	}
+
+	template<class T>
+	Serializer & operator>>(T &t)
+	{
+		this->This()->load(t);
+		return * this->This();
+	}
+	
+	template<class T>
+	CISer & operator&(T & t){
+		return * this->This() >> t;
+	}
+};
+
+template<typename Ser,typename T>
+struct SavePrimitive
+{
+	static void invoke(Ser &s, const T &data)
+	{
+		s.savePrimitive(data);
+	}
+};
+template<typename Ser,typename T>
+struct SaveSerializable
+{
+	static void invoke(Ser &s, const T &data)
+	{
+		s.saveSerializable(data);
+	}
+};
+template<typename Ser,typename T>
+struct LoadPrimitive
+{
+	static void invoke(Ser &s, T &data)
+	{
+		s.loadPrimitive(data);
+	}
+};
+template<typename Ser,typename T>
+struct SavePointer
+{
+	static void invoke(Ser &s, const T &data)
+	{
+		s.savePointer(data);
+	}
+};
+template<typename Ser,typename T>
+struct LoadPointer
+{
+	static void invoke(Ser &s, T &data)
+	{
+		s.loadPointer(data);
+	}
+};
+template<typename Ser,typename T>
+struct LoadSerializable
+{
+	static void invoke(Ser &s, T &data)
+	{
+		s.loadSerializable(data);
+	}
+};
+
+template<typename Ser,typename T>
+struct SaveWrong
+{
+	static void invoke(Ser &s, const T &data)
+	{
+		throw std::exception("Wrong save serialization call!");
+	}
+};
+template<typename Ser,typename T>
+struct LoadWrong
+{
+	static void invoke(Ser &s, const T &data)
+	{
+		throw std::exception("Wrong load serialization call!");
+	}
+};
+
+
+class DLL_EXPORT CConnection
+	:public CISer<CConnection>, public COSer<CConnection>
+{
+
+
+	std::ostream &out;
+	CConnection(void);
+	void init();
+public:
+	boost::mutex *rmx, *wmx; // read/write mutexes
+
+	template <typename T>
+	void savePrimitive(const T &data)
+	{
+		write(&data,sizeof(data));
+	}
+	template <typename T>
+	void loadPrimitive(T &data)
+	{
+		read(&data,sizeof(data));
+	}
+
+	
+	
+	template <typename T>
+	void saveSerializable(const T &data)
+	{
+		const_cast<T&>(data).serialize(*static_cast<COSer<CConnection>*>(this),version);
+	}
+	template <typename T>
+	void loadSerializable(T &data)
+	{
+		data.serialize(*static_cast<CISer<CConnection>*>(this),version);
+	}	
+	template <typename T>
+	void savePointer(const T &data)
+	{
+		*this << *data;
+	}
+	template <typename T>
+	void loadPointer(T &data)
+	{
+		std::cout<<"Allocating memory for pointer!"<<std::endl;
+		typedef typename boost::remove_pointer<T>::type npT;
+		data = new npT;
+		*this >> *data;
+	}
+	template <typename T>
+	void saveSerializable(const std::vector<T> &data)
+	{
+		boost::uint32_t length = data.size();
+		*this << length;
+		for(ui32 i=0;i<length;i++)
+			*this << data[i];
+	}
+	template <typename T>
+	void loadSerializable(std::vector<T> &data)
+	{
+		boost::uint32_t length;
+		*this >> length;
+		data.resize(length);
+		for(ui32 i=0;i<length;i++)
+			*this >> data[i];
+	}
+	
+	template <typename T>
+	void saveSerializable(const std::set<T> &data)
+	{
+		std::set<T> &d = const_cast<std::set<T> &>(data);
+		boost::uint32_t length = d.size();
+		*this << length;
+		for(typename std::set<T>::iterator i=d.begin();i!=d.end();i++)
+			*this << *i;
+	}
+	template <typename T>
+	void loadSerializable(std::set<T> &data)
+	{
+		boost::uint32_t length;
+		*this >> length;
+		T ins;
+		for(ui32 i=0;i<length;i++)
+		{
+			*this >> ins;
+			data.insert(ins);
+		}
+	}
+	
+	template <typename T1, typename T2>
+	void saveSerializable(const std::pair<T1,T2> &data)
+	{
+		*this << data.first << data.second;
+	}
+	template <typename T1, typename T2>
+	void loadSerializable(std::pair<T1,T2> &data)
+	{
+		*this >> data.first >> data.second;
+	}
+	
+	template <typename T1, typename T2>
+	void saveSerializable(const std::map<T1,T2> &data)
+	{
+		*this << ui32(data.size());
+		for(typename std::map<T1,T2>::const_iterator i=data.begin();i!=data.end();i++)
+			*this << i->first << i->second;
+	}
+	template <typename T1, typename T2>
+	void loadSerializable(std::map<T1,T2> &data)
+	{
+		ui32 length;
+		*this >> length;
+		T1 t;
+		for(int i=0;i<length;i++)
+		{
+			*this >> t;
+			*this >> data[t];
+		}
+	}
+	template <typename T>
+	void save(const T &data)
+	{
+		typedef 
+			//if
+			typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<Primitive> >,
+				mpl::identity<SavePrimitive<CConnection,T> >,
+			//else if
+			typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Pointer> >,
+				mpl::identity<SavePointer<CConnection,T> >,
+			//else if
+			typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Serializable> >,
+				mpl::identity<SaveSerializable<CConnection,T> >,
+			//else
+				mpl::identity<SaveWrong<CConnection,T> >
+			>
+			>
+			>::type typex;
+		typex::invoke(*this, data);
+	}
+
+	template <typename T>
+	void load(T &data)
+	{
+		typedef 
+			//if
+			typename mpl::eval_if< mpl::equal_to<SerializationLevel<T>,mpl::int_<Primitive> >,
+				mpl::identity<LoadPrimitive<CConnection,T> >,
+			//else if
+			typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Pointer> >,
+				mpl::identity<LoadPointer<CConnection,T> >,
+			//else if
+			typename mpl::eval_if<mpl::equal_to<SerializationLevel<T>,mpl::int_<Serializable> >,
+				mpl::identity<LoadSerializable<CConnection,T> >,
+			//else
+				mpl::identity<LoadWrong<CConnection,T> >
+			>
+			>
+			>::type typex;
+		typex::invoke(*this, data);
+	}
+
+	boost::asio::basic_stream_socket < boost::asio::ip::tcp , boost::asio::stream_socket_service<boost::asio::ip::tcp>  > * socket;
+	bool logging;
+	bool connected;
+	bool myEndianess, contactEndianess; //true if little endian, if ednianess is different we'll have to revert recieved multi-byte vars
+    boost::asio::io_service *io_service;
+	std::string name; //who uses this connection
+
+	CConnection
+		(std::string host, std::string port, std::string Name, std::ostream & Out);
+	CConnection
+		(boost::asio::basic_socket_acceptor<boost::asio::ip::tcp, boost::asio::socket_acceptor_service<boost::asio::ip::tcp> > * acceptor, 
+		boost::asio::io_service *Io_service, std::string Name, std::ostream & Out);
+	CConnection
+		(boost::asio::basic_stream_socket < boost::asio::ip::tcp , boost::asio::stream_socket_service<boost::asio::ip::tcp>  > * Socket, 
+		std::string Name, std::ostream & Out); //use immediately after accepting connection into socket
+	int write(const void * data, unsigned size);
+	int read(void * data, unsigned size);
+	int readLine(void * data, unsigned maxSize);
+	~CConnection(void);
+};
+
+template<> DLL_EXPORT 
+void CConnection::saveSerializable<std::string>(const std::string &data);
+template <>DLL_EXPORT 
+void CConnection::loadSerializable<std::string>(std::string &data);
+
+

+ 32 - 0
lib/Makefile.am

@@ -0,0 +1,32 @@
+noinst_LIBRARIES = libvcmi.a
+#vcmi_LDADD = $(BOOST_SYSTEM_LIB) $(BOOST_FILESYSTEM_LIB) $(BOOST_THREAD_LIB)
+#AM_CXXFLAGS = $(BOOST_CPPFLAGS)
+libvcmi_a_SOURCES = \
+		    ../hch/CAmbarCendamo.cpp \
+../hch/CArtHandler.cpp \
+../hch/CBuildingHandler.cpp \
+../hch/CCreatureHandler.cpp \
+../hch/CDefObjInfoHandler.cpp \
+../CGameState.cpp \
+../hch/CHeroHandler.cpp \
+../hch/CLodHandler.cpp \
+../hch/CObjectHandler.cpp \
+./Connection.cpp \
+../hch/CTownHandler.cpp \
+../map.cpp \
+../stdafx.cpp \
+./VCMI_Lib.cpp \
+../hch/CAmbarCendamo.h \
+../hch/CArtHandler.h \
+../hch/CBuildingHandler.h \
+../hch/CCreatureHandler.h \
+../hch/CDefObjInfoHandler.h \
+../CGameState.h \
+../hch/CHeroHandler.h \
+../hch/CLodHandler.h \
+../hch/CObjectHandler.h \
+./Connection.h \
+../hch/CTownHandler.h \
+../map.h \
+./NetPacks.h \
+./VCMI_Lib.h

+ 337 - 0
lib/NetPacks.h

@@ -0,0 +1,337 @@
+#include "../global.h"
+struct IPack
+{
+	virtual ui16 getType()const = 0 ;
+	//template<ui16 Type>
+	//static bool isType(const IPack * ip)
+	//{
+	//	return Type == ip->getType();
+	//}
+	template<ui16 Type>
+	static bool isType(IPack * ip)
+	{
+		return Type == ip->getType();
+	}
+	//template<ui16 Type>
+	//static bool isType(const IPack & ip)
+	//{
+	//	return Type == ip.getType();
+	//}
+};
+template <typename T> struct CPack
+	:public IPack
+{
+	ui16 type; 
+	ui16 getType() const{return type;}
+	T* This(){return static_cast<T*>(this);};
+};
+struct NewTurn : public CPack<NewTurn> //101
+{
+	struct Hero
+	{
+		ui32 id, move, mana; //id is a general serial id
+		template <typename Handler> void serialize(Handler &h, const int version)
+		{
+			h & id & move & mana;
+		}
+		bool operator<(const Hero&h)const{return id < h.id;}
+	};
+	struct Resources
+	{
+		ui8 player;
+		si32 resources[RESOURCE_QUANTITY];
+		template <typename Handler> void serialize(Handler &h, const int version)
+		{
+			h & player & resources;
+		}
+		bool operator<(const Resources&h)const{return player < h.player;}
+	};
+
+	std::set<Hero> heroes; //updates movement and mana points
+	std::set<Resources> res;//resource list
+	ui32 day;
+	bool resetBuilded;
+
+	NewTurn(){type = 101;};
+
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & heroes & res & day & resetBuilded;
+	}
+}; 
+struct SetResource : public CPack<SetResource> //102
+{
+	SetResource(){type = 102;};
+
+	ui8 player, resid;
+	si32 val;
+
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & player & resid & val;
+	}
+}; 
+struct SetResources : public CPack<SetResources> //104
+{
+	SetResources(){type = 104;};
+	ui8 player;
+	std::vector<si32> res; //res[resid] => res amount
+
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & player & res;
+	}
+}; 
+struct SetPrimSkill : public CPack<SetPrimSkill> //105
+{
+	SetPrimSkill(){type = 105;};
+	ui8 abs; //0 - changes by value; 1 - sets to value
+	si32 id;
+	ui16 which, val;
+
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & abs & id & which & val;
+	}
+}; 
+struct RemoveHero : public CPack<RemoveHero> //500
+{
+	RemoveHero(){type = 500;};
+	RemoveHero(si32 ID){id = ID;type = 500;};
+	si32 id;
+
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & id;
+	}
+}; 
+struct TryMoveHero : public CPack<TryMoveHero> //501
+{
+	TryMoveHero(){type = 501;};
+
+	ui32 id, movePoints;
+	ui8 result;
+	int3 start, end;
+	std::set<int3> fowRevealed; //revealed tiles
+
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & id & result & start & end & movePoints & fowRevealed;
+	}
+}; 
+struct SetGarrisons : public CPack<SetGarrisons> //502
+{
+	SetGarrisons(){type = 502;};
+	std::map<ui32,CCreatureSet> garrs;
+
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & garrs;
+	}
+}; 
+struct SetStrInfo : public CPack<SetStrInfo> //503
+{
+	SetStrInfo(){type = 503;};
+	si32 tid;
+	std::map<si32,ui32> cres;
+
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & tid & cres;
+	}
+};  
+struct NewStructures : public CPack<NewStructures> //504
+{
+	NewStructures(){type = 504;};
+	si32 tid;
+	std::set<si32> bid;
+	si16 builded; 
+
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & tid & bid & builded;
+	}
+}; 
+struct MetaString : public CPack<MetaString> //2001 helper for object scrips
+{
+	std::vector<std::string> strings;
+	std::vector<std::pair<ui8,ui32> > texts; //pairs<text handler type, text number>; types: 1 - generaltexthandler->all; 2 - objh->xtrainfo; 3 - objh->names; 4 - objh->restypes; 5 - arth->artifacts[id].name; 6 - generaltexth->arraytxt; 7 - creh->creatures[os->subID].namePl; 8 - objh->creGens; 9 - objh->mines[ID].first; 10 - objh->mines[ID].second; 11 - objh->advobtxt
+	std::vector<si32> message;
+	std::vector<std::string> replacements;
+
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & strings & texts & message & replacements;
+	}
+
+	MetaString& operator<<(const std::pair<ui8,ui32> &txt)
+	{
+		message.push_back(-((si32)texts.size())-1);
+		texts.push_back(txt);
+		return *this;
+	}
+	MetaString& operator<<(const std::string &txt)
+	{
+		message.push_back(strings.size()+1);
+		strings.push_back(txt);
+		return *this;
+	}
+	void clear()
+	{
+		strings.clear();
+		texts.clear();
+		message.clear();
+	}
+
+	MetaString(){type = 2001;};
+}; 
+struct Component : public CPack<Component> //2002 helper for object scrips informations
+{
+	ui16 id, subtype; //ids: 0 - primskill; 1 - secskill; 2 - resource; 3 - creature; 4 - artifact; 5 - experience
+	si32 val; // + give; - take
+	si16 when; // 0 - now; +x - within x days; -x - per x days
+
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & id & subtype & val & when;
+	}
+	Component(){type = 2002;};
+	Component(ui16 Type, ui16 Subtype, si32 Val, si16 When):id(Type),subtype(Subtype),val(Val),when(When){type = 2002;};
+};
+
+struct InfoWindow : public CPack<InfoWindow> //103  - displays simple info window
+{
+	MetaString text;
+	std::vector<Component> components;
+	ui8 player;
+
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & text & components & player;
+	}
+	InfoWindow(){type = 103;};
+};
+
+struct SetObjectProperty : public CPack<SetObjectProperty>//1001
+{
+	ui32 id;
+	ui8 what; //1 - owner; 2 - blockvis
+	ui32 val;
+	SetObjectProperty(){type = 1001;};
+	SetObjectProperty(ui32 ID, ui8 What, ui32 Val):id(ID),what(What),val(Val){type = 1001;};
+	
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & id & what & val;
+	}
+};
+
+struct SetHoverName : public CPack<SetHoverName>//1002
+{
+	ui32 id;
+	MetaString name;
+	SetHoverName(){type = 1002;};
+	SetHoverName(ui32 ID, MetaString& Name):id(ID),name(Name){type = 1002;};
+	
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & id & name;
+	}
+};
+struct HeroLevelUp : public CPack<HeroLevelUp>//2000
+{
+	si32 id;
+	ui8 primskill, level;
+	std::set<ui16> skills;
+
+	HeroLevelUp(){type = 2000;};
+	
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & id & primskill & level & skills;
+	}
+};
+struct BattleInfo;
+struct BattleStart : public CPack<BattleStart>//3000
+{
+	BattleInfo * info;
+
+	BattleStart(){type = 3000;};
+	
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & info;
+	}
+};
+struct BattleNextRound : public CPack<BattleNextRound>//3001
+{
+	si32 round;
+
+	BattleNextRound(){type = 3001;};
+	
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & round;
+	}
+};
+struct BattleSetActiveStack : public CPack<BattleSetActiveStack>//3002
+{
+	ui32 stack;
+
+	BattleSetActiveStack(){type = 3002;};
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & stack;
+	}
+};
+struct BattleResult : public CPack<BattleResult>//3003
+{
+	ui8 result; //0 - normal victory; 1 - escape; 2 - surrender
+	ui8 winner; //0 - attacker, 1 - defender, [2 - draw (should be possible?)]
+	std::set<std::pair<ui32,si32> > s1, s2; //first => casualties of attackers - set of pairs crid<>number
+	ui32 exp[2]; //exp for attacker and defender
+	std::set<ui32> artifacts; //artifacts taken from loser to winner
+
+
+
+	BattleResult(){type = 3003;};
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & result & winner & s1 & s2 & exp & artifacts;
+	}
+};
+
+struct BattleStackMoved : public CPack<BattleStackMoved>//3004
+{
+	ui32 stack, tile;
+	ui8 flags;
+
+
+
+	BattleStackMoved(){flags = 0; type = 3004;};
+	bool startMoving()
+	{
+		return flags & 1;
+	}
+	bool endMoving()
+	{
+		return flags & 2;
+	}
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & stack & tile & flags;
+	}
+};
+
+struct ShowInInfobox : public CPack<ShowInInfobox> //107
+{
+	ShowInInfobox(){type = 107;};
+	ui8 player;
+	Component c;
+	MetaString text;
+
+	template <typename Handler> void serialize(Handler &h, const int version)
+	{
+		h & player & c & text;
+	}
+}; 

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