diff --git a/AI/EmptyAI/CEmptyAI.cpp b/AI/EmptyAI/CEmptyAI.cpp index 345659259..658b947e0 100644 --- a/AI/EmptyAI/CEmptyAI.cpp +++ b/AI/EmptyAI/CEmptyAI.cpp @@ -10,6 +10,7 @@ void CEmptyAI::init(ICallback * CB) } void CEmptyAI::yourTurn() { + cb->endTurn(); } void CEmptyAI::heroKilled(const CGHeroInstance *) { diff --git a/AI/EmptyAI/exp_funcs.cpp b/AI/EmptyAI/exp_funcs.cpp index 769885432..1c700fe5d 100644 --- a/AI/EmptyAI/exp_funcs.cpp +++ b/AI/EmptyAI/exp_funcs.cpp @@ -1,30 +1,30 @@ +#define VCMI_DLL #include "../../AI_Base.h" #include "CEmptyAI.h" #include #include std::set 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); diff --git a/AI_Base.h b/AI_Base.h index dfd9df5fa..cf1ecd3d0 100644 --- a/AI_Base.h +++ b/AI_Base.h @@ -1,16 +1,15 @@ #pragma once #include #include -#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 + + + + + + + + + diff --git a/AUTHORS b/AUTHORS index 8b1378917..e69de29bb 100644 --- a/AUTHORS +++ b/AUTHORS @@ -1 +0,0 @@ - diff --git a/AdventureMapButton.cpp b/AdventureMapButton.cpp index b44480730..6bda0df31 100644 --- a/AdventureMapButton.cpp +++ b/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;iourImages.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; isize();i++) { - temp = CGI->spriteh->giveDef((*add)[i]); + temp = CDefHandler::giveDef((*add)[i]); temp->notFreeImgs = true; for (int j=0;jourImages.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 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; diff --git a/CAdvmapInterface.cpp b/CAdvmapInterface.cpp index d01c6c22c..4e1f130b6 100644 --- a/CAdvmapInterface.cpp +++ b/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 #include "AdventureMapButton.h" #include "CHeroWindow.h" -#pragma warning (disable : 4355) +#include "client/Graphics.h" +#include "hch/CObjectHandler.h" +#include +#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;iplayerColors[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; imh->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; iipos.w) && (pos.y*ho+jjpos.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; iipos.w) && (pos.y*ho+jjpos.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; yourImages.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 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(35,577)),(std::pair(120,577)),(std::pair(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(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) { diff --git a/CBattleInterface.cpp b/CBattleInterface.cpp index 471793ed4..39c5475ee 100644 --- a/CBattleInterface.cpp +++ b/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 #include +#include "lib/CondSh.h" +#ifndef __GNUC__ +const double M_PI = 3.14159265358979323846; +#else #define _USE_MATH_DEFINES #include +#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(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; gformat->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 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; iourImages.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; iourImages.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) { diff --git a/CBattleInterface.h b/CBattleInterface.h index 196f8ade9..f4f3ca400 100644 --- a/CBattleInterface.h +++ b/CBattleInterface.h @@ -9,6 +9,7 @@ class CDefHandler; class CStack; class CCallback; class AdventureMapButton; +template struct CondSh; class CBattleHero : public IShowable, public CIntObject { @@ -112,7 +113,7 @@ private: }; std::list 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 *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: diff --git a/CCallback.cpp b/CCallback.cpp index 59acf22db..e5c47b7b4 100644 --- a/CCallback.cpp +++ b/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 +#include +#include "lib/NetPacks.h" +#include +#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 > 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 >::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::iterator i = gs->players.begin() ; - gs->day++; - for (std::set::iterator i=gs->cppscripts.begin();i!=gs->cppscripts.end();i++) - { - (*i)->newTurn(); - } - for ( std::map::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;jsecond.towns.size();j++) - { - i->second.towns[j]->builded=0; - if(getDate(1)==1) //first day of week - { - for(int k=0;ksecond.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->firstsecond.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::iterator j=CGI->state->players.begin(); j!=CGI->state->players.end(); ++j) + for(std::map::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; pitblockVisit) - 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; iiistate) //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; xdgetPosition(false).x-xd)*(hero->getPosition(false).x-xd); - int deltaY = (hero->getPosition(false).y-yd)*(hero->getPosition(false).y-yd); - if(deltaX+deltaYgetSightDistance()*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::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; iiicheckFunc(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; iiiblockVisit) - { - 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 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::iterator itr = std::find_if(mess.res->begin(),mess.res->end(),IPack::isType<501>); + TryMoveHero tmh = *static_cast(*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 Parka; - for(std::map::iterator av=t->strInfo.creatures.begin();av!=t->strInfo.creatures.end();av++) + for(std::map::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 > parb; + std::pair > 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(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."<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(obj)->visitedTown)) { CGTownInstance * t; @@ -349,7 +209,7 @@ UpgradeInfo CCallback::getUpgradeInfo(const CArmedInstance *obj, int stackPos) t = static_cast(const_cast(obj)); else t = static_cast(obj)->visitedTown; - for(std::set::iterator i=t->builtBuildings.begin(); i!=t->builtBuildings.end(); i++) + for(std::set::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 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 lock(*gs->mx); if (gs->currentPlayer!=player) //TODO: checking if we are allowed to give that info return NULL; if (!mode) if(valplayers[player].heroes.size()) return gs->players[player].heroes[val]; else return NULL; - else + else { for (int i=0; iplayers[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 lock(*gs->mx); return gs->players[player].resources[type]; } -std::vector CCallback::getResourceAmount() +std::vector CCallback::getResourceAmount() { + boost::shared_lock 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 lock(*gs->mx); + return gs->getDate(mode); +} +std::vector < std::string > CCallback::getObjDescriptions(int3 pos) +{ + boost::shared_lock lock(*gs->mx); + std::vector 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;inodes.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 > > & CCallback::getVisibilityMap() +std::vector< std::vector< std::vector > > & CCallback::getVisibilityMap() { + boost::shared_lock lock(*gs->mx); return gs->players[player].fogOfWarMap; } bool CCallback::isVisible(int3 pos, int Player) { + boost::shared_lock 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 lock(*gs->mx); std::vector < const CGTownInstance *> ret = std::vector < const CGTownInstance *>(); - for ( std::map::iterator i=gs->players.begin() ; i!=gs->players.end();i++) + for ( std::map::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::iterator i=gs->players.begin() ; i!=gs->players.end();i++) + boost::shared_lock lock(*gs->mx); + std::vector < const CGHeroInstance *> ret; + for(int i=0;imap->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::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 lock(*gs->mx); for (int i=0; iplayers[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(getGarrison(s1)), *S2 = const_cast(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->tempOwnerplayerint.size(); ++b) - { - if(CGI->playerint[b]->playerID == s1->tempOwner) - { - CGI->playerint[b]->garrisonChanged(s1); - break; - } - } - } - if((s2->tempOwnerplayerint.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(getGarrison(s1)), *S2 = const_cast(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->tempOwnerplayerint.size(); ++b) - { - if(CGI->playerint[b]->playerID == s1->tempOwner) - { - CGI->playerint[b]->garrisonChanged(s1); - break; - } - } - } - if((s2->tempOwnerplayerint.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(getGarrison(s1)), *S2 = const_cast(getGarrison(s2)); - if ((S1->slots[p1].secondslots[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->tempOwnerplayerint.size(); ++b) - { - if(CGI->playerint[b]->playerID == s1->tempOwner) - { - CGI->playerint[b]->garrisonChanged(s1); - break; - } - } - } - if((s2->tempOwnerplayerint.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(hero); - CGI->mh->removeObject(Vhero); - std::vector::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 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(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 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 lock(*gs->mx); + return gs->battleGetStack(pos); } -CStack CCallback::battleGetStackByID(int ID) +CStack* CCallback::battleGetStackByID(int ID) { - for(int g=0; gstate->curB->stacks.size(); ++g) - { - if(CGI->state->curB->stacks[g]->ID == ID) - return *(CGI->state->curB->stacks[g]); - } - return CStack(); + boost::shared_lock 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; gstate->curB->stacks.size(); ++g) + boost::shared_lock lock(*gs->mx); + for(int g=0; gcurB->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 CCallback::battleGetStacks() { + boost::shared_lock lock(*gs->mx); std::map ret; - for(int g=0; gstate->curB->stacks.size(); ++g) + for(int g=0; gcurB->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; hstate->curB->stacks.size(); ++h) + boost::shared_lock lock(*gs->mx); + for(int h=0; hcurB->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 CCallback::battleGetAvailableHexes(int ID) { - return CGI->state->battleGetRange(ID); + boost::shared_lock lock(*gs->mx); + return gs->curB->getAccessibility(ID); + //return gs->battleGetRange(ID); } bool CCallback::battleIsStackMine(int ID) { - for(int h=0; hstate->curB->stacks.size(); ++h) + boost::shared_lock lock(*gs->mx); + for(int h=0; hcurB->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 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 (whichprimSkills[which]+=val; - for (int i=0; iplayerint.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 "<level<::*g = (hero->level>9) ? (&std::pair::second) : (&std::pair::first); - for(;xtype->heroClass->primChance[x].*g; - if(rprimSkills[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 * 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; iplayerint.size();i++) - { - if (CGI->playerint[i]->human) - ((CPlayerInterface*)(CGI->playerint[i]))->showInfoDialog(text,*components); - } - } -} - -void CScriptCallback::showSelDialog(int player, std::string text, std::vector*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(CGI->playerint[gs->players[player].serial]); - if(i) - i->showComp(*comp); -} -void CScriptCallback::heroVisitCastle(CGObjectInstance * ob, int heroID) -{ - CGTownInstance * n; - if(n = dynamic_cast(ob)) - { - n->visitingHero = CGI->state->getHero(heroID,0); - CGI->state->getHero(heroID,0)->visitedTown = n; - for(int b=0; bplayerint.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(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;iartifacts.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; -} diff --git a/CCallback.h b/CCallback.h index 07d9b2c0b..8cb7ce1ae 100644 --- a/CCallback.h +++ b/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 > > & getVisibilityMap()=0; //returns visibility map (TODO: make it const) + virtual std::vector< std::vector< std::vector > > & 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 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 > > & getVisibilityMap(); //returns visibility map (TODO: make it const) + std::vector< std::vector< std::vector > > & 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 getResourceAmount(); + std::vector 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 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 * components); //TODO: obslugiwac nulle - void showSelDialog(int player, std::string text, std::vector*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 diff --git a/CCastleInterface.cpp b/CCastleInterface.cpp index e61625f87..bda748917 100644 --- a/CCastleInterface.cpp +++ b/CCastleInterface.cpp @@ -8,15 +8,17 @@ #include "hch/CTownHandler.h" #include "AdventureMapButton.h" #include "hch/CBuildingHandler.h" +#include "hch/CDefHandler.h" #include #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 "<ID<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 "<ID<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;i3)?(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() > s; //group - id - for (std::set::const_iterator i=town->builtBuildings.begin();i!=town->builtBuildings.end();i++) + for (std::set::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 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; diff --git a/CConsoleHandler.cpp b/CConsoleHandler.cpp index b41e3f9c7..d08d59d2b 100644 --- a/CConsoleHandler.cpp +++ b/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."<>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: "<heroh->heroInstances.size()<>heronum; - #ifndef __GNUC__ - std::cout<<"Position of hero "<heroh->heroInstances[heronum]->getPosition(false)<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>>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<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; cobjh->objInstances.size(); ++c) - { - CGI->mh->printObject(CGI->objh->objInstances[c]); - } - break; + //case 'P': + // std::cout<<"Policzyc sciezke."<>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: "<heroh->heroInstances.size()<>heronum; + // std::cout<<"Position of hero "<heroh->heroInstances[heronum]->getPosition(false)<>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<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; cobjh->objInstances.size(); ++c) + // { + // CGI->mh->printObject(CGI->objh->objInstances[c]); + // } + // break; } //SDL_Delay(100); - delete p; + //delete p; } SDL_Delay(10); } diff --git a/CConsoleHandler.h b/CConsoleHandler.h index 8b183a9cd..e84579b8c 100644 --- a/CConsoleHandler.h +++ b/CConsoleHandler.h @@ -7,6 +7,8 @@ class CConsoleHandler public: void runConsole(); + friend class CClient; + #ifndef __GNUC__ friend int _tmain(int argc, _TCHAR* argv[]); #else diff --git a/CCursorHandler.cpp b/CCursorHandler.cpp index 9ed52d384..5d532d670 100644 --- a/CCursorHandler.cpp +++ b/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); -} \ No newline at end of file diff --git a/CCursorHandler.h b/CCursorHandler.h index 5b9ca77e8..313e96d03 100644 --- a/CCursorHandler.h +++ b/CCursorHandler.h @@ -1,6 +1,7 @@ #ifndef CCURSORHANDLER_H #define CCURSORHANDLER_H - +#include "global.h" +#include 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 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(); }; diff --git a/CGameInfo.cpp b/CGameInfo.cpp index b7cadcc04..e677d0c4e 100644 --- a/CGameInfo.cpp +++ b/CGameInfo.cpp @@ -1,4 +1,4 @@ #include "stdafx.h" #include "CGameInfo.h" -CGameInfo * CGameInfo::mainObj; +CGameInfo * CGI; diff --git a/CGameInfo.h b/CGameInfo.h index d0f3fb969..e10c0f3be 100644 --- a/CGameInfo.h +++ b/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 @@ -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 playerint; - std::vector playerColors; - std::vector playerColorInfo; //gems from adventure map interface - SDL_Color neutralColor; - StartInfo scenarioOps; }; #endif //CGAMEINFO_H diff --git a/CGameInterface.cpp b/CGameInterface.cpp index f542dc19e..0a847d999 100644 --- a/CGameInterface.cpp +++ b/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 "<player*/< #include +#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 & components, int askID){}; + virtual void showInfoDialog(std::string text, std::vector &components){}; + virtual void showSelDialog(std::string text, std::vector & 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 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 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; diff --git a/CGameState.cpp b/CGameState.cpp index 942e10c0b..0dbca2669 100644 --- a/CGameState.cpp +++ b/CGameState.cpp @@ -1,356 +1,165 @@ -#include "CGameState.h" -#include "CGameInterface.h" -#include "CPlayerInterface.h" +#define VCMI_DLL #include -#include "SDL_thread.h" -#include "SDL_Extensions.h" -#include "CBattleInterface.h" //for CBattleHex #include +#include +#include "CGameState.h" +#include +#include "hch/CDefObjInfoHandler.h" +#include "hch/CArtHandler.h" +#include "hch/CTownHandler.h" +#include "hch/CHeroHandler.h" +#include "hch/CObjectHandler.h" +#include "hch/CCreatureHandler.h" +#include "lib/VCMI_Lib.h" +#include "map.h" +#include "StartInfo.h" +#include "lib/NetPacks.h" +#include +#include +#include +boost::rand48 ran; - -class CMP_stack +CGObjectInstance * createObject(int id, int subid, int3 pos, int owner) { -public: - bool operator ()(const CStack* a, const CStack* b) + CGObjectInstance * nobj; + switch(id) { - return (a->creature->speed)>(b->creature->speed); - } -} cmpst ; - -void CGameState::battle(CCreatureSet * army1, CCreatureSet * army2, int3 tile, CArmedInstance *hero1, CArmedInstance *hero2) -{ - curB = new BattleInfo(); - std::vector & stacks = (curB->stacks); - - curB->army1=army1; - curB->army2=army2; - curB->hero1=dynamic_cast(hero1); - curB->hero2=dynamic_cast(hero2); - curB->side1=(hero1)?(hero1->tempOwner):(-1); - curB->side2=(hero2)?(hero2->tempOwner):(-1); - curB->round = -2; - curB->stackActionPerformed = false; - for(std::map >::iterator i = army1->slots.begin(); i!=army1->slots.end(); i++) - { - stacks.push_back(new CStack(i->second.first,i->second.second, hero1->tempOwner, stacks.size(), true)); - stacks[stacks.size()-1]->ID = stacks.size()-1; - } - //initialization of positions - switch(army1->slots.size()) //for attacker - { - case 0: - break; - case 1: - stacks[0]->position = 86; //6 - break; - case 2: - stacks[0]->position = 35; //3 - stacks[1]->position = 137; //9 - break; - case 3: - stacks[0]->position = 35; //3 - stacks[1]->position = 86; //6 - stacks[2]->position = 137; //9 - break; - case 4: - stacks[0]->position = 1; //1 - stacks[1]->position = 69; //5 - stacks[2]->position = 103; //7 - stacks[3]->position = 171; //11 - break; - case 5: - stacks[0]->position = 1; //1 - stacks[1]->position = 35; //3 - stacks[2]->position = 86; //6 - stacks[3]->position = 137; //9 - stacks[4]->position = 171; //11 - break; - case 6: - stacks[0]->position = 1; //1 - stacks[1]->position = 35; //3 - stacks[2]->position = 69; //5 - stacks[3]->position = 103; //7 - stacks[4]->position = 137; //9 - stacks[5]->position = 171; //11 - break; - case 7: - stacks[0]->position = 1; //1 - stacks[1]->position = 35; //3 - stacks[2]->position = 69; //5 - stacks[3]->position = 86; //6 - stacks[4]->position = 103; //7 - stacks[5]->position = 137; //9 - stacks[6]->position = 171; //11 - break; - default: //fault - break; - } - for(std::map >::iterator i = army2->slots.begin(); i!=army2->slots.end(); i++) - stacks.push_back(new CStack(i->second.first,i->second.second, hero2 ? hero2->tempOwner : 255, stacks.size(), false)); - switch(army2->slots.size()) //for defender - { - case 0: - break; - case 1: - stacks[0+army1->slots.size()]->position = 100; //6 - break; - case 2: - stacks[0+army1->slots.size()]->position = 49; //3 - stacks[1+army1->slots.size()]->position = 151; //9 - break; - case 3: - stacks[0+army1->slots.size()]->position = 49; //3 - stacks[1+army1->slots.size()]->position = 100; //6 - stacks[2+army1->slots.size()]->position = 151; //9 - break; - case 4: - stacks[0+army1->slots.size()]->position = 15; //1 - stacks[1+army1->slots.size()]->position = 83; //5 - stacks[2+army1->slots.size()]->position = 117; //7 - stacks[3+army1->slots.size()]->position = 185; //11 - break; - case 5: - stacks[0+army1->slots.size()]->position = 15; //1 - stacks[1+army1->slots.size()]->position = 49; //3 - stacks[2+army1->slots.size()]->position = 100; //6 - stacks[3+army1->slots.size()]->position = 151; //9 - stacks[4+army1->slots.size()]->position = 185; //11 - break; - case 6: - stacks[0+army1->slots.size()]->position = 15; //1 - stacks[1+army1->slots.size()]->position = 49; //3 - stacks[2+army1->slots.size()]->position = 83; //5 - stacks[3+army1->slots.size()]->position = 117; //7 - stacks[4+army1->slots.size()]->position = 151; //9 - stacks[5+army1->slots.size()]->position = 185; //11 - break; - case 7: - stacks[0+army1->slots.size()]->position = 15; //1 - stacks[1+army1->slots.size()]->position = 49; //3 - stacks[2+army1->slots.size()]->position = 83; //5 - stacks[3+army1->slots.size()]->position = 100; //6 - stacks[4+army1->slots.size()]->position = 117; //7 - stacks[5+army1->slots.size()]->position = 151; //9 - stacks[6+army1->slots.size()]->position = 185; //11 - break; - default: //fault - break; - } - for(int g=0; gposition%17)==1 && stacks[g]->creature->isDoubleWide()) + case 34: //hero { - stacks[g]->position += 1; - } - else if((stacks[g]->position%17)==15 && stacks[g]->creature->isDoubleWide()) - { - stacks[g]->position -= 1; - } - } - std::stable_sort(stacks.begin(),stacks.end(),cmpst); - - //for start inform players about battle - for(std::map::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[tile.x][tile.y][tile.z]) - { //player should be notified - tribool side = tribool::indeterminate_value; - if(j->first == curB->side1) //player is attacker - side = false; - else if(j->first == curB->side2) //player is defender - side = true; - else - continue; //no witnesses - if(CGI->playerint[j->second.serial]->human) + CGHeroInstance * nobj; + nobj = new CGHeroInstance(); + nobj->pos = pos; + nobj->tempOwner = owner; + nobj->defInfo = new CGDefInfo(); + nobj->defInfo->id = 34; + nobj->defInfo->subid = subid; + nobj->defInfo->printPriority = 0; + nobj->type = VLC->heroh->heroes[subid]; + for(int i=0;i<6;i++) { - ((CPlayerInterface*)( CGI->playerint[j->second.serial] ))->battleStart(army1, army2, tile, curB->hero1, curB->hero2, side); - } - else - { - //CGI->playerint[j->second.serial]->battleStart(army1, army2, tile, curB->hero1, curB->hero2, side); + nobj->defInfo->blockMap[i]=255; + nobj->defInfo->visitMap[i]=0; } + nobj->ID = id; + nobj->subID = subid; + nobj->defInfo->handler=NULL; + nobj->defInfo->blockMap[5] = 253; + nobj->defInfo->visitMap[5] = 2; + nobj->artifacts.resize(20); + nobj->artifWorn[16] = 3; + nobj->portrait = subid; + nobj->primSkills.resize(4); + nobj->primSkills[0] = nobj->type->heroClass->initialAttack; + nobj->primSkills[1] = nobj->type->heroClass->initialDefence; + nobj->primSkills[2] = nobj->type->heroClass->initialPower; + nobj->primSkills[3] = nobj->type->heroClass->initialKnowledge; + nobj->mana = 10 * nobj->primSkills[3]; + return nobj; } + case 98: //town + nobj = new CGTownInstance; + break; + default: //rest of objects + nobj = new CGObjectInstance; + nobj->defInfo = VLC->dobjinfo->gobjs[id][subid]; + break; } + nobj->ID = id; + nobj->subID = subid; + if(!nobj->defInfo) + std::cout <<"No def declaration for " <pos = pos; + //nobj->state = NULL;//new CLuaObjectScript(); + nobj->tempOwner = owner; + nobj->info = NULL; + nobj->defInfo->id = id; + nobj->defInfo->subid = subid; - curB->round++; - if( (curB->hero1 && curB->hero1->getSecSkillLevel(19)>=0) || ( curB->hero2 && curB->hero2->getSecSkillLevel(19)>=0) )//someone has tactics - { - //TODO: wywolania dla rundy -1, ograniczenie pola ruchu, etc - } - - curB->round++; - - //SDL_Thread * eventh = SDL_CreateThread(battleEventThread, NULL); - - while(true) //till the end of the battle ;] - { - bool battleEnd = false; - //tell players about next round - for(int v=0; vplayerint.size(); ++v) - CGI->playerint[v]->battleNewRound(curB->round); - - //stack loop - for(int i=0;iactiveStack = i; - curB->stackActionPerformed = false; - if(stacks[i]->alive) //indicate posiibility of making action for this unit - { - if(stacks[i]->owner==255) //neutral unit - { - } - else if(CGI->playerint[stacks[i]->owner]->human) - { - BattleAction ba = ((CPlayerInterface*)CGI->playerint[stacks[i]->owner])->activeStack(stacks[i]->ID); - switch(ba.actionType) - { - case 2: //walk - { - battleMoveCreatureStack(ba.stackNumber, ba.destinationTile); - } - case 3: //defend - { - break; - } - case 4: //retreat/flee - { - for(int v=0; vplayerint.size(); ++v) //tell about the end of this battle to interfaces - CGI->playerint[v]->battleEnd(army1, army2, hero1, hero2, std::vector(), 0, false); - battleEnd = true; - break; - } - case 6: //walk or attack - { - battleMoveCreatureStack(ba.stackNumber, ba.destinationTile); - battleAttackCreatureStack(ba.stackNumber, ba.destinationTile); - break; - } - case 7: //shoot - { - battleShootCreatureStack(ba.stackNumber, ba.destinationTile); - break; - } - } - } - else - { - //CGI->playerint[stacks[i]->owner]->activeStack(stacks[i]->ID); - } - } - if(battleEnd) - break; - //sprawdzic czy po tej akcji ktoras strona nie wygrala bitwy - } - if(battleEnd) - break; - curB->round++; - SDL_Delay(50); - } - - for(int i=0;iID==34 || nobj->ID==98) + return nobj; + nobj->defInfo = VLC->dobjinfo->gobjs[id][subid]; + //if(!nobj->defInfo->handler) + //{ + // nobj->defInfo->handler = CDefHandler::giveDef(nobj->defInfo->name); + // nobj->defInfo->width = nobj->defInfo->handler->ourImages[0].bitmap->w/32; + // nobj->defInfo->height = nobj->defInfo->handler->ourImages[0].bitmap->h/32; + //} + return nobj; } - -bool CGameState::battleMoveCreatureStack(int ID, int dest) +CStack * BattleInfo::getStack(int stackID) { - //first checks - if(curB->stackActionPerformed) //because unit cannot be moved more than once - return false; - - unsigned char owner = -1; //owner moved of unit - for(int g=0; gstacks.size(); ++g) + for(int g=0; gstacks[g]->ID == ID) - { - owner = curB->stacks[g]->owner; - break; - } + if(stacks[g]->ID == stackID) + return stacks[g]; } - - bool stackAtEnd = false; //true if there is a stack at the end of the path (we should attack it) - int numberOfStackAtEnd = -1; - for(int g=0; gstacks.size(); ++g) + return NULL; +} +CStack * BattleInfo::getStackT(int tileID) +{ + for(int g=0; gstacks[g]->position == dest - || (curB->stacks[g]->creature->isDoubleWide() && curB->stacks[g]->attackerOwned && curB->stacks[g]->position-1 == dest) - || (curB->stacks[g]->creature->isDoubleWide() && !curB->stacks[g]->attackerOwned && curB->stacks[g]->position+1 == dest)) + if(stacks[g]->position == tileID + || (stacks[g]->creature->isDoubleWide() && stacks[g]->attackerOwned && stacks[g]->position-1 == tileID) + || (stacks[g]->creature->isDoubleWide() && !stacks[g]->attackerOwned && stacks[g]->position+1 == tileID)) { - if(curB->stacks[g]->alive) + if(stacks[g]->alive) { - stackAtEnd = true; - numberOfStackAtEnd = g; - break; + return stacks[g]; } } } + return NULL; +} +void BattleInfo::getAccessibilityMap(bool *accessibility) +{ + memset(accessibility,1,187); //initialize array with trues + for(int g=0; galive) //we don't want to lock enemy's positions and this units' position + continue; - //selecting moved stack - CStack * curStack = NULL; - for(int y=0; ystacks.size(); ++y) - { - if(curB->stacks[y]->ID == ID) + accessibility[stacks[g]->position] = false; + if(stacks[g]->creature->isDoubleWide()) //if it's a double hex creature { - curStack = curB->stacks[y]; - break; + if(stacks[g]->attackerOwned) + accessibility[stacks[g]->position-1] = false; + else + accessibility[stacks[g]->position+1] = false; } } - if(!curStack) - return false; - //initing necessary tables - bool accessibility[187]; //accesibility of hexes - for(int k=0; k<187; k++) - accessibility[k] = true; - for(int g=0; gstacks.size(); ++g) + //TODO: obstacles +} +void BattleInfo::getAccessibilityMapForTwoHex(bool *accessibility, bool atackerSide) //send pointer to at least 187 allocated bytes +{ + bool mac[187]; + getAccessibilityMap(mac); + memcpy(accessibility,mac,187); + + for(int b=0; b<187; ++b) { - if(curB->stacks[g]->ID != ID && curB->stacks[g]->alive) //we don't want to lock enemy's positions and this units' position + if( mac[b] && !(atackerSide ? mac[b-1] : mac[b+1])) { - accessibility[curB->stacks[g]->position] = false; - if(curB->stacks[g]->creature->isDoubleWide()) //if it's a double hex creature - { - if(curB->stacks[g]->attackerOwned) - accessibility[curB->stacks[g]->position-1] = false; - else - accessibility[curB->stacks[g]->position+1] = false; - } + accessibility[b] = false; } } - accessibility[dest] = true; - if(curStack->creature->isDoubleWide()) //locking positions unreachable by two-hex creatures - { - bool mac[187]; - for(int b=0; b<187; ++b) - { - // - // && ( ? (curStack->attackerOwned ? accessibility[curNext-1] : accessibility[curNext+1]) : true ) - mac[b] = accessibility[b]; - if( accessibility[b] && !(curStack->attackerOwned ? accessibility[b-1] : accessibility[b+1])) - { - mac[b] = false; - } - } - mac[curStack->attackerOwned ? curStack->position+1 : curStack->position-1]=true; - for(int v=0; v<187; ++v) - accessibility[v] = mac[v]; - //removing accessibility for side hexes - for(int v=0; v<187; ++v) - if(curStack->attackerOwned ? (v%17)==1 : (v%17)==15) - accessibility[v] = false; - } - if(!stackAtEnd && !accessibility[dest]) - return false; - int predecessor[187]; //for getting the Path + + //removing accessibility for side hexes + for(int v=0; v<187; ++v) + if(atackerSide ? (v%17)==1 : (v%17)==15) + accessibility[v] = false; +} +void BattleInfo::makeBFS(int start, bool*accessibility, int *predecessor, int *dists) //both pointers must point to the at least 187-elements int arrays +{ + //inits for(int b=0; b<187; ++b) predecessor[b] = -1; - //bfsing - int dists[187]; //calculated distances - std::queue hexq; //bfs queue - hexq.push(curStack->position); for(int g=0; g<187; ++g) - dists[g] = 100000000; + dists[g] = 100000000; + + std::queue hexq; //bfs queue + hexq.push(start); dists[hexq.front()] = 0; int curNext = -1; //for bfs loop only (helper var) while(!hexq.empty()) //bfs loop @@ -358,125 +167,764 @@ bool CGameState::battleMoveCreatureStack(int ID, int dest) int curHex = hexq.front(); hexq.pop(); curNext = curHex - ( (curHex/17)%2 ? 18 : 17 ); - if((curNext > 0) && (accessibility[curNext] || curNext==dest) && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //top left + if((curNext > 0) && (accessibility[curNext]) && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //top left { hexq.push(curNext); dists[curNext] = dists[curHex] + 1; predecessor[curNext] = curHex; } curNext = curHex - ( (curHex/17)%2 ? 17 : 16 ); - if((curNext > 0) && (accessibility[curNext] || curNext==dest) && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //top right + if((curNext > 0) && (accessibility[curNext]) && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //top right { hexq.push(curNext); dists[curNext] = dists[curHex] + 1; predecessor[curNext] = curHex; } curNext = curHex - 1; - if((curNext > 0) && (accessibility[curNext] || curNext==dest) && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //left + if((curNext > 0) && (accessibility[curNext]) && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //left { hexq.push(curNext); dists[curNext] = dists[curHex] + 1; predecessor[curNext] = curHex; } curNext = curHex + 1; - if((curNext < 187) && (accessibility[curNext] || curNext==dest) && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //right + if((curNext < 187) && (accessibility[curNext]) && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //right { hexq.push(curNext); dists[curNext] = dists[curHex] + 1; predecessor[curNext] = curHex; } curNext = curHex + ( (curHex/17)%2 ? 16 : 17 ); - if((curNext < 187) && (accessibility[curNext] || curNext==dest) && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //bottom left + if((curNext < 187) && (accessibility[curNext]) && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //bottom left { hexq.push(curNext); dists[curNext] = dists[curHex] + 1; predecessor[curNext] = curHex; } curNext = curHex + ( (curHex/17)%2 ? 17 : 18 ); - if((curNext < 187) && (accessibility[curNext] || curNext==dest) && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //bottom right + if((curNext < 187) && (accessibility[curNext]) && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //bottom right { hexq.push(curNext); dists[curNext] = dists[curHex] + 1; predecessor[curNext] = curHex; } } - //following the Path - if(dists[dest] > curStack->creature->speed && !(stackAtEnd && dists[dest] == curStack->creature->speed+1)) //we can attack a stack if we can go to adjacent hex - return false; +}; + +std::vector BattleInfo::getAccessibility(int stackID) +{ + std::vector ret; + bool ac[187]; + CStack *s = getStack(stackID); + if(s->creature->isDoubleWide()) + getAccessibilityMapForTwoHex(ac,s->attackerOwned); + else + getAccessibilityMap(ac); + + int pr[187], dist[187]; + makeBFS(s->position,ac,pr,dist); + + for(int i=0;i<187;i++) + if(dist[i] <= s->creature->speed) + ret.push_back(i); + + return ret; +} +std::vector BattleInfo::getPath(int start, int dest, bool*accessibility) +{ + int predecessor[187]; //for getting the Path + int dist[187]; //calculated distances + + makeBFS(start,accessibility,predecessor,dist); + + //making the Path std::vector path; int curElem = dest; - while(curElem!=curStack->position) + while(curElem != start) { path.push_back(curElem); curElem = predecessor[curElem]; } - for(int v=path.size()-1; v>=0; --v) - { - if(v!=0 || !stackAtEnd) //it's not the last step - { - LOCPLINT->battleStackMoved(ID, path[v], v==path.size()-1, v==0 || (stackAtEnd && v==1) ); - curStack->position = path[v]; - } - else //if it's last step and we should attack unit at the end - { - LOCPLINT->battleStackAttacking(ID, path[v]); - //counting dealt damage - int finalDmg = calculateDmg(curStack, curB->stacks[numberOfStackAtEnd]); - - //applying damages - int cresKilled = finalDmg / curB->stacks[numberOfStackAtEnd]->creature->hitPoints; - int damageFirst = finalDmg % curB->stacks[numberOfStackAtEnd]->creature->hitPoints; - - if( curB->stacks[numberOfStackAtEnd]->firstHPleft <= damageFirst ) - { - curB->stacks[numberOfStackAtEnd]->amount -= 1; - curB->stacks[numberOfStackAtEnd]->firstHPleft += curB->stacks[numberOfStackAtEnd]->creature->hitPoints - damageFirst; - } - else - { - curB->stacks[numberOfStackAtEnd]->firstHPleft -= damageFirst; - } - - int cresInstackBefore = curB->stacks[numberOfStackAtEnd]->amount; - curB->stacks[numberOfStackAtEnd]->amount -= cresKilled; - if(curB->stacks[numberOfStackAtEnd]->amount<=0) //stack killed - { - curB->stacks[numberOfStackAtEnd]->amount = 0; - LOCPLINT->battleStackKilled(curB->stacks[numberOfStackAtEnd]->ID, finalDmg, std::min(cresKilled, cresInstackBefore) , ID, false); - curB->stacks[numberOfStackAtEnd]->alive = false; - } - else - { - LOCPLINT->battleStackIsAttacked(curB->stacks[numberOfStackAtEnd]->ID, finalDmg, std::min(cresKilled, cresInstackBefore), ID, false); - } - - //damage applied - } - } - curB->stackActionPerformed = true; - LOCPLINT->actionFinished(BattleAction()); - return true; + return path; } -bool CGameState::battleAttackCreatureStack(int ID, int dest) +CStack::CStack(CCreature * C, int A, int O, int I, bool AO) + :creature(C),amount(A),owner(O), alive(true), position(-1), ID(I), attackerOwned(AO), firstHPleft(C->hitPoints) { - int attackedCreaure = -1; //-1 - there is no attacked creature - for(int b=0; bstacks.size(); ++b) //TODO: make upgrades for two-hex cres. +} +void CGameState::apply(IPack * pack) +{ + mx->lock(); + switch(pack->getType()) { - if(curB->stacks[b]->position == dest) + case 101://NewTurn { - attackedCreaure = curB->stacks[b]->ID; + NewTurn * n = static_cast(pack); + day = n->day; + BOOST_FOREACH(NewTurn::Hero h, n->heroes) //give mana/movement point + { + static_cast(map->objects[h.id])->movement = h.move; + static_cast(map->objects[h.id])->mana = h.mana; + } + BOOST_FOREACH(NewTurn::Resources h, n->res) //give resources + { + for(int i=0;iresetBuilded) //reset amount of structures set in this turn in towns + BOOST_FOREACH(CGTownInstance* t, map->towns) + t->builded = 0; break; } + case 102: //set resource amount + { + SetResource *sr = static_cast(pack); + players[sr->player].resources[sr->resid] = sr->val; + break; + } + case 104: + { + SetResources *sr = static_cast(pack); + for(int i=0;ires.size();i++) + players[sr->player].resources[i] = sr->res[i]; + break; + } + case 105: + { + SetPrimSkill *sr = static_cast(pack); + CGHeroInstance *hero = getHero(sr->id); + if(sr->which <4) + { + if(sr->abs) + hero->primSkills[sr->which] = sr->val; + else + hero->primSkills[sr->which] += sr->val; + } + else if(sr->which == 4) //XP + { + if(sr->abs) + hero->exp = sr->val; + else + hero->exp += sr->val; + } + break; + } + case 500: + { + RemoveHero *rh = static_cast(pack); + CGHeroInstance *h = static_cast(map->objects[rh->id]); + std::vector::iterator nitr = std::find(map->heroes.begin(), map->heroes.end(),h); + map->heroes.erase(nitr); + int player = h->tempOwner; + nitr = std::find(players[player].heroes.begin(), players[player].heroes.end(), h); + players[player].heroes.erase(nitr); + map->objects[h->id] = NULL; + break; + } + case 501://hero try-move + { + TryMoveHero * n = static_cast(pack); + CGHeroInstance *h = static_cast(map->objects[n->id]); + h->movement = n->movePoints; + if(n->result) + h->pos = n->end; + else + h->pos = n->start; + BOOST_FOREACH(int3 t, n->fowRevealed) + players[h->getOwner()].fogOfWarMap[t.x][t.y][t.z] = 1; + break; + } + case 502: + { + SetGarrisons * n = static_cast(pack); + for(std::map::iterator i = n->garrs.begin(); i!=n->garrs.end(); i++) + static_cast(map->objects[i->first])->army = i->second; + break; + } + case 503: + { + SetStrInfo *ssi = static_cast(pack); + static_cast(map->objects[ssi->tid])->strInfo.creatures = ssi->cres; + break; + } + case 504: + { + NewStructures *ns = static_cast(pack); + CGTownInstance*t = static_cast(map->objects[ns->tid]); + BOOST_FOREACH(si32 bid,ns->bid) + t->builtBuildings.insert(bid); + t->builded = ns->builded; + break; + } + case 1001://set object property + { + SetObjectProperty *p = static_cast(pack); + int CGObjectInstance::*point; + switch(p->what) + { + case 1: + point = &CGObjectInstance::tempOwner; + break; + case 2: + point = &CGObjectInstance::blockVisit; + break; + } + map->objects[p->id]->*point = p->val; + break; + } + case 3000: + { + BattleStart * bs = static_cast(pack); + curB = bs->info; + break; + } + case 3001: + { + BattleNextRound *ns = static_cast(pack); + curB->round = ns->round; + break; + } + case 3002: + { + BattleSetActiveStack *ns = static_cast(pack); + curB->activeStack = ns->stack; + break; + } + case 3003: + { + BattleResult *br = static_cast(pack); + + //TODO: give exp, artifacts to winner, decrease armies (casualties) + + for(unsigned i=0;istacks.size();i++) + delete curB->stacks[i]; + delete curB; + curB = NULL; + break; + } + case 3004: + { + BattleStackMoved *br = static_cast(pack); + curB->getStack(br->stack)->position = br->tile; + break; + } + //case 1002://set hover name + // { + // SetHoverName * shn = static_cast(pack); + // map->objects[shn->id]->hoverName = toString(shn->name); + // break; + // } + } + mx->unlock(); +} +int CGameState::pickHero(int owner) +{ + int h=-1; + if(map->getHero(h = scenarioOps->getIthPlayersSettings(owner).hero,0) && h>=0) //we haven't used selected hero + return h; + int f = scenarioOps->getIthPlayersSettings(owner).castle; + int i=0; + do //try to find free hero of our faction + { + i++; + h = scenarioOps->getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(ran()%(HEROES_PER_TYPE*2));//->scenarioOps->playerInfos[pru].hero = VLC-> + } while( map->getHero(h) && i<175); + if(i>174) //probably no free heroes - there's no point in further search, we'll take first free + { + std::cout << "Warning: cannot find free hero - trying to get first available..."<getHero(j)) + h=j; + } + return h; +} +CGHeroInstance *CGameState::getHero(int objid) +{ + if(objid<0 || objid>=map->objects.size()) + return NULL; + return static_cast(map->objects[objid]); +} +std::pair CGameState::pickObject(CGObjectInstance *obj) +{ + switch(obj->ID) + { + case 65: //random artifact + return std::pair(5,(ran()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki + case 66: //random treasure artifact + return std::pair(5,VLC->arth->treasures[ran()%VLC->arth->treasures.size()]->id); + case 67: //random minor artifact + return std::pair(5,VLC->arth->minors[ran()%VLC->arth->minors.size()]->id); + case 68: //random major artifact + return std::pair(5,VLC->arth->majors[ran()%VLC->arth->majors.size()]->id); + case 69: //random relic artifact + return std::pair(5,VLC->arth->relics[ran()%VLC->arth->relics.size()]->id); + case 70: //random hero + { + return std::pair(34,pickHero(obj->tempOwner)); + } + case 71: //random monster + return std::pair(54,ran()%(VLC->creh->creatures.size())); + case 72: //random monster lvl1 + return std::pair(54,VLC->creh->levelCreatures[1][ran()%VLC->creh->levelCreatures[1].size()]->idNumber); + case 73: //random monster lvl2 + return std::pair(54,VLC->creh->levelCreatures[2][ran()%VLC->creh->levelCreatures[2].size()]->idNumber); + case 74: //random monster lvl3 + return std::pair(54,VLC->creh->levelCreatures[3][ran()%VLC->creh->levelCreatures[3].size()]->idNumber); + case 75: //random monster lvl4 + return std::pair(54,VLC->creh->levelCreatures[4][ran()%VLC->creh->levelCreatures[4].size()]->idNumber); + case 76: //random resource + return std::pair(79,ran()%7); //now it's OH3 style, use %8 for mithril + case 77: //random town + { + int align = ((CGTownInstance*)obj)->alignment, + f; + if(align>PLAYER_LIMIT-1)//same as owner / random + { + if(obj->tempOwner > PLAYER_LIMIT-1) + f = -1; //random + else + f = scenarioOps->getIthPlayersSettings(obj->tempOwner).castle; + } + else + { + f = scenarioOps->getIthPlayersSettings(align).castle; + } + if(f<0) f = ran()%VLC->townh->towns.size(); + return std::pair(98,f); + } + case 162: //random monster lvl5 + return std::pair(54,VLC->creh->levelCreatures[5][ran()%VLC->creh->levelCreatures[5].size()]->idNumber); + case 163: //random monster lvl6 + return std::pair(54,VLC->creh->levelCreatures[6][ran()%VLC->creh->levelCreatures[6].size()]->idNumber); + case 164: //random monster lvl7 + return std::pair(54,VLC->creh->levelCreatures[7][ran()%VLC->creh->levelCreatures[7].size()]->idNumber); + case 216: //random dwelling + { + int faction = ran()%F_NUMBER; + CCreGen2ObjInfo* info =(CCreGen2ObjInfo*)obj->info; + if (info->asCastle) + { + for(int i=0;iobjects.size();i++) + { + if(map->objects[i]->ID==77 && dynamic_cast(map->objects[i])->identifier == info->identifier) + { + randomizeObject(map->objects[i]); //we have to randomize the castle first + faction = map->objects[i]->subID; + break; + } + else if(map->objects[i]->ID==98 && dynamic_cast(map->objects[i])->identifier == info->identifier) + { + faction = map->objects[i]->subID; + break; + } + } + } + else + { + while((!(info->castles[0]&(1<7) && (info->castles[1]&(1<<(faction-8)))) + break; + faction = ran()%F_NUMBER; + } + } + int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel)); + int cid = VLC->townh->towns[faction].basicCreatures[level]; + for(int i=0;iobjh->cregens.size();i++) + if(VLC->objh->cregens[i]==cid) + return std::pair(17,i); + std::cout << "Cannot find a dwelling for creature "<(17,0); + } + case 217: + { + int faction = ran()%F_NUMBER; + CCreGenObjInfo* info =(CCreGenObjInfo*)obj->info; + if (info->asCastle) + { + for(int i=0;iobjects.size();i++) + { + if(map->objects[i]->ID==77 && dynamic_cast(map->objects[i])->identifier == info->identifier) + { + randomizeObject(map->objects[i]); //we have to randomize the castle first + faction = map->objects[i]->subID; + break; + } + else if(map->objects[i]->ID==98 && dynamic_cast(map->objects[i])->identifier == info->identifier) + { + faction = map->objects[i]->subID; + break; + } + } + } + else + { + while((!(info->castles[0]&(1<7) && (info->castles[1]&(1<<(faction-8)))) + break; + faction = ran()%F_NUMBER; + } + } + int cid = VLC->townh->towns[faction].basicCreatures[obj->subID]; + for(int i=0;iobjh->cregens.size();i++) + if(VLC->objh->cregens[i]==cid) + return std::pair(17,i); + std::cout << "Cannot find a dwelling for creature "<(17,0); + } + case 218: + { + CCreGen3ObjInfo* info =(CCreGen3ObjInfo*)obj->info; + int level = ((info->maxLevel-info->minLevel) ? (ran()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel)); + int cid = VLC->townh->towns[obj->subID].basicCreatures[level]; + for(int i=0;iobjh->cregens.size();i++) + if(VLC->objh->cregens[i]==cid) + return std::pair(17,i); + std::cout << "Cannot find a dwelling for creature "<(17,0); + } + } + return std::pair(-1,-1); +} +void CGameState::randomizeObject(CGObjectInstance *cur) +{ + std::pair ran = pickObject(cur); + if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything + { + if(cur->ID==98) //town - set def + { + CGTownInstance *t = dynamic_cast(cur); + if(t->hasCapitol()) + t->defInfo = capitols[t->subID]; + else if(t->hasFort()) + t->defInfo = forts[t->subID]; + else + t->defInfo = villages[t->subID]; + } + return; + } + else if(ran.first==34)//special code for hero + { + CGHeroInstance *h = dynamic_cast(cur); + if(!h) {std::cout<<"Wrong random hero at "<pos<ID = ran.first; + h->portrait = cur->subID = ran.second; + h->type = VLC->heroh->heroes[ran.second]; + map->heroes.push_back(h); + return; //TODO: maybe we should do something with definfo? + } + else if(ran.first==98)//special code for town + { + CGTownInstance *t = dynamic_cast(cur); + if(!t) {std::cout<<"Wrong random town at "<pos<ID = ran.first; + cur->subID = ran.second; + t->town = &VLC->townh->towns[ran.second]; + if(t->hasCapitol()) + t->defInfo = capitols[t->subID]; + else if(t->hasFort()) + t->defInfo = forts[t->subID]; + else + t->defInfo = villages[t->subID]; + map->towns.push_back(t); + return; + } + //we have to replace normal random object + cur->ID = ran.first; + cur->subID = ran.second; + map->defs.insert(cur->defInfo = VLC->dobjinfo->gobjs[ran.first][ran.second]); + if(!cur->defInfo) + { + std::cout<<"Missing def declaration for "<ID<<" "<subID<map = map; + + for(int i=0;idobjinfo->castles[i]); + forts[i] = VLC->dobjinfo->castles[i]; + capitols[i] = new CGDefInfo(*VLC->dobjinfo->castles[i]); + } + + //picking random factions for players + for(int i=0;iplayerInfos.size();i++) + { + if(scenarioOps->playerInfos[i].castle==-1) + { + int f; + do + { + f = ran()%F_NUMBER; + }while(!(map->players[scenarioOps->playerInfos[i].color].allowedFactions & 1<playerInfos[i].castle = f; + } + } + //randomizing objects + for(int no=0; noobjects.size(); ++no) + { + randomizeObject(map->objects[no]); + if(map->objects[no]->ID==26) + map->objects[no]->defInfo->handler=NULL; + map->objects[no]->hoverName = VLC->objh->names[map->objects[no]->ID]; + } + //std::cout<<"\tRandomizing objects: "<players[i].generateHeroAtMainTown && map->players[i].hasMainTown) || (map->players[i].hasMainTown && map->version==RoE)) + { + int3 hpos = map->players[i].posOfMainTown; + hpos.x+=1;// hpos.y+=1; + int j; + for(j=0; jplayerInfos.size(); j++) + if(scenarioOps->playerInfos[j].color == i) + break; + if(j == scenarioOps->playerInfos.size()) + continue; + int h=pickHero(i); + CGHeroInstance * nnn = static_cast(createObject(34,h,hpos,i)); + nnn->id = map->objects.size(); + //nnn->defInfo->handler = graphics->flags1[0]; + map->heroes.push_back(nnn); + map->objects.push_back(nnn); + } + } + //std::cout<<"\tGiving starting heroes: "<playerInfos.size();i++) + { + std::pair ins(scenarioOps->playerInfos[i].color,PlayerState()); + ins.second.color=ins.first; + ins.second.serial=i; + players.insert(ins); + } + /******************RESOURCES****************************************************/ + //TODO: zeby komputer dostawal inaczej niz gracz + std::vector startres; + std::ifstream tis("config/startres.txt"); + int k; + for (int j=0;jdifficulty;j++) + { + tis >> k; + for (int z=0;z>k; + } + tis >> k; + for (int i=0;i> k; + startres.push_back(k); + } + tis.close(); + for (std::map::iterator i = players.begin(); i!=players.end(); i++) + { + (*i).second.resources.resize(RESOURCE_QUANTITY); + for (int x=0;xheroes.size();i++) //heroes instances + { + if (map->heroes[i]->getOwner()<0) + continue; + CGHeroInstance * vhi = (map->heroes[i]); + if(!vhi->type) + vhi->type = VLC->heroh->heroes[vhi->subID]; + //vhi->subID = vhi->type->ID; + if (vhi->level<1) + { + vhi->exp=40+ran()%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()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 = (VLC->creh->nameToID[vhi->type->refTypeStack[x]]); + if(pom>=145 && pom<=149) //war machine + { + pom2++; + switch (pom) + { + case 145: //catapult + vhi->artifWorn[16] = 3; + break; + default: + pom-=145; + vhi->artifWorn[13+pom] = 4+pom; + break; + } + continue; + } + vhi->army.slots[x-pom2].first = pom; + if((pom = (vhi->type->highStack[x]-vhi->type->lowStack[x])) > 0) + vhi->army.slots[x-pom2].second = (ran()%pom)+vhi->type->lowStack[x]; + else + vhi->army.slots[x-pom2].second = +vhi->type->lowStack[x]; + } + } + + players[vhi->getOwner()].heroes.push_back(vhi); + + } + /*************************FOG**OF**WAR******************************************/ + for(std::map::iterator k=players.begin(); k!=players.end(); ++k) + { + k->second.fogOfWarMap.resize(map->width); + for(int g=0; gwidth; ++g) + k->second.fogOfWarMap[g].resize(map->height); + + for(int g=-0; gwidth; ++g) + for(int h=0; hheight; ++h) + k->second.fogOfWarMap[g][h].resize(map->twoLevel+1, 0); + + for(int g=0; gwidth; ++g) + for(int h=0; hheight; ++h) + for(int v=0; vtwoLevel+1; ++v) + k->second.fogOfWarMap[g][h][v] = 0; + for(int xd=0; xdwidth; ++xd) //revealing part of map around heroes + { + for(int yd=0; ydheight; ++yd) + { + for(int ch=0; chsecond.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+deltaYsecond.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;itowns.size();i++) + { + CGTownInstance * vti =(map->towns[i]); + if(!vti->town) + vti->town = &VLC->townh->towns[vti->subID]; + if (vti->name.length()==0) // if town hasn't name we draw it + vti->name=vti->town->names[ran()%vti->town->names.size()]; + if(vti->builtBuildings.find(-50)!=vti->builtBuildings.end()) //give standard set of buildings + { + vti->builtBuildings.erase(-50); + vti->builtBuildings.insert(10); + vti->builtBuildings.insert(5); + vti->builtBuildings.insert(30); + if(ran()%2) + vti->builtBuildings.insert(31); + } + players[vti->getOwner()].towns.push_back(vti); + } + + for(std::map::iterator k=players.begin(); k!=players.end(); ++k) + { + if(k->first==-1 || k->first==255) + continue; + for(int xd=0; xdwidth; ++xd) //revealing part of map around towns + { + for(int yd=0; ydheight; ++yd) + { + for(int ch=0; chsecond.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+deltaYsecond.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; lsecond.heroes.size();l++) + { + for(int m=0; msecond.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; + } + } + } } - if(attackedCreaure == -1) - return false; - //LOCPLINT->cb-> - return true; } bool CGameState::battleShootCreatureStack(int ID, int dest) -{ +{/* CStack * curStack = NULL; for(int y=0; ystacks.size(); ++y) { @@ -534,7 +982,7 @@ bool CGameState::battleShootCreatureStack(int ID, int dest) LOCPLINT->battleStackIsAttacked(curB->stacks[numberOfStackAtEnd]->ID, finalDmg, std::min(cresKilled, cresInstackBefore), ID, true); } - //damage applied + //damage applied*/ return true; } @@ -595,131 +1043,7 @@ int CGameState::calculateDmg(const CStack* attacker, const CStack* defender) } std::vector CGameState::battleGetRange(int ID) -{ - int initialPlace=-1; //position of unit - int radius=-1; //range of unit - unsigned char owner = -1; //owner of unit - //selecting stack - CStack * curStack = NULL; - for(int y=0; ystacks.size(); ++y) - { - if(curB->stacks[y]->ID == ID) - { - curStack = curB->stacks[y]; - break; - } - } - - for(int g=0; gstacks.size(); ++g) - { - if(curB->stacks[g]->ID == ID) - { - initialPlace = curB->stacks[g]->position; - radius = curB->stacks[g]->creature->speed; - owner = curB->stacks[g]->owner; - break; - } - } - - bool accessibility[187]; //accesibility of hexes - for(int k=0; k<187; k++) - accessibility[k] = true; - for(int g=0; gstacks.size(); ++g) - { - if(curB->stacks[g]->ID != ID && curB->stacks[g]->alive) //we don't want to lock current unit's position - { - accessibility[curB->stacks[g]->position] = false; - if(curB->stacks[g]->creature->isDoubleWide()) //if it's a double hex creature - { - if(curB->stacks[g]->attackerOwned) - accessibility[curB->stacks[g]->position-1] = false; - else - accessibility[curB->stacks[g]->position+1] = false; - } - } - } - - if(curStack->creature->isDoubleWide()) //locking positions unreachable by two-hex creatures - { - bool mac[187]; - for(int b=0; b<187; ++b) - { - // - // && ( ? (curStack->attackerOwned ? accessibility[curNext-1] : accessibility[curNext+1]) : true ) - mac[b] = accessibility[b]; - if( accessibility[b] && !(curStack->attackerOwned ? accessibility[b-1] : accessibility[b+1])) - { - mac[b] = false; - } - } - mac[curStack->attackerOwned ? curStack->position+1 : curStack->position-1]=true; - for(int v=0; v<187; ++v) - accessibility[v] = mac[v]; - //removing accessibility for side hexes - for(int v=0; v<187; ++v) - if(curStack->attackerOwned ? (v%17)==1 : (v%17)==15) - accessibility[v] = false; - } - - int dists[187]; //calculated distances - std::queue hexq; //bfs queue - hexq.push(initialPlace); - for(int g=0; g<187; ++g) - dists[g] = 100000000; - dists[initialPlace] = 0; - int curNext = -1; //for bfs loop only (helper var) - while(!hexq.empty()) //bfs loop - { - int curHex = hexq.front(); - hexq.pop(); - curNext = curHex - ( (curHex/17)%2 ? 18 : 17 ); - if((curNext > 0) && accessibility[curNext] && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //top left - { - hexq.push(curNext); - dists[curNext] = dists[curHex] + 1; - } - curNext = curHex - ( (curHex/17)%2 ? 17 : 16 ); - if((curNext > 0) && accessibility[curNext] && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //top right - { - hexq.push(curNext); - dists[curNext] = dists[curHex] + 1; - } - curNext = curHex - 1; - if((curNext > 0) && accessibility[curNext] && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //left - { - hexq.push(curNext); - dists[curNext] = dists[curHex] + 1; - } - curNext = curHex + 1; - if((curNext < 187) && accessibility[curNext] && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //right - { - hexq.push(curNext); - dists[curNext] = dists[curHex] + 1; - } - curNext = curHex + ( (curHex/17)%2 ? 16 : 17 ); - if((curNext < 187) && accessibility[curNext] && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //bottom left - { - hexq.push(curNext); - dists[curNext] = dists[curHex] + 1; - } - curNext = curHex + ( (curHex/17)%2 ? 17 : 18 ); - if((curNext < 187) && accessibility[curNext] && (dists[curHex] + 1 < dists[curNext]) && (curNext)%17!=0 && (curNext)%17!=16) //bottom right - { - hexq.push(curNext); - dists[curNext] = dists[curHex] + 1; - } - } - - std::vector ret; - - for(int i=0; i<187; ++i) - { - if(dists[i]<=radius) - { - ret.push_back(i); - } - } - +{/* std::vector additionals; //adding enemies' positions @@ -759,6 +1083,7 @@ std::vector CGameState::battleGetRange(int ID) ret2.push_back(*it); } - return ret2; + return ret2;*/ + return std::vector(); } diff --git a/CGameState.h b/CGameState.h index a8a0b4fdb..8c22cc605 100644 --- a/CGameState.h +++ b/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 +#include #ifdef _WIN32 #include #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; -struct PlayerState +namespace boost +{ + class shared_mutex; +} + +struct DLL_EXPORT PlayerState { public: - int color, serial; - //std::vector > > fogOfWarMap; //true - visible, false - hidden - PseudoV< PseudoV< PseudoV > > fogOfWarMap; //true - visible, false - hidden - std::vector resources; + ui8 color, serial; + std::vector > > fogOfWarMap; //true - visible, false - hidden + std::vector resources; std::vector heroes; std::vector 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 stacks; - bool stackActionPerformed; //true if current stack has been moved + + template 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 getPath(int start, int dest, bool*accessibility); + std::vector 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 void save(Handler &h, const int version) + { + h & creature->idNumber; + } + template void load(Handler &h, const int version) + { + ui32 id; + h & id; + creature = &VLC->creh->creatures[id]; + } + template 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 players; //color <-> playerstate - std::set cppscripts; - std::map > objscr; //custom user scripts (as for now only Lua) + ui32 day; //total number of days in game + Mapa * map; + std::map players; //ID <-> playerstate + std::map 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 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::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 battleGetRange(int ID); //called by std::vector 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 * 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 > > & 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 diff --git a/CHeroWindow.cpp b/CHeroWindow.cpp index 3cfda076b..63abf480e 100644 --- a/CHeroWindow.cpp +++ b/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 - +#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(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(sartifacts.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 && sartifacts.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 && sartifacts.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<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; gcb->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; fheroh->smallPortraits[cur->portrait]->w; ++f) + for(int f=0; fportraitSmall[cur->portrait]->w; ++f) { - for(int h=0; hheroh->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; hportraitSmall[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()); - #else - #warning error here! - #endif - } + //if(!down) + //{ + // LOCPLINT->showInfoDialog("TEST TEST AAA", std::vector()); + //} + + + + } 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()); - #else - #warning error here! - #endif - } + //if(!down) + //{ + // LOCPLINT->showInfoDialog("TEST TEST AAA", std::vector()); + //} + + + + } void LRClickableAreaWText::clickLeft(boost::logic::tribool down) diff --git a/CHeroWindow.h b/CHeroWindow.h index a2e015863..b0566a79f 100644 --- a/CHeroWindow.h +++ b/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 diff --git a/CLua.cpp b/CLua.cpp index cf8598a25..8e7b9b93f 100644 --- a/CLua.cpp +++ b/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 -#include "hch/CObjectHandler.h" -#include "hch/CTownHandler.h" -#include "CCallback.h" -#include "hch/CGeneralTextHandler.h" -#include -#include "CPlayerInterface.h" #include #include +#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 "<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); -#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)) - { - lua_settop(is, 0); -#ifndef __GNUC__ - throw new std::exception(("Failed to call "+genFN("hoverText",os->ID)+" function in lua script.").c_str()); -#else - throw std::exception(); -#endif - } - std::string ret = lua_tostring(is,1); - lua_settop(is, 0); - return ret; + //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 ""; +//} -std::string CCPPObjectScript::hoverText(CGObjectInstance *os) -{ - return CGI->objh->objects[os->defInfo->id].name; -} - -void CVisitableOPH::newObject(CGObjectInstance *os) +void CVisitableOPH::newObject(int objid) { visitors.insert - (std::pair >(os,std::set())); + (std::pair >(objid,std::set())); + + DEFOS; + MetaString hovername; + 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 new std::exception(); +#endif + } + hovername << std::pair(3,os->ID) << " " << std::pair(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 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(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 weko; - weko.push_back(new SComponent(SComponent::experience,0,vvv)); - cb->showInfoDialog(cb->getHeroOwner(heroID),CGI->objh->advobtxt[ot],&weko); - //for (int ii=0; iigetHeroOwner(heroID); + iw.text << std::pair(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()); + InfoWindow iw; + iw.player = cb->getHeroOwner(heroID); + iw.text << std::pair(11,ot); + cb->showInfoDialog(&iw); } } @@ -310,49 +320,9 @@ std::vector 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()); //TODO: maybe we have memory leak with these windows + + InfoWindow iw; + iw.player = cb->getHero(heroID)->tempOwner; + iw.text << std::pair(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 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(11,mid); + cb->showInfoDialog(&iw); + visited[objid] = true; + MetaString ms; //set text to "visited" + ms << std::pair(3,os->ID) << " " << std::pair(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::iterator i = visited.begin(); i != visited.end(); i++) + for (std::map::iterator i = visited.begin(); i != visited.end(); i++) { (*i).second = false; + MetaString ms; //set text to "not visited" + ms << std::pair(3,cb->getObj(i->first)->ID) << " " << std::pair(1,353); + cb->setHoverName(i->first,&ms); } + } -} -void CVisitableOPW::newObject(CGObjectInstance *os) +} +void CVisitableOPW::newObject(int objid) { - visited.insert(std::pair(os,false)); + visited.insert(std::pair(objid,false)); + DEFOS; + MetaString ms; + ms << std::pair(3,os->ID) << " " << std::pair(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 CVisitableOPW::yourObjects() //returns IDs of objects which are handled by script @@ -445,75 +432,88 @@ std::vector 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(3,os->ID); + cb->setHoverName(objid,&ms); } +void CMines::onHeroVisit(int objid, int heroID) +{ + //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(9,os->subID) << " " << std::pair(6,23+h->tempOwner); + cb->setHoverName(objid,&ms); + ms.clear(); -void CMines::newObject(CGObjectInstance *os) -{ - ourObjs.push_back(os); - os->tempOwner = NEUTRAL_PLAYER; -} -void CMines::onHeroVisit(CGObjectInstance *os, int heroID) -{ - int vv = 1; + 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 weko; - weko.push_back(com); - cb->showInfoDialog(cb->getHeroOwner(heroID),CGI->objh->mines[os->subID].second,&weko); - } + + InfoWindow iw; + iw.text << std::pair(10,os->subID); + iw.player = h->tempOwner; + iw.components.push_back(Component(2,os->subID,vv,-1)); + cb->showInfoDialog(&iw); } std::vector CMines::yourObjects() { - std::vector ret(1); + std::vector 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;itempOwner == 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(4,os->subID); + break; + case 5: + ms << std::pair(5,os->subID); + break; + default: + ms << std::pair(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 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(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;iID) - { - 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 CPickable::yourObjects() //returns IDs of objects which are handled by script @@ -641,20 +630,22 @@ std::vector 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(os)) - return n->name + ", " + n->town->name; - else return ""; + cb->stopHeroVisitCastle(objid,heroID); } std::vector CTownScript::yourObjects() //returns IDs of objects which are handled by script @@ -664,27 +655,33 @@ std::vector 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(os->subID,os)); + cb->setBlockVis(objid,true); + MetaString ms; + ms << std::pair(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(heroes[heroID])->tempOwner == static_cast(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(heroes[heroID]))->army, - &(static_cast(os))->army, - os->pos, - static_cast(heroes[heroID]), - static_cast(os)); + &my->army, + &vis->army, + my->pos, + my, + vis); } } std::vector CHeroScript::yourObjects() //returns IDs of objects which are handled by script @@ -693,65 +690,58 @@ std::vector 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(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(6,pom) << " " << std::pair(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(&CGI->creh->creatures[os->subID],((CCreatureObjInfo*)os->info)->number); - cb->startBattle(heroID,&set,os->pos); + set.slots[0] = std::pair(os->subID,amounts[objid]); + cb->startBattle(heroID,set,os->pos); } std::vector CMonsterS::yourObjects() //returns IDs of objects which are handled by script { @@ -761,15 +751,15 @@ std::vector CMonsterS::yourObjects() //returns IDs of objects which are han } -void CCreatureGen::newObject(CGObjectInstance *os) +void CCreatureGen::newObject(int objid) { - amount[os] = CGI->creh->creatures[CGI->objh->cregens[os->subID]].growth; + DEFOS; + amount[objid] = VLC->creh->creatures[VLC->objh->cregens[os->subID]].growth; + MetaString ms; + ms << std::pair(8,os->subID); + cb->setHoverName(objid,&ms); } -std::string CCreatureGen::hoverText(CGObjectInstance *os) -{ - return CGI->objh->creGens[os->subID]; -} -void CCreatureGen::onHeroVisit(CGObjectInstance *os, int heroID) +void CCreatureGen::onHeroVisit(int objid, int heroID) { } std::vector CCreatureGen::yourObjects() //returns IDs of objects which are handled by script diff --git a/CLua.h b/CLua.h index 4a93bdcf1..707ed0ba4 100644 --- a/CLua.h +++ b/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 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 > visitors; + std::map > 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 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 visited; - void onNAHeroVisit(CGObjectInstance *os, int heroID, bool alreadyVisited); - void newObject(CGObjectInstance *os); - void onHeroVisit(CGObjectInstance *os, int heroID); + std::map visited; + void onNAHeroVisit(int objid, int heroID, bool alreadyVisited); + void newObject(int objid); + void onHeroVisit(int objid, int heroID); std::vector 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 ourObjs; + std::vector ourObjs; - void newObject(CGObjectInstance *os); - void onHeroVisit(CGObjectInstance *os, int heroID); + void newObject(int objid); + void onHeroVisit(int objid, int heroID); std::vector 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 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 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 yourObjects(); //returns IDs of objects which are handled by script - - friend void initGameState(CGameInfo * cgi); }; class CHeroScript : public CCPPObjectScript { - std::map 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 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 heroes; +public: + std::map 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 yourObjects(); //returns IDs of objects which are handled by script - - friend void initGameState(CGameInfo * cgi); }; class CCreatureGen : public CCPPObjectScript { - std::map amount; //amount of creatures in each dwelling +public: + std::map 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 yourObjects(); //returns IDs of objects which are handled by script - - friend void initGameState(CGameInfo * cgi); }; diff --git a/CLuaHandler.cpp b/CLuaHandler.cpp index 23881cd10..68eabcf80 100644 --- a/CLuaHandler.cpp +++ b/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") - // //.def(luabind::constructor<>()) - // //.def(luabind::constructor()) - // .def_readwrite("x", &int3::x) - // .def_readwrite("y", &int3::y) - // .def_readwrite("z", &int3::z) - //]; - //luabind::module(lua) - //[ - // luabind::def("powitanie",&piszpowitanie2) - //]; + //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); + + + + + + + + + + + + + + + + + + + + - 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(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); } @@ -82,10 +82,10 @@ std::vector * 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; diff --git a/CMT.cpp b/CMT.cpp index a3c7a90df..61326f606 100644 --- a/CMT.cpp +++ b/CMT.cpp @@ -1,45 +1,22 @@ // CMT.cpp : Defines the entry point for the console application. // #include "stdafx.h" -#include "SDL.h" +#include +#include +#include +#include +#include +#include #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 -#include -#include -#include -#include -#include -#include "zlib.h" -#include -#include -#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 "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 -#include -#if defined(MSDOS) || defined(OS2) || defined(WIN32) || defined(__CYGWIN__) -# include -# include -# 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 events; +boost::mutex eventsM; TTF_Font * TNRB16, *TNR, *GEOR13, *GEORXX, *GEORM, *GEOR16; -void handleCPPObjS(std::map * mapa, CCPPObjectScript * script) -{ - std::vector tempv = script->yourObjects(); - for (int i=0;istate->cppscripts.insert(script); -} -void initGameState(CGameInfo * cgi) -{ - cgi->state->day=0; - /*********creating players entries in gs****************************************/ - for (int i=0; iscenarioOps.playerInfos.size();i++) - { - std::pair 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 startres; - std::ifstream tis("config/startres.txt"); - int k; - for (int j=0;jscenarioOps.difficulty;j++) - { - tis >> k; - for (int z=0;z>k; - } - tis >> k; - for (int i=0;i> k; - startres.push_back(k); - } - tis.close(); - for (std::map::iterator i = cgi->state->players.begin(); i!=cgi->state->players.end(); i++) - { - (*i).second.resources.resize(RESOURCE_QUANTITY); - for (int x=0;xheroh->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()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::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; gac->map.width+Woff; ++g) - k->second.fogOfWarMap[g].resize(cgi->ac->map.height, Hoff); - - for(int g=-Woff; gac->map.width+Woff; ++g) - for(int h=-Hoff; hac->map.height+Hoff; ++h) - k->second.fogOfWarMap[g][h].resize(cgi->ac->map.twoLevel+1, 0); - - for(int g=-Woff; gac->map.width+Woff; ++g) - for(int h=-Hoff; hac->map.height+Hoff; ++h) - for(int v=0; vac->map.twoLevel+1; ++v) - k->second.fogOfWarMap[g][h][v] = 0; - for(int xd=0; xdac->map.width; ++xd) //revealing part of map around heroes - { - for(int yd=0; ydac->map.height; ++yd) - { - for(int ch=0; chsecond.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+deltaYsecond.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;itownh->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::iterator k=cgi->state->players.begin(); k!=cgi->state->players.end(); ++k) - { - if(k->first==-1 || k->first==255) - continue; - for(int xd=0; xdac->map.width; ++xd) //revealing part of map around towns - { - for(int yd=0; ydac->map.height; ++yd) - { - for(int ch=0; chsecond.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+deltaYsecond.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; lsecond.heroes.size();l++) - { - for(int m=0; msecond.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 > * skrypty = &cgi->state->objscr; //alias for easier access - /****************************C++ OBJECT SCRIPTS************************************************/ - std::map 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 * lf = CLuaHandler::searchForScripts("scripts/lua/objects"); //files - for (int i=0; isize(); i++) - { - try - { - std::vector * temp = CLuaHandler::functionList((*lf)[i]); - CLuaObjectScript * objs = new CLuaObjectScript((*lf)[i]); - CLuaCallback::registerFuncs(objs->is); - //objs - for (int j=0; jsize(); 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 >(obid,std::map())); - (*skrypty)[obid].insert(std::pair(fname,objs)); - } - delete temp; - }HANDLE_EXCEPTION - } - /****************************INITIALIZING OBJECT SCRIPTS************************************************/ - std::string temps("newObject"); - for (int i=0; iobjh->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 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: "<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: "<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: "<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!"<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: "<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: "<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: "<townh = new CTownHandler; - cgi->townh->loadNames(); + //cgi->screenh = new CScreenHandler; + //cgi->screenh->initScreen(); + THC std::cout<<"\tScreen handler: "<loadAbilities(); cgi->abilh = abilh; - CHeroHandler * heroh = new CHeroHandler; - heroh->loadHeroes(); - heroh->loadPortraits(); - cgi->heroh = heroh; + THC std::cout<<"\tAbility handler: "< animacje; + for(std::vector::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: "<generaltexth = new CGeneralTextHandler; cgi->generaltexth->load(); THC std::cout<<"Preparing more handlers: "<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; oheroh->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; ffheroh->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; oheroh->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; ffheroh->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; oheroh->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; ffheroh->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; oheroh->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; oheroh->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; ffheroh->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: "<mush = mush; - cgi->scenarioOps = cpg->runLoop(); - THC tmh.getDif(); - - CArtHandler * arth = new CArtHandler; - arth->loadArtifacts(); - cgi->arth = arth; - THC std::cout<<"\tArtifact handler: "<loadCreatures(); - cgi->creh = creh; - THC std::cout<<"\tCreature handler: "<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: "<loadBuildings(); - cgi->buildh = buildh; - THC std::cout<<"\tBuilding handler: "<loadObjects(); - cgi->objh = objh; - THC std::cout<<"\tObject handler: "<dobjinfo = new CDefObjInfoHandler; - cgi->dobjinfo->load(); - THC std::cout<<"\tDef information handler: "<state = new CGameState(); - cgi->state->players = std::map(); - THC std::cout<<"\tGamestate: "<pathf = new CPathfinder(); THC std::cout<<"\tPathfinder: "<consoleh->cb = new CCallback(cgi->state,-1); cgi->consoleh->runConsole(); THC std::cout<<"\tCallback and console: "<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): "< 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; ssac = ac; - THC std::cout<<"Reading file: "<deh3m(); - THC std::cout<<"Detecting file (together): "<loadDefs(); - THC std::cout<<"Reading terrain defs: "<mh = mh; - mh->reader = ac; - THC std::cout<<"Creating mapHandler: "<init(); - THC std::cout<<"Initializing mapHandler (together): "<playerint.push_back(NULL); - }*/ - for (int i=0; iscenarioOps.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(CAIHandler::getNewAI(new CCallback(cgi->state,cgi->scenarioOps.playerInfos[i].color),"EmptyAI.dll"))); -#else - cgi->playerint.push_back(static_cast(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; gplayerint.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; dmh->reader->map.twoLevel+1; ++d) - { - SDL_Surface * pt = CSDL_Ext::newSurface(mm.pos.w, mm.pos.h, CSDL_Ext::std32bppSurface); - - for (int i=0; imh->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;iplayerint.size();i++) - { - cgi->state->currentPlayer=cgi->playerint[i]->playerID; - try - { - cgi->playerint[i]->yourTurn(); - }HANDLE_EXCEPTION - } - } + //for(int g=0; gplayerint.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; dmh->map->twoLevel+1; ++d) + // { + // SDL_Surface * pt = CSDL_Ext::newSurface(mm.pos.w, mm.pos.h, CSDL_Ext::std32bppSurface); + // for (int i=0; imh->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 { diff --git a/CMessage.cpp b/CMessage.cpp index 544a21883..9ae2c6b75 100644 --- a/CMessage.cpp +++ b/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 #include "CPlayerInterface.h" #include "hch/CDefHandler.h" -#include "hch/CSemiDefHandler.h" #include "CGameInfo.h" #include "SDL_Extensions.h" #include #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;ispriteh->giveDef("DIALGBOX.DEF"); + CDefHandler * bluePieces = CDefHandler::giveDef("DIALGBOX.DEF"); std::vector n; piecesOfBox.push_back(n); if (i==1) @@ -63,15 +62,15 @@ void CMessage::init() } for (int j=0;jourImages.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"); } diff --git a/CPathfinder.cpp b/CPathfinder.cpp index 802611bab..d3b36d04a 100644 --- a/CPathfinder.cpp +++ b/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* 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; } diff --git a/CPlayerInterface.cpp b/CPlayerInterface.cpp index 5e760a420..f77d3302a 100644 --- a/CPlayerInterface.cpp +++ b/CPlayerInterface.cpp @@ -1,17 +1,18 @@ #include "stdafx.h" +#include #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 +#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 #include #include #include "hch/CPreGameTextHandler.h" +#include "hch/CObjectHandler.h" #include "CBattleInterface.h" +#include "CGameInfo.h" #include "CLua.h" #include +#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 events; +extern boost::mutex eventsM; + class OCM_HLP_CGIN { public: - bool operator ()(const std::pair & a, const std::pair & b) const + bool operator ()(const std::pair & a, const std::pair & 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(7,(CGarrisonSlot *)(NULL)); for - (std::map >::const_iterator i=set1->slots.begin(); + (std::map >::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; isize(); i++) if((*sup)[i] == NULL) @@ -343,11 +356,11 @@ void CGarrisonInt::createSlots() { sdown = new std::vector(7,(CGarrisonSlot *)(NULL)); for - (std::map >::const_iterator i=set2->slots.begin(); + (std::map >::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; isize(); 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(44,82)); - slotsPos.push_back(std::pair(80,82)); - slotsPos.push_back(std::pair(116,82)); - slotsPos.push_back(std::pair(26,131)); - slotsPos.push_back(std::pair(62,131)); - slotsPos.push_back(std::pair(98,131)); - slotsPos.push_back(std::pair(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(CB); - CGI->localPlayer = serialID; adventureInt = new CAdvMapInt(playerID); castleInt = NULL; std::vector hh = cb->getHeroesInfo(false); for(int i=0;i(hh[i]->subID,pom)); + graphics->heroWins.insert(std::pair(hh[i]->subID,pom)); } std::vector tt = cb->getTownsInfo(false); for(int i=0;i(tt[i]->identifier,pom)); + graphics->townWins.insert(std::pair(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;itick(); } 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.xac->map.width-19+4) + if(LOCPLINT->adventureInt->position.xmh->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.yac->map.height-18+4) + if(LOCPLINT->adventureInt->position.ymh->map->height-18+4) { LOCPLINT->adventureInt->position.y++; LOCPLINT->adventureInt->updateScreen = true; @@ -1059,12 +1076,14 @@ void CPlayerInterface::yourTurn() } for(int i=0;ishow(); - //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 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 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(hero->subID,infoWin(hero))); + if(graphics->heroWins.find(hero->subID)==graphics->heroWins.end()) + graphics->heroWins.insert(std::pair(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;iprimSkills[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 >::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 >::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; -} - 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(specific)); + return graphics->drawHeroInfoWin(dynamic_cast(specific)); break; case 98: - return drawTownInfoWin(dynamic_cast(specific)); + return graphics->drawTownInfoWin(dynamic_cast(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; ipos,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 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 un(*pim); if(obj->ID == 34) //hero { const CGHeroInstance * hh; if(hh = dynamic_cast(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(curint); if(hw) @@ -1968,8 +1921,8 @@ void CPlayerInterface::garrisonChanged(const CGObjectInstance * obj) const CGTownInstance * tt; if(tt = dynamic_cast(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(curint); @@ -1986,6 +1939,7 @@ void CPlayerInterface::buildChanged(const CGTownInstance *town, int buildingID, return; if(castleInt->town!=town) return; + boost::unique_lock 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 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(curint)->stackActivated(stackID); - while(!dynamic_cast(curint)->givenCommand) //while current unit can perform an action + CBattleInterface *b = dynamic_cast(curint); { - ++showCount; - SDL_Event sEvent; - while (SDL_PollEvent(&sEvent)) //wait for event... - { - LOCPLINT->handleEvent(&sEvent); - } - if(showCount%2==0) - for(int i=0;ishow(); - //SDL_Flip(screen); - CSDL_Ext::update(screen); - - /*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(); - }*/ - - SDL_Delay(1); //give time for other apps - SDL_framerateDelay(mainFPSmng); + boost::unique_lock un(*pim); + b->stackActivated(stackID); } - BattleAction ret = *(dynamic_cast(curint)->givenCommand); - delete dynamic_cast(curint)->givenCommand; - dynamic_cast(curint)->givenCommand = NULL; - dynamic_cast(curint)->myTurn = false; + //wait till BattleInterface sets its command + boost::unique_lock lock(b->givenCommand->mx); + while(!b->givenCommand->data) + b->givenCommand->cond.wait(lock); + + //tidy up + BattleAction ret = *(b->givenCommand->data); + delete b->givenCommand->data; + b->givenCommand->data = NULL; + + //return command return ret; } -void CPlayerInterface::battleEnd(CCreatureSet * army1, CCreatureSet * army2, CArmedInstance *hero1, CArmedInstance *hero2, std::vector capturedArtifacts, int expForWinner, bool winner) +void CPlayerInterface::battleEnd(BattleResult *br) { + boost::unique_lock un(*pim); dynamic_cast(curint)->deactivate(); LOCPLINT->objsToBlit.erase(std::find(LOCPLINT->objsToBlit.begin(),LOCPLINT->objsToBlit.end(),dynamic_cast(curint))); delete dynamic_cast(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 un(*pim); dynamic_cast(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 un(*pim); adventureInt->infoBar.showComp(&comp,4000); } +void CPlayerInterface::showInfoDialog(std::string text, std::vector &components) +{ + curint->deactivate(); //dezaktywacja starego interfejsu + std::vector intComps; + for(int i=0;iplayerID,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;icomponents.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 & 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(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;itownh->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 > &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 > &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) diff --git a/CPlayerInterface.h b/CPlayerInterface.h index 1fd2834fd..1da22d45b 100644 --- a/CPlayerInterface.h +++ b/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 okb; std::vector 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 lclickable; std::vector rclickable; std::vector hoverable; @@ -309,15 +318,7 @@ public: std::vector timeinterested; std::vector objsToBlit; - SDL_Surface * hInfo, *tInfo; - std::vector > slotsPos; - CDefEssential *luck22, *luck30, *luck42, *luck82, - *morale22, *morale30, *morale42, *morale82, - *halls, *forts, *bigTownPic; - std::map heroWins; - std::map 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 &components); void showSelDialog(std::string text, std::vector & 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 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 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 & 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 diff --git a/CPreGame.cpp b/CPreGame.cpp index c38f4c07d..312ca4b0c 100644 --- a/CPreGame.cpp +++ b/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 - +#include "client/Graphics.h" +#include +#include 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(),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(),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(),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(),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->castlecastle>=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")); + 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(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")); + 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,73 +979,50 @@ void MapSel::show() //SDL_Flip(screen); CSDL_Ext::update(screen); } +boost::mutex mx; +void MapSel::processMaps(std::vector &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: "<bitmaph->loadBitmap("SCSELBCK.bmp"); - SDL_SetColorKey(bg,SDL_SRCCOLORKEY,SDL_MapRGB(bg->format,0,255,255)); - small.imgs = CGI->spriteh->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.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.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.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.fun = NULL; - all.pos = genRect(all.imgs->ourImages[0].bitmap->h,all.imgs->ourImages[0].bitmap->w,349,52); - all.ourGroup=NULL; - all.selectable=xlarge.selectable=large.selectable=medium.selectable=small.selectable=false; - 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.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.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.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.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.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.fun = NULL; - loscon.pos = genRect(loscon.imgs->ourImages[0].bitmap->h,loscon.imgs->ourImages[0].bitmap->w,342,92); - loscon.key=_loscon; - - 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"); - //Dsizes = CPG->slh->giveDef("SCNRMPSZ.DEF"); - Dsizes = CGI->spriteh->giveDef("SCNRMPSZ.DEF"); - sFlags = CGI->spriteh->giveDef("ITGFLAGS.DEF"); //get map files names std::vector pliczkiTemp; fs::path tie( (fs::initial_path())/"/maps" ); @@ -1049,31 +1035,79 @@ void MapSel::init() pliczkiTemp.push_back("Maps/"+(dir->path().leaf())); } } - for (int i=0; i4000) 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: "<format,0,255,255)); + 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 = 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 = 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 = 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 = 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; + all.selectable=xlarge.selectable=large.selectable=medium.selectable=small.selectable=false; + 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 = 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 = 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 = 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 = 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 = 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 = 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; + + 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 = CDefHandler::giveDef("SCSELC.DEF"); + Dvic = CDefHandler::giveDef("SCNRVICT.DEF"); + Dloss = CDefHandler::giveDef("SCNRLOSS.DEF"); + //Dsizes = CPG->slh->giveDef("SCNRMPSZ.DEF"); + 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; ibScens.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; ibRandom.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; ibOptions.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; } diff --git a/CPreGame.h b/CPreGame.h index d7e34d3d4..cabd9fc20 100644 --- a/CPreGame.h +++ b/CPreGame.h @@ -4,16 +4,15 @@ #include #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 #include 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 &pliczkiTemp, int &index); MapSel(); ~MapSel(); }; diff --git a/CScreenHandler.cpp b/CScreenHandler.cpp deleted file mode 100644 index 547db1377..000000000 --- a/CScreenHandler.cpp +++ /dev/null @@ -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);*/ -} diff --git a/CScreenHandler.h b/CScreenHandler.h deleted file mode 100644 index 74d6126c7..000000000 --- a/CScreenHandler.h +++ /dev/null @@ -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 diff --git a/ChangeLog b/ChangeLog index 8b1378917..e69de29bb 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1 +0,0 @@ - diff --git a/DefSorter.exe b/DefSorter.exe deleted file mode 100644 index 8da32bc65..000000000 Binary files a/DefSorter.exe and /dev/null differ diff --git a/Makefile.am b/Makefile.am index bbf8ae698..6d07a0bed 100644 --- a/Makefile.am +++ b/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 +# +# diff --git a/NEWS b/NEWS index 8b1378917..e69de29bb 100644 --- a/NEWS +++ b/NEWS @@ -1 +0,0 @@ - diff --git a/Projekt.dia b/Projekt.dia deleted file mode 100644 index c61a45a67..000000000 Binary files a/Projekt.dia and /dev/null differ diff --git a/README b/README index 8b1378917..e69de29bb 100644 --- a/README +++ b/README @@ -1 +0,0 @@ - diff --git a/SDL_Extensions.cpp b/SDL_Extensions.cpp index 0389a56c6..609a51513 100644 --- a/SDL_Extensions.cpp +++ b/SDL_Extensions.cpp @@ -9,8 +9,7 @@ #include #include "hch/CDefHandler.h" #include - -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 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; iformat->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; yh; ++y) - { - for(int x=0; xw; ++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; yh; ++y) - { - for(int x=0; xw; ++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 sort1; - sort1.push_back(cp[0]); - sort1.push_back(cp[1]); - sort1.push_back(cp[2]); - std::vector< std::pair > 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 sort1; - sort1.push_back(cp[2]); - sort1.push_back(cp[1]); - sort1.push_back(cp[0]); - std::vector< std::pair > 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;iformat->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 & tor) { for (int i=0;(i & tor); //replaces %s in string diff --git a/SDL_rotozoom.cpp b/SDL_rotozoom.cpp deleted file mode 100644 index 2e36db595..000000000 --- a/SDL_rotozoom.cpp +++ /dev/null @@ -1,1231 +0,0 @@ -/* - - SDL_rotozoom.c - rotozoomer for 32bit or 8bit surfaces - - LGPL (c) A. Schiffler - -*/ -#include "stdafx.h" -#ifdef WIN32 -#include -#endif - -#include -#include - -#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); -} diff --git a/SDL_rotozoom.h b/SDL_rotozoom.h deleted file mode 100644 index cc3b7720b..000000000 --- a/SDL_rotozoom.h +++ /dev/null @@ -1,117 +0,0 @@ - -/* - - SDL_rotozoom - rotozoomer - - LGPL (c) A. Schiffler - -*/ - -#ifndef _SDL_rotozoom_h -#define _SDL_rotozoom_h - -#include - -/* 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 */ diff --git a/StartInfo.h b/StartInfo.h index da09eb13f..86a79ecb9 100644 --- a/StartInfo.h +++ b/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 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 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 void serialize(Handler &h, const int version) + { + h & difficulty; + h & playerInfos; + h & turnTime; + h & mapname; + } }; #endif diff --git a/aclocal.m4 b/aclocal.m4 index 5285515bf..ab2ad391e 100644 --- a/aclocal.m4 +++ b/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]) diff --git a/aclocal/m4/ax_boost_thread.m4 b/aclocal/m4/ax_boost_thread.m4 new file mode 100644 index 000000000..94ab82e11 --- /dev/null +++ b/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 +# . +# +# This macro calls: +# +# AC_SUBST(BOOST_THREAD_LIB) +# +# And sets: +# +# HAVE_BOOST_THREAD +# +# LAST MODIFICATION +# +# 2008-04-12 +# +# COPYLEFT +# +# Copyright (c) 2008 Thomas Porschberg +# 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_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 +]) diff --git a/client/CBitmapHandler.cpp b/client/CBitmapHandler.cpp new file mode 100644 index 000000000..1bbb67caa --- /dev/null +++ b/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 +#include +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<0;y--) + { + it=0xC+(y-1)*bh.x; + for (int j=0;j0) + { + for (int j=0;j0; y--) + { + it=0xC+(y-1)*bh.x*3; + for (int j=0;j0) + { + for (int j=0;jformat->palette->colors+i) = tp; + } + for (y=bh.y;y>0;y--) + { + it=0xC+(y-1)*bh.x; + for (int j=0;jpixels + ret->pitch * (y-1) + ret->format->BytesPerPixel * j) = pcx[it+j]; + } + if (add>0) + { + for (int j=0;jpixels + 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;jpixels + ret->pitch * (y-1) + j) = pcx[it+j]; + } + if (add>0) + { + for (int j=0;jpixels + 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 "<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 "<realSize); + SDL_Surface * ret = cp.getSurface(); + if(setKey) + SDL_SetColorKey(ret,SDL_SRCCOLORKEY,SDL_MapRGB(ret->format,0,255,255)); + return ret; +} \ No newline at end of file diff --git a/client/CBitmapHandler.h b/client/CBitmapHandler.h new file mode 100644 index 000000000..53114c138 --- /dev/null +++ b/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); +}; \ No newline at end of file diff --git a/client/CCreatureAnimation.cpp b/client/CCreatureAnimation.cpp new file mode 100644 index 000000000..e1916cda4 --- /dev/null +++ b/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=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=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=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;i0) + { + 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 && xBw && yBh) + { + 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=0 && yB>=0 && xBw && yBh) + { + 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(TotalRowLength0) + { + 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; gpixels + 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; + } + } +} diff --git a/client/CCreatureAnimation.h b/client/CCreatureAnimation.h new file mode 100644 index 000000000..98b56012f --- /dev/null +++ b/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 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 +}; diff --git a/client/Client.cpp b/client/Client.cpp new file mode 100644 index 000000000..9b00bb45e --- /dev/null +++ b/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 +#include +#include +#include "../hch/CObjectHandler.h" +#include "../hch/CGeneralTextHandler.h" +#include "../hch/CArtHandler.h" +#include +#include "../lib/VCMI_Lib.h" +CSharedCond > mess(new std::set); + +std::string toString(MetaString &ms) +{ + std::string ret; + for(int i=0;i0) + { + ret += ms.strings[ms.message[i]-1]; + } + else + { + std::vector *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;istate = new CGameState(); + THC std::cout<<"\tGamestate: "<> pom8; + if(pom8) throw "Server cannot open the map!"; + c << ui8(si->playerInfos.size()); + for(int i=0;iplayerInfos.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: "<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: "<state; + gs->scenarioOps = si; + gs->init(si,mapa,seed); + + CGI->mh = new CMapHandler(); + THC std::cout<<"Initializing GameState (together): "<mh->map = mapa; + THC std::cout<<"Creating mapHandler: "<mh->init(); + THC std::cout<<"Initializing mapHandler (together): "<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(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."<> n; + std::cout << "New day: "<<(unsigned)n.day<<". Applying changes... "; + gs->apply(&n); + std::cout << "done!"<> sr; + std::cout << "Set amount of "<objh->restypes[sr.resid] + << " of player "<<(unsigned)sr.player <<" to "<apply(&sr); + playerint[sr.player]->receivedResource(sr.resid,sr.val); + break; + } + case 103: //show info dialog + { + InfoWindow iw; + *serv >> iw; + std::vector comps; + for(int i=0;ishowInfoDialog(toString(iw.text),comps); + break; + } + case 104: + { + SetResources sr; + *serv >> sr; + std::cout << "Set amount of resources of player "<<(unsigned)sr.player<apply(&sr); + playerint[sr.player]->receivedResource(-1,-1); + break; + } + case 105: + { + SetPrimSkill sps; + *serv >> sps; + std::cout << "Changing hero primary skill"<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(playerint[sii.player])->showComp(sc); + break; + } + case 500: + { + RemoveHero rh; + *serv >> rh; + CGHeroInstance *h = static_cast(gs->map->objects[rh.id]); + std::cout << "Removing hero with id = "<<(unsigned)rh.id<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="<id<<"\tResult: "<<(unsigned)th->result<<"\tPosition "<end<apply(th); + int player = gs->map->objects[th->id]->getOwner(); + + if(playerint[player]) + { + for(std::set::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::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(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::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(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 "<apply(&sop); + break; + } + case 1002: + { + SetHoverName shn; + *serv >> shn; + std::cout << "Setting a name of " << shn.id <<" object to "<< toString(shn.name) <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!" <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 <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 <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 <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 "<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 +} + diff --git a/client/Client.h b/client/Client.h new file mode 100644 index 000000000..7778e6692 --- /dev/null +++ b/client/Client.h @@ -0,0 +1,53 @@ +#pragma once +#include "../global.h" +#include +struct StartInfo; +class CGameState; +class CGameInterface; +class CConnection; +class CCallback; + +namespace boost +{ + class mutex; + class condition_variable; +} + +template +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 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; +}; diff --git a/client/Graphics.cpp b/client/Graphics.cpp new file mode 100644 index 000000000..54fe23859 --- /dev/null +++ b/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 +#include +#include +#include +#include +#include +#include +#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;iprimSkills[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 >::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 >::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>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>battleHeroes[i]; + } +} +Graphics::Graphics() +{ + slotsPos.push_back(std::pair(44,82)); + slotsPos.push_back(std::pair(80,82)); + slotsPos.push_back(std::pair(116,82)); + slotsPos.push_back(std::pair(26,131)); + slotsPos.push_back(std::pair(62,131)); + slotsPos.push_back(std::pair(98,131)); + slotsPos.push_back(std::pair(134,131)); + + CDefHandler *smi, *smi2; + + std::vector 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; iourImages.size(); i++) + { + smallImgs[i-2] = smi->ourImages[i].bitmap; + } + delete smi; + smi2->notFreeImgs = true; + for (int i=0; iourImages.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>ID; + std::string path; + of>>path; + portraitSmall.push_back(BitmapHandler::loadBitmap(path)); + for(int ff=0; ffformat,0,255,255)); + + } + of.close(); +} +void Graphics::loadHeroAnim(std::vector & anims) +{ + std::vector > 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; iourImages[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 Graphics::*, std::vector > &pr, bool mode) +{ + for(int i=0;i<8;i++) + (this->*pr.first).push_back(CDefHandler::giveDef(pr.second[i])); + std::vector > 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*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; oourImages.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 Graphics::*point; + std::pair Graphics::*, std::vector > 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: "<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; yh; ++y) + { + for(int x=0; xw; ++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 sort1; + sort1.push_back(cp[0]); + sort1.push_back(cp[1]); + sort1.push_back(cp[2]); + std::vector< std::pair > 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 sort1; + sort1.push_back(cp[2]); + sort1.push_back(cp[1]); + sort1.push_back(cp[0]); + std::vector< std::pair > 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; + } + } + } + } + } + } +} diff --git a/client/Graphics.h b/client/Graphics.h new file mode 100644 index 000000000..007f55ee1 --- /dev/null +++ b/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 > slotsPos; //creature slot positions in infoboxes + CDefEssential *luck22, *luck30, *luck42, *luck82, + *morale22, *morale30, *morale42, *morale82, + *halls, *forts, *bigTownPic; + std::map heroWins; //hero_ID => infobox + std::map townWins; //town_ID => infobox + CDefHandler * artDefs; //artifacts + std::vector portraitSmall; //48x32 px portraits of heroes + std::vector portraitLarge; //58x64 px portraits of heroes + std::vector 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 smallImgs; //creature ID -> small 32x32 img of creature; //ID=-2 is for blank (black) img; -1 for the border + std::map bigImgs; //creature ID -> big 58x64 img of creature; //ID=-2 is for blank (black) img; -1 for the border + std::map 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 Graphics::*, std::vector > &pr, bool mode); + void loadHeroAnim(std::vector & 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; \ No newline at end of file diff --git a/client/Makefile.am b/client/Makefile.am new file mode 100644 index 000000000..3607a6104 --- /dev/null +++ b/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 diff --git a/client/VCMI_client.vcproj b/client/VCMI_client.vcproj new file mode 100644 index 000000000..c1e2da63a --- /dev/null +++ b/client/VCMI_client.vcproj @@ -0,0 +1,570 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/config.h.in b/config.h.in index ff033e530..e67fd55fa 100644 --- a/config.h.in +++ b/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 header file. */ #undef HAVE_FCNTL_H diff --git a/configure.ac b/configure.ac index a7cfb011e..60fd85e67 100644 --- a/configure.ac +++ b/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) diff --git a/global.h b/global.h index c0b44233c..c28537ef4 100644 --- a/global.h +++ b/global.h @@ -1,22 +1,30 @@ #ifndef GLOBAL_H #define GLOBAL_H +#include +#include +#include +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 -#include -#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<= 4 + #define DLL_EXPORT __attribute__ ((visibility("default"))) + #else + #define DLL_EXPORT + #endif +#endif #define HANDLE_EXCEPTION \ catch (const std::exception& e) { \ diff --git a/hch/CAbilityHandler.cpp b/hch/CAbilityHandler.cpp index 2c40e676f..2269c5a8c 100644 --- a/hch/CAbilityHandler.cpp +++ b/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; iname,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); } } \ No newline at end of file diff --git a/hch/CAmbarCendamo.cpp b/hch/CAmbarCendamo.cpp index 9773a70ed..0bbe244a1 100644 --- a/hch/CAmbarCendamo.cpp +++ b/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 -#include -#include -#include "../CLua.h" - -int readInt(unsigned char * bufor, int bytCon) -{ - int ret=0; - int amp=1; - for (int i=0; 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;iiclose(); - // delete of; - //} -} -std::set convertBuildings(const std::set h3m, int castleID) -{ - std::map mapa; - std::set 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::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 "<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; iheroh->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; garth->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; ispellh->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; iabilh->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: "<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; yyabilities.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; ssartifacts.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; zzbiography+=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; ispellh->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 defsToUnpack; - for (int idd = 0 ; iddname += 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: "<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; yymessage +=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; ooabilities.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; ooartifacts.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; oospells.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; ggname+=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; yyabilities.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; ssartifacts.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; bbbiography+=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; ispellh->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(nhi))) = *nobj; - delete nobj; - nobj=nhi; - spec->myInstance = nhi; - //nobj->isHero = true; - (static_cast(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; qqabilities.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; ttmessage += 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; rrmessage += 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; yym5arts.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; hhm6cre.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; eefirstVisitText += bufor[i]; ++i; - } - - int len2 = readNormalNr(i); i+=4; - for(int ee=0; eenextVisitText += bufor[i]; ++i; - } - - int len3 = readNormalNr(i); i+=4; - for(int ee=0; eecompletedText += 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; iabilh->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; ggabilh->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; hhmessage += 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; mmmessage+=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; ggname += 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; ispellh->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; ispellh->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 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(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<h3mbuildings.insert(byte*8+bit); - } - } - } - for(int byte=6;byte<12;byte++) - { - for(int bit=0;bit<8;bit++) - { - if(spec->buildingSettings[byte] & (1<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(); - 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; vvmessage += 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; vvmessage += 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; ooabilities.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 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; oospells.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; yym5arts.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; hhm6cre.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; eefirstVisitText += bufor[i]; ++i; - } - - int len2; - len2 = readNormalNr(i); i+=4; - for(int ee=0; eenextVisitText += bufor[i]; ++i; - } - - int len3; - len3 = readNormalNr(i); i+=4; - for(int ee=0; eecompletedText += 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: "< dhandlers = CGameInfo::mainObj->spriteh->extractManyFiles(defsToUnpack); - - THC std::cout<<"\tUnpacking defs: "<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; vvhandler->alphaTransformed) - continue; - for(int yy=0; yyhandler->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: "<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=amp/2) - { - ret = ret-amp; - } - return ret; -} - -void CAmbarCendamo::loadDefs() -{ - std::set loadedTypes; - for (int i=0; ispriteh->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 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 > 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 > 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 > 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 > 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 > 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 > 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 > tt(6,ins); - ret.slots.insert(tt); - } - return ret; - } - else - { - CCreatureSet ret; - std::pair 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 > 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 > 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 > 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 > 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 > 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 > 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 > tt(6,ins); - ret.slots.insert(tt); - } - return ret; - } -} - -void CAmbarCendamo::processMap(std::vector & defsToUnpack) -{} +//#define VCMI_DLL +//#include "../stdafx.h" +//#include "CAmbarCendamo.h" +//#include "CObjectHandler.h" +//#include "CDefObjInfoHandler.h" +//#include +//#include +//#include +//#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 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 -#include #include #include #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 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 & defsToUnpack); //choose castles, creatures, resources, artifacts... - //// - std::vector 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 diff --git a/hch/CArtHandler.cpp b/hch/CArtHandler.cpp index 06b02a19f..06c989ed2 100644 --- a/hch/CArtHandler.cpp +++ b/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 +#include +#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 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 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 #include 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 treasures, minors, majors, relics; std::vector artifacts; void loadArtifacts(); bool loadArtEvents(); + CArtHandler(); }; #endif // CARTHANDLER_H diff --git a/hch/CBuildingHandler.cpp b/hch/CBuildingHandler.cpp index 5a285cbc1..b9a8b3ae1 100644 --- a/hch/CBuildingHandler.cpp +++ b/hch/CBuildingHandler.cpp @@ -1,9 +1,10 @@ +#define VCMI_DLL #include "../stdafx.h" -#include "../CGameInfo.h" #include "CBuildingHandler.h" #include "CLodHandler.h" #include #include +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;fbitmaph->getTextFile("DWELLING.TXT"); + buf = bitmaph->getTextFile("DWELLING.TXT"); andame = buf.size(), it=0; for(int f=0;f +#include //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 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 > buildings; ///< first int is the castle ID, second the building ID (in ERM-U format) diff --git a/hch/CCastleHandler.cpp b/hch/CCastleHandler.cpp deleted file mode 100644 index 8f24dbd55..000000000 --- a/hch/CCastleHandler.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#include "../stdafx.h" -#include "CCastleHandler.h" \ No newline at end of file diff --git a/hch/CCastleHandler.h b/hch/CCastleHandler.h deleted file mode 100644 index 934472c18..000000000 --- a/hch/CCastleHandler.h +++ /dev/null @@ -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 buildings; //buildings we can build in this castle - std::vector isBuild; //isBuild[i] is true, when building buildings[i] has been built - std::vector 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 possibleSpells; - std::vector obligatorySpells; - std::vector availableSpells; - - std::vector events; - - unsigned char alignment; //255 - same as owner/random, 0 - same as red, 1 - same as blue, etc -}; - -#endif //CCASTLEHANDLER_H diff --git a/hch/CCreatureHandler.cpp b/hch/CCreatureHandler.cpp index 3f6f8181a..5f22ff6a3 100644 --- a/hch/CCreatureHandler.cpp +++ b/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 @@ -8,8 +7,12 @@ #include #include #include -#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 &res) const //how many creatures can be bought +si32 CCreature::maxAmount(const std::vector &res) const //how many creatures can be bought { int ret = 2147483645; int resAmnt = std::min(res.size(),cost.size()); for(int i=0;ibitmaph->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; iourImages.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; iourImages.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; ispriteh->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=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=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=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;i0) - { - 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 && xBw && yBh) - { - 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=0 && yB>=0 && xBw && yBh) - { - 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(TotalRowLength0) - { - 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; gpixels + 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; - } - } -} diff --git a/hch/CCreatureHandler.h b/hch/CCreatureHandler.h index 8bdca2d24..de2d9524d 100644 --- a/hch/CCreatureHandler.h +++ b/hch/CCreatureHandler.h @@ -1,16 +1,14 @@ #ifndef CCREATUREHANDLER_H #define CCREATUREHANDLER_H - -#include "../CPlayerInterface.h" +#include "../global.h" #include #include #include -#include "CDefHandler.h" +#include -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 &res) const; //how many creatures can be bought + si32 maxAmount(const std::vector &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 > 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 smallImgs; //creature ID -> small 32x32 img of creature; //ID=-2 is for blank (black) img; -1 for the border - std::map bigImgs; //creature ID -> big 58x64 img of creature; //ID=-2 is for blank (black) img; -1 for the border - std::map backgrounds; //castle ID -> 100x130 background creature image // -1 is for neutral std::vector creatures; //creature ID -> creature info std::map > levelCreatures; //level -> list of creatures std::map 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 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 diff --git a/hch/CDefHandler.cpp b/hch/CDefHandler.cpp index 39b3396fd..df5e44f95 100644 --- a/hch/CDefHandler.cpp +++ b/hch/CDefHandler.cpp @@ -1,7 +1,9 @@ #include "../stdafx.h" +#include "SDL.h" #include "CDefHandler.h" #include - +#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; +} + diff --git a/hch/CDefHandler.h b/hch/CDefHandler.h index bf91321d4..e160e4038 100644 --- a/hch/CDefHandler.h +++ b/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 SEntries ; - char id[2]; - - -public: - std::string defName, curDir; - std::vector 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 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 SEntries ; + char id[2]; + + +public: + static CLodHandler * Spriteh; + std::string defName, curDir; + std::vector 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 ourImages; + ~CDefEssential(); +}; + +#endif // CDEFHANDLER_H diff --git a/hch/CDefObjInfoHandler.cpp b/hch/CDefObjInfoHandler.cpp index acd9ec269..fb51a6987 100644 --- a/hch/CDefObjInfoHandler.cpp +++ b/hch/CDefObjInfoHandler.cpp @@ -1,9 +1,11 @@ +#define VCMI_DLL #include "../stdafx.h" #include "CDefObjInfoHandler.h" #include "../CGameInfo.h" #include "CLodHandler.h" #include - +#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 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>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; -} +} \ No newline at end of file diff --git a/hch/CDefObjInfoHandler.h b/hch/CDefObjInfoHandler.h index d18f4527a..df3d047b5 100644 --- a/hch/CDefObjInfoHandler.h +++ b/hch/CDefObjInfoHandler.h @@ -2,8 +2,10 @@ #define COBJINFOECTHANDLER_H #include #include +#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 > gobjs; diff --git a/hch/CGeneralTextHandler.cpp b/hch/CGeneralTextHandler.cpp index 5b27e8280..60c888a46 100644 --- a/hch/CGeneralTextHandler.cpp +++ b/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 #include - +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 primarySkillNames; std::vector jktexts; std::vector 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(); }; diff --git a/hch/CHeroHandler.cpp b/hch/CHeroHandler.cpp index 3dab9ca6f..b9db4e17c 100644 --- a/hch/CHeroHandler.cpp +++ b/hch/CHeroHandler.cpp @@ -1,81 +1,60 @@ +#define VCMI_DLL #include "../stdafx.h" #include "CHeroHandler.h" -#include "../CGameInfo.h" #include -#include "../CGameInfo.h" -#include "CGeneralTextHandler.h" #include "CLodHandler.h" -#include "CAbilityHandler.h" -#include "../SDL_Extensions.h" -#include -#include +#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 possibles) //picks secondary skill out from given possibilities +{ + if(possibles.size()==1) + return *possibles.begin(); + int totalProb = 0; + for(std::set::iterator i=possibles.begin(); i!=possibles.end(); i++) { - delete heroes[j]; + totalProb += proSec[*i]; } - for(std::map::iterator it = smallPortraits.begin(); it!=smallPortraits.end(); ++it) + int ran = rand()%totalProb; + for(std::set::iterator i=possibles.begin(); i!=possibles.end(); i++) { - delete it->second; - } - for(std::map::iterator it = largePortraits.begin(); it!=largePortraits.end(); ++it) - { - 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>ID; - std::string path; - of>>path; - smallPortraits[ID] = CGI->bitmaph->loadBitmap(path); - if (!smallPortraits[ID]) - std::cout<<"Can't read small portrait for "<bitmaph->loadBitmap(path); - if (!largePortraits[ID]) - std::cout<<"Can't read large portrait for "<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; iheroh = 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;ibonusName,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;ibiography,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; yabilh->abilities.size(); ++dd) + for(int dd=0; ddmoveAnim = CGI->spriteh->giveDef(nm.str()); - - for(int o=0; omoveAnim->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; omoveAnim->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; ffmoveAnim->ourImages.size(); ++ff) - { - CSDL_Ext::alphaTransform(hc->moveAnim->ourImages[ff].bitmap); - } - hc->moveAnim->alphaTransformed = true; heroClasses.push_back(hc); } } diff --git a/hch/CHeroHandler.h b/hch/CHeroHandler.h index 1b4d7b92d..34bf77c8c 100644 --- a/hch/CHeroHandler.h +++ b/hch/CHeroHandler.h @@ -1,19 +1,14 @@ #ifndef CHEROHANDLER_H #define CHEROHANDLER_H - +#include "../global.h" #include #include -#include "CCreatureHandler.h" -#include "SDL.h" -#include "../int3.h" -#include "CAmbarCendamo.h" -#include "../CGameInterface.h" - +#include 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 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 possibles); //picks secondary skill out from given possibilities + CHeroClass(); + ~CHeroClass(); }; -class CHeroHandler +class DLL_EXPORT CHeroHandler { public: - std::vector heroInstances; std::vector heroes; //by³o nodrze std::vector heroClasses; - std::vector flags1, flags2, flags3, flags4; //flags blitted on heroes when , - std::map 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 pskillsn; std::vector 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 diff --git a/hch/CLodHandler.cpp b/hch/CLodHandler.cpp index e15221b5b..491459918 100644 --- a/hch/CLodHandler.cpp +++ b/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 #include #include #include -#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 +#include +#include +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 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<0;y--) - { - it=0xC+(y-1)*bh.x; - for (int j=0;j0) - { - for (int j=0;j0; y--) - { - it=0xC+(y-1)*bh.x*3; - for (int j=0;j0) - { - for (int j=0;jformat->palette->colors+i) = tp; - } - for (y=bh.y;y>0;y--) - { - it=0xC+(y-1)*bh.x; - for (int j=0;jpixels + ret->pitch * (y-1) + ret->format->BytesPerPixel * j) = pcx[it+j]; - } - if (add>0) - { - for (int j=0;jpixels + 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;jpixels + ret->pitch * (y-1) + j) = pcx[it+j]; - } - if (add>0) - { - for (int j=0;jpixels + 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 "<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 "<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; irealSize; + 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: "<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 CLodHandler::extractManyFiles(std::vector defNamesIn) -{ - std::vector ret(defNamesIn.size()); - for(int hh=0; hhoffset, 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; oostatus())) + { + 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!"<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: "<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;itrrealSize;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 +#include "../global.h" #include #include #include -#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 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 extractManyFiles(std::vector 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 diff --git a/hch/CMusicHandler.cpp b/hch/CMusicHandler.cpp index 891270524..102db06f1 100644 --- a/hch/CMusicHandler.cpp +++ b/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); diff --git a/hch/CObjectHandler.cpp b/hch/CObjectHandler.cpp index a13562f5f..6b943ce1a 100644 --- a/hch/CObjectHandler.cpp +++ b/hch/CObjectHandler.cpp @@ -1,72 +1,74 @@ +#define VCMI_DLL #include "../stdafx.h" #include "CObjectHandler.h" -#include "../CGameInfo.h" -#include "CGeneralTextHandler.h" -#include "CLodHandler.h" -#include "CAmbarCendamo.h" -#include "../mapHandler.h" #include "CDefObjInfoHandler.h" -#include "../CLua.h" +#include "CLodHandler.h" +#include "CDefObjInfoHandler.h" #include "CHeroHandler.h" #include #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 (itbitmaph->getTextFile("ADVEVENT.TXT"); + buf = bitmaph->getTextFile("ADVEVENT.TXT"); it=0; std::string temp; while (itbitmaph->getTextFile("XTRAINFO.TXT"); + buf = bitmaph->getTextFile("XTRAINFO.TXT"); it=0; while (itbitmaph->getTextFile("MINENAME.TXT"); + buf = bitmaph->getTextFile("MINENAME.TXT"); it=0; while (it(temp,"")); } - buf = CGameInfo::mainObj->bitmaph->getTextFile("MINEEVNT.TXT"); + buf = bitmaph->getTextFile("MINEEVNT.TXT"); it=0; int i=0; while (itbitmaph->getTextFile("RESTYPES.TXT"); + buf = bitmaph->getTextFile("RESTYPES.TXT"); it=0; while (itbitmaph->getTextFile("ZCRGN1.TXT"); + buf = bitmaph->getTextFile("ZCRGN1.TXT"); it=0; while (ithandler->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.xspeedspeed; + if(VLC->creh->creatures[army.slots[h].first].speedcreh->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 "< #include #include +#include #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 abilities; //gained abilities - std::vector abilityLevels; //levels of gained abilities - std::vector artifacts; //gained artifacts - std::vector 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 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 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 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 spells; //hero's spells - int attack, defence, power, knowledge; //main hero's attributes - unsigned int experience; //hero's experience points - std::vector abilities; //hero's abilities - std::vector 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 m5arts; - //for mission 6 - std::vector m6cre; - std::vector 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 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 abilities; - std::vector abilityLevels; - std::vector artifacts; - std::vector 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 CCreGen3ObjInfo : public CSpecObjInfo -{ -public: - unsigned char player; //owner - unsigned char minLevel, maxLevel; //minimal and maximal level of creature in dwelling: <0, 6> -}; - -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 m5arts; - //for mission 6 - std::vector m6cre; - std::vector 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; -}; - -class CObject //typical object that can be encountered on a map -{ -public: - std::string name; //object's name -}; - +class CGTownInstance; +class CArtifact; class CGDefInfo; +class CSpecObjInfo; -class CGObjectInstance +class DLL_EXPORT 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 + + bool operator<(const CCastleEvent &drugie) const + { + return firstShow primSkills; //0-attack, 1-defence, 2-spell power, 3-knowledge std::vector > 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; - bool inTownGarrison; // if hero is in town garrison + struct DLL_EXPORT Patrol + { + Patrol(){patrolling=false;patrolRadious=-1;}; + bool patrolling; + int patrolRadious; + } patrol; + + + bool inTownGarrison; // if hero is in town garrison CGTownInstance * visitedTown; //set if hero is visiting town or in the town garrison - std::vector artifacts; //hero's artifacts from bag - std::vector 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 artifacts; //hero's artifacts from bag + std::map artifWorn; //map; 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 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 forbiddenBuildings, builtBuildings; + std::vector possibleSpells, obligatorySpells, availableSpells; struct StrInfo { - public: - std::map creatures; //level - available amount + std::map creatures; //level - available amount + + template void serialize(Handler &h, const int version) + { + h & creatures; + } } strInfo; + std::set events; - std::set forbiddenBuildings, builtBuildings, h3mbuildings; - - const CGHeroInstance * garrisonHero, *visitingHero; - - std::vector 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 objects; //vector of objects; i-th object in vector has subnumber i - std::vector objInstances; //vector with objects on map + std::vector names; //vector of objects; i-th object in vector has subnumber i std::vector cregens; //type 17. dwelling subid -> creature ID void loadObjects(); diff --git a/hch/CPreGameTextHandler.cpp b/hch/CPreGameTextHandler.cpp index afec40335..f0171f4bc 100644 --- a/hch/CPreGameTextHandler.cpp +++ b/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(itrbitmaph->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) diff --git a/hch/CSemiDefHandler.cpp b/hch/CSemiDefHandler.cpp deleted file mode 100644 index 2d0b0d6ff..000000000 --- a/hch/CSemiDefHandler.cpp +++ /dev/null @@ -1,148 +0,0 @@ -#include "../stdafx.h" -#include "CSemiDefHandler.h" -#include -#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;iw; - 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); -} diff --git a/hch/CSemiDefHandler.h b/hch/CSemiDefHandler.h deleted file mode 100644 index b00308f78..000000000 --- a/hch/CSemiDefHandler.h +++ /dev/null @@ -1,31 +0,0 @@ -#ifndef SEMIDEF_H -#define SEMIDEF_H -#include "../global.h" -#include -#include "SDL.h" -//#include "SDL_image.h" -#include - -struct Cimage -{ - int groupNumber; - std::string imName; //name without extension - SDL_Surface * bitmap; -}; -class CSemiDefHandler -{ -public: - int howManyImgs; - std::string defName; - std::vector ourImages; - std::vector 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 diff --git a/hch/CSemiLodHandler.cpp b/hch/CSemiLodHandler.cpp deleted file mode 100644 index 1043774d4..000000000 --- a/hch/CSemiLodHandler.cpp +++ /dev/null @@ -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; -}; \ No newline at end of file diff --git a/hch/CSemiLodHandler.h b/hch/CSemiLodHandler.h deleted file mode 100644 index 8d55cc46e..000000000 --- a/hch/CSemiLodHandler.h +++ /dev/null @@ -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 diff --git a/hch/CSpellHandler.cpp b/hch/CSpellHandler.cpp index 0b2d1bae8..244969e48 100644 --- a/hch/CSpellHandler.cpp +++ b/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; diff --git a/hch/CTownHandler.cpp b/hch/CTownHandler.cpp index ce93c8708..e99640166 100644 --- a/hch/CTownHandler.cpp +++ b/hch/CTownHandler.cpp @@ -1,24 +1,22 @@ +#define VCMI_DLL #include "../stdafx.h" #include "CTownHandler.h" -#include "../CGameInfo.h" #include "CLodHandler.h" #include -#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(itrbitmaph->getTextFile("HALLINFO.TXT"); + strs = bitmaph->getTextFile("HALLINFO.TXT"); itr=0; while(itrourImages[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; -} - diff --git a/hch/CTownHandler.h b/hch/CTownHandler.h index 932fd725b..2cf895980 100644 --- a/hch/CTownHandler.h +++ b/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 -#include +#include "../global.h" #include 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 towns; std::vector 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 > structures; // > std::map > > requirements; //requirements[town_id][structure_id] -> set of required buildings - std::vector townInstances; - + CTownHandler(); + ~CTownHandler(); + void loadNames(); }; #endif //CTOWNHANDLER_H diff --git a/int3.h b/int3.h index 49e5a0767..2b28a2885 100644 --- a/int3.h +++ b/int3.h @@ -1,22 +1,34 @@ #ifndef INT3_H #define INT3_H +#include +class CCreature; +class CCreatureSet //seven combined creatures +{ +public: + std::map > slots; //slots[slot_id]=> pair(creature_id,creature_quantity) + bool formation; //false - wide, true - tight + template 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 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< void serialize(Handler &h, const int version) + { + h & side & stackNumber & actionType & destinationTile & additionalInfo; + } +}; \ No newline at end of file diff --git a/lib/CondSh.h b/lib/CondSh.h new file mode 100644 index 000000000..0cc44f23b --- /dev/null +++ b/lib/CondSh.h @@ -0,0 +1,13 @@ +#pragma once +#include +template 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 lock(mx); return data;}; +}; \ No newline at end of file diff --git a/lib/Connection.cpp b/lib/Connection.cpp new file mode 100644 index 000000000..ee5234704 --- /dev/null +++ b/lib/Connection.cpp @@ -0,0 +1,104 @@ +#define VCMI_DLL +#pragma warning(disable:4355) +#include "Connection.h" +#include +#include +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 "<connect(*endpoint_iterator, error); + if (error){ delete socket; throw "Can't establish connection :("; } + init(); +} +CConnection::CConnection( + boost::asio::basic_stream_socket > * 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 > * 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" <close(); + delete socket; + delete io_service; + delete wmx; + delete rmx; +} + +template <> +void CConnection::saveSerializable(const std::string &data) +{ + *this << ui32(data.size()); + write(data.c_str(),data.size()); +} + +template <> +void CConnection::loadSerializable(std::string &data) +{ + ui32 l; + *this >> l; + data.resize(l); + read((void*)data.c_str(),l); +} diff --git a/lib/Connection.h b/lib/Connection.h new file mode 100644 index 000000000..a071f7dd0 --- /dev/null +++ b/lib/Connection.h @@ -0,0 +1,382 @@ +#pragma once +#include "../global.h" +#include +#include +#include + +#include +#include +#include +#include + +#include +#include +#include +#include + +const int version = 63; +class CConnection; + +namespace mpl = boost::mpl; + +namespace boost +{ + namespace asio + { + namespace ip + { + class tcp; + } + class io_service; + + template class stream_socket_service; + template + class basic_stream_socket; + + template class socket_acceptor_service; + template + class basic_socket_acceptor; + } + class mutex; +}; + +enum SerializationLvl +{ + Wrong=0, + Primitive, + Pointer, + Serializable +}; + +template +struct SerializationLevel +{ + typedef mpl::integral_c_tag tag; + typedef + typename mpl::eval_if< + boost::is_fundamental, + mpl::int_, + //else + typename mpl::eval_if< + boost::is_class, + mpl::int_, + //else + typename mpl::eval_if< + boost::is_array, + mpl::int_, + //else + typename mpl::eval_if< + boost::is_pointer, + mpl::int_, + //else + typename mpl::eval_if< + boost::is_enum, + mpl::int_, + //else + mpl::int_ + > + > + > + > + >::type type; + static const int value = SerializationLevel::type::value; +}; + +template class DLL_EXPORT COSer +{ +public: + bool saving; + COSer(){saving=true;}; + Serializer * This() + { + return static_cast(this); + } + + template + Serializer & operator<<(const T &t) + { + this->This()->save(t); + return * this->This(); + } + + template + COSer & operator&(T & t){ + return * this->This() << t; + } +}; +template class DLL_EXPORT CISer +{ +public: + bool saving; + CISer(){saving = false;}; + Serializer * This() + { + return static_cast(this); + } + + template + Serializer & operator>>(T &t) + { + this->This()->load(t); + return * this->This(); + } + + template + CISer & operator&(T & t){ + return * this->This() >> t; + } +}; + +template +struct SavePrimitive +{ + static void invoke(Ser &s, const T &data) + { + s.savePrimitive(data); + } +}; +template +struct SaveSerializable +{ + static void invoke(Ser &s, const T &data) + { + s.saveSerializable(data); + } +}; +template +struct LoadPrimitive +{ + static void invoke(Ser &s, T &data) + { + s.loadPrimitive(data); + } +}; +template +struct SavePointer +{ + static void invoke(Ser &s, const T &data) + { + s.savePointer(data); + } +}; +template +struct LoadPointer +{ + static void invoke(Ser &s, T &data) + { + s.loadPointer(data); + } +}; +template +struct LoadSerializable +{ + static void invoke(Ser &s, T &data) + { + s.loadSerializable(data); + } +}; + +template +struct SaveWrong +{ + static void invoke(Ser &s, const T &data) + { + throw std::exception("Wrong save serialization call!"); + } +}; +template +struct LoadWrong +{ + static void invoke(Ser &s, const T &data) + { + throw std::exception("Wrong load serialization call!"); + } +}; + + +class DLL_EXPORT CConnection + :public CISer, public COSer +{ + + + std::ostream &out; + CConnection(void); + void init(); +public: + boost::mutex *rmx, *wmx; // read/write mutexes + + template + void savePrimitive(const T &data) + { + write(&data,sizeof(data)); + } + template + void loadPrimitive(T &data) + { + read(&data,sizeof(data)); + } + + + + template + void saveSerializable(const T &data) + { + const_cast(data).serialize(*static_cast*>(this),version); + } + template + void loadSerializable(T &data) + { + data.serialize(*static_cast*>(this),version); + } + template + void savePointer(const T &data) + { + *this << *data; + } + template + void loadPointer(T &data) + { + std::cout<<"Allocating memory for pointer!"<::type npT; + data = new npT; + *this >> *data; + } + template + void saveSerializable(const std::vector &data) + { + boost::uint32_t length = data.size(); + *this << length; + for(ui32 i=0;i + void loadSerializable(std::vector &data) + { + boost::uint32_t length; + *this >> length; + data.resize(length); + for(ui32 i=0;i> data[i]; + } + + template + void saveSerializable(const std::set &data) + { + std::set &d = const_cast &>(data); + boost::uint32_t length = d.size(); + *this << length; + for(typename std::set::iterator i=d.begin();i!=d.end();i++) + *this << *i; + } + template + void loadSerializable(std::set &data) + { + boost::uint32_t length; + *this >> length; + T ins; + for(ui32 i=0;i> ins; + data.insert(ins); + } + } + + template + void saveSerializable(const std::pair &data) + { + *this << data.first << data.second; + } + template + void loadSerializable(std::pair &data) + { + *this >> data.first >> data.second; + } + + template + void saveSerializable(const std::map &data) + { + *this << ui32(data.size()); + for(typename std::map::const_iterator i=data.begin();i!=data.end();i++) + *this << i->first << i->second; + } + template + void loadSerializable(std::map &data) + { + ui32 length; + *this >> length; + T1 t; + for(int i=0;i> t; + *this >> data[t]; + } + } + template + void save(const T &data) + { + typedef + //if + typename mpl::eval_if< mpl::equal_to,mpl::int_ >, + mpl::identity >, + //else if + typename mpl::eval_if,mpl::int_ >, + mpl::identity >, + //else if + typename mpl::eval_if,mpl::int_ >, + mpl::identity >, + //else + mpl::identity > + > + > + >::type typex; + typex::invoke(*this, data); + } + + template + void load(T &data) + { + typedef + //if + typename mpl::eval_if< mpl::equal_to,mpl::int_ >, + mpl::identity >, + //else if + typename mpl::eval_if,mpl::int_ >, + mpl::identity >, + //else if + typename mpl::eval_if,mpl::int_ >, + mpl::identity >, + //else + mpl::identity > + > + > + >::type typex; + typex::invoke(*this, data); + } + + boost::asio::basic_stream_socket < boost::asio::ip::tcp , boost::asio::stream_socket_service > * 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 > * 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 > * 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(const std::string &data); +template <>DLL_EXPORT +void CConnection::loadSerializable(std::string &data); + + diff --git a/lib/Makefile.am b/lib/Makefile.am new file mode 100644 index 000000000..f03134e15 --- /dev/null +++ b/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 diff --git a/lib/NetPacks.h b/lib/NetPacks.h new file mode 100644 index 000000000..a53fa5ad9 --- /dev/null +++ b/lib/NetPacks.h @@ -0,0 +1,337 @@ +#include "../global.h" +struct IPack +{ + virtual ui16 getType()const = 0 ; + //template + //static bool isType(const IPack * ip) + //{ + // return Type == ip->getType(); + //} + template + static bool isType(IPack * ip) + { + return Type == ip->getType(); + } + //template + //static bool isType(const IPack & ip) + //{ + // return Type == ip.getType(); + //} +}; +template struct CPack + :public IPack +{ + ui16 type; + ui16 getType() const{return type;} + T* This(){return static_cast(this);}; +}; +struct NewTurn : public CPack //101 +{ + struct Hero + { + ui32 id, move, mana; //id is a general serial id + template 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 void serialize(Handler &h, const int version) + { + h & player & resources; + } + bool operator<(const Resources&h)const{return player < h.player;} + }; + + std::set heroes; //updates movement and mana points + std::set res;//resource list + ui32 day; + bool resetBuilded; + + NewTurn(){type = 101;}; + + template void serialize(Handler &h, const int version) + { + h & heroes & res & day & resetBuilded; + } +}; +struct SetResource : public CPack //102 +{ + SetResource(){type = 102;}; + + ui8 player, resid; + si32 val; + + template void serialize(Handler &h, const int version) + { + h & player & resid & val; + } +}; +struct SetResources : public CPack //104 +{ + SetResources(){type = 104;}; + ui8 player; + std::vector res; //res[resid] => res amount + + template void serialize(Handler &h, const int version) + { + h & player & res; + } +}; +struct SetPrimSkill : public CPack //105 +{ + SetPrimSkill(){type = 105;}; + ui8 abs; //0 - changes by value; 1 - sets to value + si32 id; + ui16 which, val; + + template void serialize(Handler &h, const int version) + { + h & abs & id & which & val; + } +}; +struct RemoveHero : public CPack //500 +{ + RemoveHero(){type = 500;}; + RemoveHero(si32 ID){id = ID;type = 500;}; + si32 id; + + template void serialize(Handler &h, const int version) + { + h & id; + } +}; +struct TryMoveHero : public CPack //501 +{ + TryMoveHero(){type = 501;}; + + ui32 id, movePoints; + ui8 result; + int3 start, end; + std::set fowRevealed; //revealed tiles + + template void serialize(Handler &h, const int version) + { + h & id & result & start & end & movePoints & fowRevealed; + } +}; +struct SetGarrisons : public CPack //502 +{ + SetGarrisons(){type = 502;}; + std::map garrs; + + template void serialize(Handler &h, const int version) + { + h & garrs; + } +}; +struct SetStrInfo : public CPack //503 +{ + SetStrInfo(){type = 503;}; + si32 tid; + std::map cres; + + template void serialize(Handler &h, const int version) + { + h & tid & cres; + } +}; +struct NewStructures : public CPack //504 +{ + NewStructures(){type = 504;}; + si32 tid; + std::set bid; + si16 builded; + + template void serialize(Handler &h, const int version) + { + h & tid & bid & builded; + } +}; +struct MetaString : public CPack //2001 helper for object scrips +{ + std::vector strings; + std::vector > texts; //pairs; 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 message; + std::vector replacements; + + template void serialize(Handler &h, const int version) + { + h & strings & texts & message & replacements; + } + + MetaString& operator<<(const std::pair &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 //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 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 //103 - displays simple info window +{ + MetaString text; + std::vector components; + ui8 player; + + template void serialize(Handler &h, const int version) + { + h & text & components & player; + } + InfoWindow(){type = 103;}; +}; + +struct SetObjectProperty : public CPack//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 void serialize(Handler &h, const int version) + { + h & id & what & val; + } +}; + +struct SetHoverName : public CPack//1002 +{ + ui32 id; + MetaString name; + SetHoverName(){type = 1002;}; + SetHoverName(ui32 ID, MetaString& Name):id(ID),name(Name){type = 1002;}; + + template void serialize(Handler &h, const int version) + { + h & id & name; + } +}; +struct HeroLevelUp : public CPack//2000 +{ + si32 id; + ui8 primskill, level; + std::set skills; + + HeroLevelUp(){type = 2000;}; + + template void serialize(Handler &h, const int version) + { + h & id & primskill & level & skills; + } +}; +struct BattleInfo; +struct BattleStart : public CPack//3000 +{ + BattleInfo * info; + + BattleStart(){type = 3000;}; + + template void serialize(Handler &h, const int version) + { + h & info; + } +}; +struct BattleNextRound : public CPack//3001 +{ + si32 round; + + BattleNextRound(){type = 3001;}; + + template void serialize(Handler &h, const int version) + { + h & round; + } +}; +struct BattleSetActiveStack : public CPack//3002 +{ + ui32 stack; + + BattleSetActiveStack(){type = 3002;}; + template void serialize(Handler &h, const int version) + { + h & stack; + } +}; +struct BattleResult : public CPack//3003 +{ + ui8 result; //0 - normal victory; 1 - escape; 2 - surrender + ui8 winner; //0 - attacker, 1 - defender, [2 - draw (should be possible?)] + std::set > s1, s2; //first => casualties of attackers - set of pairs crid<>number + ui32 exp[2]; //exp for attacker and defender + std::set artifacts; //artifacts taken from loser to winner + + + + BattleResult(){type = 3003;}; + template void serialize(Handler &h, const int version) + { + h & result & winner & s1 & s2 & exp & artifacts; + } +}; + +struct BattleStackMoved : public CPack//3004 +{ + ui32 stack, tile; + ui8 flags; + + + + BattleStackMoved(){flags = 0; type = 3004;}; + bool startMoving() + { + return flags & 1; + } + bool endMoving() + { + return flags & 2; + } + template void serialize(Handler &h, const int version) + { + h & stack & tile & flags; + } +}; + +struct ShowInInfobox : public CPack //107 +{ + ShowInInfobox(){type = 107;}; + ui8 player; + Component c; + MetaString text; + + template void serialize(Handler &h, const int version) + { + h & player & c & text; + } +}; \ No newline at end of file diff --git a/lib/VCMI_Lib.cpp b/lib/VCMI_Lib.cpp new file mode 100644 index 000000000..c6e208609 --- /dev/null +++ b/lib/VCMI_Lib.cpp @@ -0,0 +1,161 @@ +#define VCMI_DLL +#include "../global.h" +#include "VCMI_Lib.h" +#include "../hch/CArtHandler.h" +#include "../hch/CCreatureHandler.h" +#include "../hch/CDefObjInfoHandler.h" +#include "../hch/CHeroHandler.h" +#include "../hch/CObjectHandler.h" +#include "../hch/CTownHandler.h" +#include "../hch/CBuildingHandler.h" +class CLodHandler; +LibClasses * VLC = NULL; +CLodHandler * bitmaph=NULL; + +DLL_EXPORT void initDLL(CLodHandler *b) +{ + timeHandler pomtime; + bitmaph=b; + VLC = new LibClasses; + + CHeroHandler * heroh = new CHeroHandler; + heroh->loadHeroes(); + heroh->loadPortraits(); + VLC->heroh = heroh; + THC std::cout<<"\tHero handler: "<loadArtifacts(); + VLC->arth = arth; + THC std::cout<<"\tArtifact handler: "<loadCreatures(); + VLC->creh = creh; + THC std::cout<<"\tCreature handler: "<townh = new CTownHandler; + VLC->townh->loadNames(); + THC std::cout<<"\tTown handler: "<loadObjects(); + VLC->objh = objh; + THC std::cout<<"\tObject handler: "<dobjinfo = new CDefObjInfoHandler; + VLC->dobjinfo->load(); + THC std::cout<<"\tDef information handler: "<buildh = new CBuildingHandler; + VLC->buildh->loadBuildings(); + THC std::cout<<"\tBuilding handler: "< playerint; + //std::vector playerColors; + //SDL_Color neutralColor; + //StartInfo scenarioOps; +}; + +extern DLL_EXPORT LibClasses * VLC; + + +DLL_EXPORT void initDLL(CLodHandler *b); + +#endif //VCMI_LIB_H diff --git a/lib/VCMI_lib.vcproj b/lib/VCMI_lib.vcproj new file mode 100644 index 000000000..41ebcd03a --- /dev/null +++ b/lib/VCMI_lib.vcproj @@ -0,0 +1,390 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/map.cpp b/map.cpp index 28912ac74..531d1d77e 100644 --- a/map.cpp +++ b/map.cpp @@ -1,25 +1,208 @@ +#define VCMI_DLL #include "stdafx.h" #include "map.h" - -int readNormalNr (unsigned char * bufor, int pos, int bytCon = 4) +#include "hch/CObjectHandler.h" +#include "hch/CDefObjInfoHandler.h" +#include "lib/VCMI_Lib.h" +#include +#include +std::set convertBuildings(const std::set h3m, int castleID) { - int ret=0; - int amp=1; - for (int i=0; i mapa; + std::set ret; + std::ifstream b5("config/buildings5.txt"); + while(!b5.eof()) { - ret+=bufor[pos+i]*amp; - amp<<=8; + 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::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 "<>i) + { + ret |= (128>>i); + } } return ret; } -bool DefInfo::isVisitable() +EDefType getDefType(CGDefInfo * a) { - for (int i=6; i<12; i++) + switch(a->id) { - if (bytes[i]) - return true; + 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 + } +} +int readNormalNr (unsigned char * bufor, int pos, int bytCon = 4, bool cyclic = false) +{ + int ret=0; + int amp=1; + for (int ir=0; ir=amp/2) + { + ret = ret-amp; + } + return ret; +} +char readChar(unsigned char * bufor, int &i) +{ + return bufor[i++]; +} +std::string readString(unsigned char * bufor, int &i) +{ + int len = readNormalNr(bufor,i); i+=4; + std::string ret; ret.reserve(len); + for(int gg=0; ggRoE maps +{ + if(version) + { + CCreatureSet ret; + std::pair ins; + for(int ir=0;ir32768) + rettt = 65536-rettt+VLC->creh->creatures.size()-16; + ins.first = rettt; + ins.second = readNormalNr(bufor,i+ir*4+2, 2); + std::pair > tt(ir,ins); + ret.slots.insert(tt); + } + i+=number*4; + return ret; + } + else + { + CCreatureSet ret; + std::pair ins; + for(int ir=0;ir220) + rettt = 256-rettt+VLC->creh->creatures.size()-16; + ins.first = rettt; + ins.second = readNormalNr(bufor,i+ir*3+1, 2); + std::pair > tt(ir,ins); + ret.slots.insert(tt); + } + i+=number*3; + return ret; } - return false; } CMapHeader::CMapHeader(unsigned char *map) { @@ -259,3 +442,1925 @@ CMapHeader::CMapHeader(unsigned char *map) } } } +void Mapa::initFromBytes(unsigned char * bufor) +{ + THC timeHandler th; + th.getDif(); + int i=0; + version = (Eformat)(readNormalNr(bufor,i)); i+=4; //map version + areAnyPLayers = readChar(bufor,i); //invalid on some maps + height = width = (readNormalNr(bufor,i)); i+=4; // wymiary mapy + twoLevel = readChar(bufor,i); //czy sa lochy + terrain = new TerrainTile**[width]; // allocate memory + for (int ii=0;iiArtifactID = bufor[i+2]; + nr=(version==RoE ? 1 : 2); + break; + } + case gatherTroop: + { + vicConDetails = new VicCon1(); + int temp1 = bufor[i+2]; + int temp2 = bufor[i+3]; + ((VicCon1*)vicConDetails)->monsterID = bufor[i+2]; + ((VicCon1*)vicConDetails)->neededQuantity=readNormalNr(bufor,i+(version==RoE ? 3 : 4)); + nr=(version==RoE ? 5 : 6); + break; + } + case gatherResource: + { + vicConDetails = new VicCon2(); + ((VicCon2*)vicConDetails)->resourceID = bufor[i+2]; + ((VicCon2*)vicConDetails)->neededQuantity=readNormalNr(bufor,i+3); + nr=5; + break; + } + case buildCity: + { + vicConDetails = new VicCon3(); + ((VicCon3*)vicConDetails)->posOfCity.x = bufor[i+2]; + ((VicCon3*)vicConDetails)->posOfCity.y = bufor[i+3]; + ((VicCon3*)vicConDetails)->posOfCity.z = bufor[i+4]; + ((VicCon3*)vicConDetails)->councilNeededLevel = bufor[i+5]; + ((VicCon3*)vicConDetails)->fortNeededLevel = bufor[i+6]; + nr=5; + break; + } + case buildGrail: + { + vicConDetails = new VicCon4(); + if (bufor[i+4]>2) + ((VicCon4*)vicConDetails)->anyLocation = true; + else + { + ((VicCon4*)vicConDetails)->whereBuildGrail.x = bufor[i+2]; + ((VicCon4*)vicConDetails)->whereBuildGrail.y = bufor[i+3]; + ((VicCon4*)vicConDetails)->whereBuildGrail.z = bufor[i+4]; + } + nr=3; + break; + } + case beatHero: + { + vicConDetails = new VicCon5(); + ((VicCon5*)vicConDetails)->locationOfHero.x = bufor[i+2]; + ((VicCon5*)vicConDetails)->locationOfHero.y = bufor[i+3]; + ((VicCon5*)vicConDetails)->locationOfHero.z = bufor[i+4]; + nr=3; + break; + } + case captureCity: + { + vicConDetails = new VicCon6(); + ((VicCon6*)vicConDetails)->locationOfTown.x = bufor[i+2]; + ((VicCon6*)vicConDetails)->locationOfTown.y = bufor[i+3]; + ((VicCon6*)vicConDetails)->locationOfTown.z = bufor[i+4]; + nr=3; + break; + } + case beatMonster: + { + vicConDetails = new VicCon7(); + ((VicCon7*)vicConDetails)->locationOfMonster.x = bufor[i+2]; + ((VicCon7*)vicConDetails)->locationOfMonster.y = bufor[i+3]; + ((VicCon7*)vicConDetails)->locationOfMonster.z = bufor[i+4]; + nr=3; + break; + } + case takeDwellings: + { + vicConDetails = new CspecificVictoryConidtions(); + nr=0; + break; + } + case takeMines: + { + vicConDetails = new CspecificVictoryConidtions(); + nr=0; + break; + } + case transportItem: + { + vicConDetails = new VicCona(); + ((VicCona*)vicConDetails)->artifactID = bufor[i+2]; + ((VicCona*)vicConDetails)->destinationPlace.x = bufor[i+3]; + ((VicCona*)vicConDetails)->destinationPlace.y = bufor[i+4]; + ((VicCona*)vicConDetails)->destinationPlace.z = bufor[i+5]; + nr=4; + break; + } + } + vicConDetails->allowNormalVictory = bufor[i++]; + vicConDetails->appliesToAI = bufor[i++]; + i+=nr; + } + lossCondition.typeOfLossCon = (ElossCon)bufor[i++]; + switch (lossCondition.typeOfLossCon) //read loss conditions + { + case lossCastle: + { + lossCondition.castlePos.x=bufor[i++]; + lossCondition.castlePos.y=bufor[i++]; + lossCondition.castlePos.z=bufor[i++]; + break; + } + case lossHero: + { + lossCondition.heroPos.x=bufor[i++]; + lossCondition.heroPos.y=bufor[i++]; + lossCondition.heroPos.z=bufor[i++]; + break; + } + case timeExpires: + { + lossCondition.timeLimit = readNormalNr(bufor,i++,2); + i++; + break; + } + } + howManyTeams=bufor[i++]; //read number of teams + if(howManyTeams>0) //read team numbers + { + for(int rr=0; rr<8; ++rr) + { + players[rr].team=bufor[i++]; + } + } + //reading allowed heroes (20 bytes) + int ist; + + ist=i; //starting i for loop + + allowedHeroes.resize(HEROES_QUANTITY); + for(int xx=0;xxRoE) //probably reserved for further heroes + i+=4; + unsigned char disp = 0; + if(version>=SoD) + { + disp = bufor[i++]; + disposedHeroes.resize(disp); + for(int g=0; g=SoD) + { + //reading allowed spells (9 bytes) + ist=i; //starting i for loop + for(i; iID = 34; + cgh->subID = z; + if(readChar(bufor,i))//true if hore's experience is greater than 0 + { cgh->exp = readNormalNr(bufor,i); i+=4; } + else + cgh->exp = 0; + if(readChar(bufor,i))//true if hero has specified abilities + { + int howMany = readNormalNr(bufor,i); i+=4; + cgh->secSkills.resize(howMany); + for(int yy=0; yysecSkills[yy].first = readNormalNr(bufor,i, 1); ++i; + cgh->secSkills[yy].second = readNormalNr(bufor,i, 1); ++i; + } + } + bool artSet = bufor[i]; ++i; //true if artifact set is not default (hero has some artifacts) + int artmask = version == RoE ? 0xff : 0xffff; + int artidlen = version == RoE ? 1 : 2; + if(artSet) + { + for(int pom=0;pom<16;pom++) + { + int id = readNormalNr(bufor,i, artidlen); i+=artidlen; + if(id!=artmask) + cgh->artifWorn[pom] = id; + } + //misc5 art //17 + if(version>=SoD) + { + i+=2; + //int id = readNormalNr(bufor,i, artidlen); i+=artidlen; + //if(id!=artmask) + // spec->artifWorn[16] = id; + } + //spellbook + int id = readNormalNr(bufor,i, artidlen); i+=artidlen; + if(id!=artmask) + cgh->artifWorn[17] = id; + //19 //???what is that? gap in file or what? - it's probably fifth slot.. + if(version>RoE) + { + id = readNormalNr(bufor,i, artidlen); i+=artidlen; + if(id!=artmask) + cgh->artifWorn[18] = id; + } + else + i+=1; + //bag artifacts //20 + int amount = readNormalNr(bufor,i, 2); i+=2; //number of artifacts in hero's bag + if(amount>0) + { + for(int ss=0; ssartifacts.push_back(id); + } + } + } //artifacts + if(readChar(bufor,i))//customBio + cgh->biography = readString(bufor,i); + int sex = bufor[i++]; // 0xFF is default, 00 male, 01 female + if(readChar(bufor,i))//are spells + { + int ist = i; + for(i; ispells.insert((i-ist)*8+yy); + } + } + } + } + if(readChar(bufor,i))//customPrimSkills + { + cgh->primSkills.resize(4); + for(int xx=0;xx<4;xx++) + cgh->primSkills[xx] = bufor[i++]; + } + predefinedHeroes.push_back(cgh); + } + break; + } + case RoE: + i+=0; + break; + } + for (int c=0; cname.reserve(nameLength); + for (int cd=0;cdname += 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(bufor,i,2);i+=2; + vinya->terrainMenu = readNormalNr(bufor,i,2);i+=2; + vinya->id = readNormalNr(bufor,i,4);i+=4; + vinya->subid = readNormalNr(bufor,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; + defy.push_back(vinya); // add this def to the vector + } + THC std::cout<<"\tReading defs info: "<defInfo->id; + int p = 99; + switch(getDefType(nobj->defInfo)) + { + case EVENTOBJ_DEF: //for event - objects + { + CEventObjInfo * spec = new CEventObjInfo; + bool guardMess; + guardMess = bufor[i]; ++i; + if(guardMess) + { + int messLong = readNormalNr(bufor,i, 4); i+=4; + if(messLong>0) + { + spec->isMessage = true; + for(int yy=0; yymessage +=bufor[i+yy]; + } + i+=messLong; + } + spec->areGuarders = bufor[i]; ++i; + if(spec->areGuarders) + { + spec->guarders = readCreatureSet(bufor,i,7,(version>RoE)); + } + i+=4; + } + else + { + spec->isMessage = false; + spec->areGuarders = false; + spec->message = std::string(""); + } + spec->gainedExp = readNormalNr(bufor,i, 4); i+=4; + spec->manaDiff = readNormalNr(bufor,i, 4); i+=4; + spec->moraleDiff = readNormalNr(bufor,i, 1, true); ++i; + spec->luckDiff = readNormalNr(bufor,i, 1, true); ++i; + spec->wood = readNormalNr(bufor,i); i+=4; + spec->mercury = readNormalNr(bufor,i); i+=4; + spec->ore = readNormalNr(bufor,i); i+=4; + spec->sulfur = readNormalNr(bufor,i); i+=4; + spec->crystal = readNormalNr(bufor,i); i+=4; + spec->gems = readNormalNr(bufor,i); i+=4; + spec->gold = readNormalNr(bufor,i); i+=4; + spec->attack = readNormalNr(bufor,i, 1); ++i; + spec->defence = readNormalNr(bufor,i, 1); ++i; + spec->power = readNormalNr(bufor,i, 1); ++i; + spec->knowledge = readNormalNr(bufor,i, 1); ++i; + int gabn; //number of gained abilities + gabn = readNormalNr(bufor,i, 1); ++i; + for(int oo = 0; ooabilities.push_back(readNormalNr(bufor,i, 1)); ++i; + spec->abilityLevels.push_back(readNormalNr(bufor,i, 1)); ++i; + } + int gart = readNormalNr(bufor,i, 1); ++i; //number of gained artifacts + for(int oo = 0; ooartifacts.push_back(readNormalNr(bufor,i, (version == RoE ? 1 : 2))); i+=(version == RoE ? 1 : 2); + } + int gspel = readNormalNr(bufor,i, 1); ++i; //number of gained spells + for(int oo = 0; oospells.push_back(readNormalNr(bufor,i, 1)); ++i; + } + int gcre = readNormalNr(bufor,i, 1); ++i; //number of gained creatures + spec->creatures = readCreatureSet(bufor,i,gcre,(version>RoE)); + if(version>RoE) + i+=gcre; + i+=8; + spec->availableFor = readNormalNr(bufor,i, 1); ++i; + spec->computerActivate = readNormalNr(bufor,i, 1); ++i; + spec->humanActivate = readNormalNr(bufor,i, 1); ++i; + i+=4; + nobj->info = spec; + break; + } + case HERO_DEF: + { + CGHeroInstance * nhi = new CGHeroInstance; + (*(static_cast(nhi))) = *nobj; + delete nobj; + nobj=nhi; + if(version>RoE) + { + nhi->identifier = readNormalNr(bufor,i, 4); i+=4; + } + nhi->setOwner(bufor[i]); ++i; + nhi->subID = readNormalNr(bufor,i, 1); ++i; + if(readChar(bufor,i))//true if hero has nonstandard name + nhi->name = readString(bufor,i); + if(version>AB) + { + if(readChar(bufor,i))//true if hore's experience is greater than 0 + { nhi->exp = readNormalNr(bufor,i); i+=4; } + else + nhi->exp = -1; + } + else + { nhi->exp = readNormalNr(bufor,i); i+=4; } + + bool portrait=bufor[i]; ++i; + if (portrait) + i++; //TODO read portrait nr, save, open + else + nhi->portrait = nhi->subID; + + if(readChar(bufor,i))//true if hero has specified abilities + { + int howMany = readNormalNr(bufor,i); i+=4; + nhi->secSkills.resize(howMany); + for(int yy=0; yysecSkills[yy].first = readNormalNr(bufor,i, 1); ++i; + nhi->secSkills[yy].second = readNormalNr(bufor,i, 1); ++i; + } + } + if(readChar(bufor,i))//true if hero has nonstandard garrison + nhi->army = readCreatureSet(bufor,i,7,(version>RoE)); + nhi->army.formation =bufor[i]; ++i; //formation + bool artSet = bufor[i]; ++i; //true if artifact set is not default (hero has some artifacts) + int artmask = version == RoE ? 0xff : 0xffff; + int artidlen = version == RoE ? 1 : 2; + if(artSet) + { + for(int pom=0;pom<16;pom++) + { + int id = readNormalNr(bufor,i, artidlen); i+=artidlen; + if(id!=artmask) + nhi->artifWorn[pom] = id; + } + //misc5 art //17 + if(version>=SoD) + { + int id = readNormalNr(bufor,i, artidlen); i+=artidlen; + if(id!=artmask) + nhi->artifWorn[16] = id; + } + //spellbook + int id = readNormalNr(bufor,i, artidlen); i+=artidlen; + if(id!=artmask) + nhi->artifWorn[17] = id; + //19 //???what is that? gap in file or what? - it's probably fifth slot.. + if(version>RoE) + { + id = readNormalNr(bufor,i, artidlen); i+=artidlen; + if(id!=artmask) + nhi->artifWorn[18] = id; + } + else + i+=1; + //bag artifacts //20 + int amount = readNormalNr(bufor,i, 2); i+=2; //number of artifacts in hero's bag + if(amount>0) + { + for(int ss=0; ssartifacts.push_back(id); + } + } + } //artifacts + + nhi->patrol.patrolRadious = readNormalNr(bufor,i, 1); ++i; + if(nhi->patrol.patrolRadious == 0xff) + nhi->patrol.patrolling = false; + else + nhi->patrol.patrolling = true; + + if(version>RoE) + { + if(readChar(bufor,i))//true if hero has nonstandard (mapmaker defined) biography + nhi->biography = readString(bufor,i); + nhi->sex = !(bufor[i]); ++i; + } + //spells + if(version>AB) + { + bool areSpells = bufor[i]; ++i; + + if(areSpells) //TODO: sprawdziæ //seems to be ok - tow + { + int ist = i; + for(i; ispells.insert((i-ist)*8+yy); + } + } + } + } + } + else if(version==AB) //we can read one spell + { + unsigned char buff = bufor[i]; ++i; + if(buff!=254) + { + nhi->spells.insert(buff); + } + } + //spells loaded + if(version>AB) + { + if(readChar(bufor,i))//customPrimSkills + { + nhi->primSkills.resize(4); + for(int xx=0;xx<4;xx++) + nhi->primSkills[xx] = bufor[i++]; + } + } + i+=16; + nhi->moveDir = 4; + nhi->isStanding = true; + nhi->level = -1; + nhi->mana = -1; + nhi->movement = -1; + if(nhi->ID==34) + heroes.push_back(nhi); + break; + } + case CREATURES_DEF: + { + CCreatureObjInfo * spec = new CCreatureObjInfo; + if(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(bufor,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(bufor,i); i+=4; + if(messLength>0) + { + for(int tt=0; ttmessage += bufor[i]; ++i; + } + } + spec->wood = readNormalNr(bufor,i); i+=4; + spec->mercury = readNormalNr(bufor,i); i+=4; + spec->ore = readNormalNr(bufor,i); i+=4; + spec->sulfur = readNormalNr(bufor,i); i+=4; + spec->crytal = readNormalNr(bufor,i); i+=4; + spec->gems = readNormalNr(bufor,i); i+=4; + spec->gold = readNormalNr(bufor,i); i+=4; + int artID = readNormalNr(bufor,i, (version == RoE ? 1 : 2)); i+=(version == RoE ? 1 : 2); + if(version==RoE) + { + if(artID!=0xff) + spec->gainedArtifact = artID; + else + spec->gainedArtifact = -1; + } + else + { + if(artID!=0xffff) + spec->gainedArtifact = artID; + else + spec->gainedArtifact = -1; + } + } + 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(bufor,i); i+=4; + for(int rr=0; rrmessage += bufor[i]; ++i; + } + i+=4; + nobj->info = spec; + break; + } + case SEERHUT_DEF: + { + CSeerHutObjInfo * spec = new CSeerHutObjInfo; + if(version>RoE) + { + spec->missionType = bufor[i]; ++i; + switch(spec->missionType) + { + case 0: + i+=3; + continue; + case 1: + { + spec->m1level = readNormalNr(bufor,i); i+=4; + int limit = readNormalNr(bufor,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(bufor,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(bufor,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(bufor,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; yym5arts.push_back(artid); + } + int limit = readNormalNr(bufor,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; hhm6cre.push_back(&(VLC->creh->creatures[creType])); + spec->m6number.push_back(creNumb); + } + int limit = readNormalNr(bufor,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(bufor,i); i+=4; + spec->m7mercury = readNormalNr(bufor,i); i+=4; + spec->m7ore = readNormalNr(bufor,i); i+=4; + spec->m7sulfur = readNormalNr(bufor,i); i+=4; + spec->m7crystal = readNormalNr(bufor,i); i+=4; + spec->m7gems = readNormalNr(bufor,i); i+=4; + spec->m7gold = readNormalNr(bufor,i); i+=4; + int limit = readNormalNr(bufor,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 = heroType; + int limit = readNormalNr(bufor,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(bufor,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(bufor,i); i+=4; + for(int ee=0; eefirstVisitText += bufor[i]; ++i; + } + + int len2 = readNormalNr(bufor,i); i+=4; + for(int ee=0; eenextVisitText += bufor[i]; ++i; + } + + int len3 = readNormalNr(bufor,i); i+=4; + for(int ee=0; eecompletedText += bufor[i]; ++i; + } + } + else //RoE + { + int artID = bufor[i]; ++i; + if(artID!=255) //not none quest + { + spec->m5arts.push_back(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(bufor,i); i+=4; + break; + } + case 2: + { + spec->r2mana = readNormalNr(bufor,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(bufor,i, 3); i+=3; + i+=1; + break; + } + case 6: + { + spec->r6type = bufor[i]; ++i; + spec->r6amount = bufor[i]; ++i; + break; + } + case 7: + { + spec->r7ability = bufor[i]; ++i; + spec->r7level = bufor[i]; ++i; + break; + } + case 8: + { + spec->r8art = readNormalNr(bufor,i, (version == RoE ? 1 : 2)); i+=(version == RoE ? 1 : 2); + break; + } + case 9: + { + spec->r9spell = bufor[i]; ++i; + break; + } + case 10: + { + if(version>RoE) + { + spec->r10creature = readNormalNr(bufor,i, 2); i+=2; + spec->r10amount = readNormalNr(bufor,i, 2); i+=2; + } + else + { + spec->r10creature = bufor[i]; ++i; + spec->r10amount = readNormalNr(bufor,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(version>RoE) //in reo we cannot specify it - all are allowed (I hope) + { + ist=i; //starting i for loop + for(i; iallowedAbilities.push_back((i-ist)*8+yy); + } + } + } + } + else //(RoE map) + { + for(int gg=0; ggallowedAbilities.push_back(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 = bufor[i]; ++i; + break; + case 2: + spec->r2 = 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(bufor,i,7,(version>RoE)); + if(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(bufor,i, 4); i+=4; + for(int hh=0; hhmessage += bufor[i]; ++i; + } + bool areGuards = bufor[i]; ++i; + if(areGuards) + { + spec->areGuards = true; + spec->guards = readCreatureSet(bufor,i,7,(version>RoE)); + } + 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(bufor,i); i+=4; + for(int mm=0; mmmessage+=bufor[i]; ++i; + } + spec->areGuards = bufor[i]; ++i; + if(spec->areGuards) + { + spec->guards = readCreatureSet(bufor,i,7,(version>RoE)); + } + i+=4; + } + else + { + spec->areGuards = false; + } + spec->amount = readNormalNr(bufor,i); i+=4; + i+=4; + nobj->info = spec; + break; + } + case TOWN_DEF: + { + CGTownInstance * nt = new CGTownInstance(); + (*(static_cast(nt))) = *nobj; + delete nobj; + nobj = nt; + nt->identifier = 0; + if(version>RoE) + { + readNormalNr(bufor,i); i+=4; + } + nt->tempOwner = bufor[i]; ++i; + if(readChar(bufor,i)) //has name + nt->name = readString(bufor,i); + if(readChar(bufor,i))//true if garrison isn't empty + nt->army = readCreatureSet(bufor,i,7,(version>RoE)); + nt->army.formation = bufor[i]; ++i; + if(readChar(bufor,i)) //unusualBuildings + { + //built buildings + for(int byte=0;byte<6;byte++) + { + for(int bit=0;bit<8;bit++) + if(bufor[i] & (1<builtBuildings.insert(byte*8+bit); + i++; + } + //forbidden buildings + for(int byte=6;byte<12;byte++) + { + for(int bit=0;bit<8;bit++) + if(bufor[i] & (1<forbiddenBuildings.insert(byte*8+bit); + i++; + } + nt->builtBuildings = convertBuildings(nt->builtBuildings,nt->subID); + nt->forbiddenBuildings = convertBuildings(nt->forbiddenBuildings,nt->subID); + } + else //standard buildings + { + if(readChar(bufor,i)) //has fort + nt->builtBuildings.insert(7); + nt->builtBuildings.insert(-50); //means that set of standard building should be included + } + + int ist = i; + if(version>RoE) + { + for(i; iobligatorySpells.push_back((i-ist)*8+yy); + } + } + } + } + + ist = i; + for(i; ipossibleSpells.push_back((i-ist)*8+yy); + } + } + } + + /////// reading castle events ////////////////////////////////// + + int numberOfEvent = readNormalNr(bufor,i); i+=4; + + for(int gh = 0; gh AB) + { + nce.forHuman = bufor[i]; ++i; + } + else + nce.forHuman = true; + nce.forComputer = bufor[i]; ++i; + nce.firstShow = readNormalNr(bufor,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(bufor,i, 2); i+=2; + } + i+=4; + nt->events.insert(nce); + }//castle events have been read + + if(version > AB) + { + nt->alignment = bufor[i]; ++i; + } + else + nt->alignment = 0xff; + i+=3; + + nt->builded = 0; + nt->destroyed = 0; + nt->garrisonHero = NULL; + if(nt->ID==98) + towns.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(bufor,i); i+=4; + for(int vv=0; vvmessage += bufor[i]; ++i; + } + spec->areGuarders = bufor[i]; ++i; + if(spec->areGuarders) + { + spec->guarders = readCreatureSet(bufor,i,7,(version>RoE)); + } + i+=4; + } + spec->spell = 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(bufor,i); i+=4; + for(int vv=0; vvmessage += bufor[i]; ++i; + } + spec->areGuarders = bufor[i]; ++i; + if(spec->areGuarders) + { + spec->guarders = readCreatureSet(bufor,i,7,(version>RoE)); + } + i+=4; + } + ////// copied form event handling (seems to be similar) + spec->gainedExp = readNormalNr(bufor,i, 4); i+=4; + spec->manaDiff = readNormalNr(bufor,i, 4); i+=4; + spec->moraleDiff = readNormalNr(bufor,i, 1, true); ++i; + spec->luckDiff = readNormalNr(bufor,i, 1, true); ++i; + spec->wood = readNormalNr(bufor,i); i+=4; + spec->mercury = readNormalNr(bufor,i); i+=4; + spec->ore = readNormalNr(bufor,i); i+=4; + spec->sulfur = readNormalNr(bufor,i); i+=4; + spec->crystal = readNormalNr(bufor,i); i+=4; + spec->gems = readNormalNr(bufor,i); i+=4; + spec->gold = readNormalNr(bufor,i); i+=4; + spec->attack = readNormalNr(bufor,i, 1); ++i; + spec->defence = readNormalNr(bufor,i, 1); ++i; + spec->power = readNormalNr(bufor,i, 1); ++i; + spec->knowledge = readNormalNr(bufor,i, 1); ++i; + int gabn; //number of gained abilities + gabn = readNormalNr(bufor,i, 1); ++i; + for(int oo = 0; ooabilities.push_back(readNormalNr(bufor,i, 1)); ++i; + spec->abilityLevels.push_back(readNormalNr(bufor,i, 1)); ++i; + } + int gart = readNormalNr(bufor,i, 1); ++i; //number of gained artifacts + for(int oo = 0; oo RoE) + { + spec->artifacts.push_back(readNormalNr(bufor,i, 2)); i+=2; + } + else + { + spec->artifacts.push_back(readNormalNr(bufor,i, 1)); i+=1; + } + } + int gspel = readNormalNr(bufor,i, 1); ++i; //number of gained spells + for(int oo = 0; oospells.push_back(readNormalNr(bufor,i, 1)); ++i; + } + int gcre = readNormalNr(bufor,i, 1); ++i; //number of gained creatures + spec->creatures = readCreatureSet(bufor,i,gcre,(version>RoE)); + if(version > RoE) + i+=gcre; + i+=8; + nobj->info = spec; + ///////end of copied fragment + break; + } + case GRAIL_DEF: + { + CGrailObjInfo * spec = new CGrailObjInfo; + spec->radius = readNormalNr(bufor,i); i+=4; + nobj->info = spec; + break; + } + case CREGEN_DEF: + { + CCreGenObjInfo * spec = new CCreGenObjInfo; + spec->player = readNormalNr(bufor,i); i+=4; + spec->identifier = readNormalNr(bufor,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(bufor,i); i+=4; + spec->identifier = readNormalNr(bufor,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; + int len1, len2, len3; + switch(spec->missionType) + { + case 0: + { + goto borderguardend; + break; + } + case 1: + { + spec->m1level = readNormalNr(bufor,i); i+=4; + int limit = readNormalNr(bufor,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(bufor,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(bufor,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(bufor,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; yym5arts.push_back(readNormalNr(bufor,i, 2)); i+=2; + } + int limit = readNormalNr(bufor,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; hhm6cre.push_back(&(VLC->creh->creatures[creType])); + spec->m6number.push_back(creNumb); + } + int limit = readNormalNr(bufor,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(bufor,i); i+=4; + spec->m7mercury = readNormalNr(bufor,i); i+=4; + spec->m7ore = readNormalNr(bufor,i); i+=4; + spec->m7sulfur = readNormalNr(bufor,i); i+=4; + spec->m7crystal = readNormalNr(bufor,i); i+=4; + spec->m7gems = readNormalNr(bufor,i); i+=4; + spec->m7gold = readNormalNr(bufor,i); i+=4; + int limit = readNormalNr(bufor,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 = heroType; + int limit = readNormalNr(bufor,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(bufor,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) + + len1 = readNormalNr(bufor,i); i+=4; + for(int ee=0; eefirstVisitText += bufor[i]; ++i; + } + + len2 = readNormalNr(bufor,i); i+=4; + for(int ee=0; eenextVisitText += bufor[i]; ++i; + } + + len3 = readNormalNr(bufor,i); i+=4; + for(int ee=0; eecompletedText += bufor[i]; ++i; + } + nobj->info = spec; +borderguardend: + break; + } + case HEROPLACEHOLDER_DEF: + { + i+=3; //TODO: handle it more properly + break; + } + } //end of main switch + objects.push_back(nobj); + }//end of loading objects + THC std::cout<<"\tReading objects: "<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; + events.push_back(ne); + } + + //map readed, bufor no longer needed + delete[] bufor; bufor=NULL; + + + for(int f=0; fdefInfo) + continue; + CDefHandler * curd = objects[f]->defInfo->handler; + for(int fx=0; fx<8; ++fx) + { + for(int fy=0; fy<6; ++fy) + { + int xVal = objects[f]->pos.x + fx - 7; + int yVal = objects[f]->pos.y + fy - 5; + int zVal = objects[f]->pos.z; + if(xVal>=0 && xVal=0 && yValdefInfo->visitMap[fy] >> (7 - fx)) & 1)) + { + curt.visitableObjects.push_back(objects[f]); + curt.visitable = true; + } + if(!((objects[f]->defInfo->blockMap[fy] >> (7 - fx)) & 1)) + { + curt.blockingObjects.push_back(objects[f]); + curt.blocked = true; + } + } + } + } + } +} + +Mapa::Mapa(std::string filename) +{ + std::cout<<"Opening map file: "< 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; ssgetHero: This mode is not supported!"); +#else + throw new std::exception(); +#endif + + for(int i=0; isubID == ID) + return heroes[i]; + return NULL; +} diff --git a/map.h b/map.h index e0d43270c..f258ee1b1 100644 --- a/map.h +++ b/map.h @@ -3,19 +3,247 @@ #pragma warning (disable : 4482) #include #include +#include +#include #include "global.h" -#include "hch/CSemiDefHandler.h" -#include "hch/CDefHandler.h" class CGDefInfo; -class CHeroObjInfo; +class CGObjectInstance; +class CGHeroInstance; +class CGTownInstance; enum ESortBy{_name, _playerAm, _size, _format, _viccon, _loscon}; -struct Sresource +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 DLL_EXPORT CSpecObjInfo //class with object - specific info (eg. different information for creatures and heroes); use inheritance to make object - specific classes +{ +}; +class DLL_EXPORT 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 abilities; //gained abilities + std::vector abilityLevels; //levels of gained abilities + std::vector artifacts; //gained artifacts + std::vector 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 DLL_EXPORT 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 + int gainedArtifact; //ID of artifact gained to hero + bool neverFlees; //if true, the troops will never flee + bool notGrowingTeam; //if true, number of units won't grow +}; +class DLL_EXPORT CSignObjInfo : public CSpecObjInfo +{ +public: + std::string message; //message +}; +class DLL_EXPORT 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 + int m1level; //for mission 1 + int m2attack, m2defence, m2power, m2knowledge;//for mission 2 + unsigned char m3bytes[4];//for mission 3 + unsigned char m4bytes[4];//for mission 4 + std::vector m5arts;//for mission 5 - artifact ID + std::vector m6cre;//for mission 6 + std::vector m6number; + int m7wood, m7mercury, m7ore, m7sulfur, m7crystal, m7gems, m7gold; //for mission 7 + int m8hero;//for mission 8 - hero ID + int m9player; //for mission 9 - 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 + int r7ability; //ability id + unsigned char r7level; //1 - basic, 2 - advanced, 3 - expert + //for reward 8 + int r8art;//artifact id + //for reward 9 + int r9spell;//spell id + //for reward 10 + int r10creature; //creature id + int r10amount; +}; +class DLL_EXPORT CWitchHutObjInfo : public CSpecObjInfo +{ +public: + std::vector allowedAbilities; +}; +class DLL_EXPORT CScholarObjInfo : public CSpecObjInfo +{ +public: + unsigned char bonusType; //255 - random, 0 - primary skill, 1 - secondary skill, 2 - spell + + unsigned char r0type; + int r1; //Ability ID + int r2; //Spell ID +}; +class DLL_EXPORT CGarrisonObjInfo : public CSpecObjInfo +{ +public: + unsigned char player; //255 - nobody; 0 - 7 - players + CCreatureSet units; + bool movableUnits; //if true, units can be moved +}; +class DLL_EXPORT CArtifactObjInfo : public CSpecObjInfo +{ +public: + bool areGuards; + std::string message; + CCreatureSet guards; +}; +class DLL_EXPORT CResourceObjInfo : public CSpecObjInfo +{ +public: + bool randomAmount; + int amount; //if not random + bool areGuards; + CCreatureSet guards; + std::string message; +}; +class DLL_EXPORT CPlayerOnlyObjInfo : public CSpecObjInfo +{ +public: + unsigned char player; //FF - nobody, 0 - 7 +}; +class DLL_EXPORT CShrineObjInfo : public CSpecObjInfo +{ +public: + unsigned char spell; //number of spell or 255 +}; +class DLL_EXPORT CSpellScrollObjinfo : public CSpecObjInfo +{ +public: + std::string message; + int spell; + bool areGuarders; + CCreatureSet guarders; +}; +class DLL_EXPORT 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 abilities; + std::vector abilityLevels; + std::vector artifacts; + std::vector spells; + CCreatureSet creatures; +}; + +class DLL_EXPORT CGrailObjInfo : public CSpecObjInfo +{ +public: + int radius; //place grail at the distance lesser or equal radius from this place +}; +class DLL_EXPORT CCreGenObjInfo : public CSpecObjInfo +{ +public: + unsigned char player; //owner + bool asCastle; + int identifier; + unsigned char castles[2]; //allowed castles +}; +class DLL_EXPORT 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 DLL_EXPORT CCreGen3ObjInfo : public CSpecObjInfo +{ +public: + unsigned char player; //owner + unsigned char minLevel, maxLevel; //minimal and maximal level of creature in dwelling: <0, 6> +}; +class DLL_EXPORT 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 m5arts; //artifacts id + //for mission 6 + std::vector m6cre; + std::vector m6number; + //for mission 7 + int m7wood, m7mercury, m7ore, m7sulfur, m7crystal, m7gems, m7gold; + //for mission 8 + int m8hero; //hero id + //for mission 9 + int m9player; //number; from 0 to 7 + + std::string firstVisitText, nextVisitText, completedText; +}; + +struct DLL_EXPORT Sresource { std::string resName; //name of this resource int amount; //it can be greater and lesser than 0 }; - -struct TimeEvent +struct DLL_EXPORT TimeEvent { std::string eventName; std::string message; @@ -25,26 +253,8 @@ struct TimeEvent bool areCompsAffected; int firstAfterNDays; //how many days after appears this event int nextAfterNDays; //how many days after the epperance before appaers this event -//bajty wydarzeñ (59 + |teksty|) -//4 bajty na d³ugoœæ nazwy zdarzenia -//nazwa zdarzenia (bajty dodatkowe) -//4 bajty na d³ugoœæ wiadomoœci -//wiadomoœæ (bajty dodatkowe) -//4 bajty na zwiêkszenie siê ilosci drewna (zapis normalny) lub ff,ff,ff,ff - iloœæ drewna do odebrania (maksymalna iloœæ drewna, któr¹ mo¿na daæ/odebraæ to 32767) -//4 bajty na zwiêkszenie siê ilosci rtêci (zapis normalny) lub ff,ff,ff,ff - iloœæ rtêci do odebrania (maksymalna iloœæ rtêci, któr¹ mo¿na daæ/odebraæ to 32767) -//4 bajty na zwiêkszenie siê ilosci rudy (zapis normalny) lub ff,ff,ff,ff - iloœæ rudy do odebrania (maksymalna iloœæ rudy, któr¹ mo¿na daæ/odebraæ to 32767) -//4 bajty na zwiêkszenie siê ilosci siarki (zapis normalny) lub ff,ff,ff,ff - iloœæ siarki do odebrania (maksymalna iloœæ siarki, któr¹ mo¿na daæ/odebraæ to 32767) -//4 bajty na zwiêkszenie siê ilosci kryszta³u (zapis normalny) lub ff,ff,ff,ff - iloœæ kryszta³u do odebrania (maksymalna iloœæ kryszta³u, któr¹ mo¿na daæ/odebraæ to 32767) -//4 bajty na zwiêkszenie siê ilosci klejnotów (zapis normalny) lub ff,ff,ff,ff - iloœæ klejnotów do odebrania (maksymalna iloœæ klejnotów, któr¹ mo¿na daæ/odebraæ to 32767) -//4 bajty na zwiêkszenie siê ilosci z³ota (zapis normalny) lub ff,ff,ff,ff - iloœæ z³ota do odebrania (maksymalna iloœæ z³ota, któr¹ mo¿na daæ/odebraæ to 32767) -//1 bajt - których graczy dotyczy zdarzenie (pole bitowe, +1 - pierwszy, +2 - drugi, +4 - trzeci, +8 - czwarty, +16 - pi¹ty, +32 - szósty, +64 - siódmy, +128 - ósmy) -//1 bajt - czy zdarzenie odnosi siê do graczy - ludzi (00 - nie, 01 - tak) -//1 bajt - czy zdarzenie odnosi siê do graczy komputerowych (00 - nie, 01 - tak) -//2 bajty - opóŸnienie pierwszego wyst¹pienia (w dniach, zapis normalny, maks 671) -//1 bajt - co ile dni wystêpuje zdarzenie (maks 28, 00 oznacza zdarzenie jednorazowe) -//17 bajtów zerowych }; -struct TerrainTile +struct DLL_EXPORT TerrainTile { EterrainType tertype; // type of terrain unsigned char terview; // look of terrain @@ -52,24 +262,20 @@ struct TerrainTile unsigned char rivDir; // direction of Eriver Eroad malle; // type of Eroad (0 if there is no Eriver) unsigned char roadDir; // direction of Eroad - unsigned char siodmyTajemniczyBajt; // mysterius byte // jak bedzie waidomo co to, to sie nazwie inaczej + unsigned char siodmyTajemniczyBajt; //bitfield, info whether this tile is coastal and how to rotate tile graphics + + bool visitable; //false = not visitable; true = visitable + bool blocked; //false = free; true = blocked; + + std::vector visitableObjects; //pointers to objects hero can visit while being on this tile + std::vector blockingObjects; //pointers to objects that are blocking this tile }; -struct DefInfo //information from def declaration -{ - std::string name; - int bytes [42]; - //CSemiDefHandler * handler; - CDefHandler * handler; - int printPriority; - bool isOnDefList; - bool isVisitable(); -}; -struct SheroName //name of starting hero +struct DLL_EXPORT SheroName //name of starting hero { int heroID; std::string heroName; }; -struct PlayerInfo +struct DLL_EXPORT PlayerInfo { int p7, p8, p9; bool canHumanPlay; @@ -86,72 +292,66 @@ struct PlayerInfo int team; bool generateHero; }; -struct LossCondition +struct DLL_EXPORT LossCondition { ElossCon typeOfLossCon; int3 castlePos; int3 heroPos; int timeLimit; // in days }; -struct CspecificVictoryConidtions +struct DLL_EXPORT CspecificVictoryConidtions { bool allowNormalVictory; bool appliesToAI; }; -struct VicCon0 : public CspecificVictoryConidtions //acquire artifact +struct DLL_EXPORT VicCon0 : public CspecificVictoryConidtions //acquire artifact { int ArtifactID; }; -struct VicCon1 : public CspecificVictoryConidtions //accumulate creatures +struct DLL_EXPORT VicCon1 : public CspecificVictoryConidtions //accumulate creatures { int monsterID; int neededQuantity; }; -struct VicCon2 : public CspecificVictoryConidtions // accumulate resources +struct DLL_EXPORT VicCon2 : public CspecificVictoryConidtions // accumulate resources { int resourceID; int neededQuantity; }; -struct VicCon3 : public CspecificVictoryConidtions // upgrade specific town +struct DLL_EXPORT VicCon3 : public CspecificVictoryConidtions // upgrade specific town { int3 posOfCity; int councilNeededLevel; //0 - town; 1 - city; 2 - capitol int fortNeededLevel;// 0 - fort; 1 - citadel; 2 - castle }; -struct VicCon4 : public CspecificVictoryConidtions // build grail structure +struct DLL_EXPORT VicCon4 : public CspecificVictoryConidtions // build grail structure { bool anyLocation; int3 whereBuildGrail; }; -struct VicCon5 : public CspecificVictoryConidtions // defeat a specific hero +struct DLL_EXPORT VicCon5 : public CspecificVictoryConidtions // defeat a specific hero { int3 locationOfHero; }; -struct VicCon6 : public CspecificVictoryConidtions // capture a specific town +struct DLL_EXPORT VicCon6 : public CspecificVictoryConidtions // capture a specific town { int3 locationOfTown; }; -struct VicCon7 : public CspecificVictoryConidtions // defeat a specific monster +struct DLL_EXPORT VicCon7 : public CspecificVictoryConidtions // defeat a specific monster { int3 locationOfMonster; }; -/*struct VicCon8 : public CspecificVictoryConidtions // flag all creature dwellings -{ -}; -struct VicCon9 : public CspecificVictoryConidtions // flag all mines -{ -};*/ -struct VicCona : public CspecificVictoryConidtions //transport specific artifact +struct DLL_EXPORT VicCona : public CspecificVictoryConidtions //transport specific artifact { int artifactID; int3 destinationPlace; }; -struct Rumor +struct DLL_EXPORT Rumor { std::string name, text; }; -struct DisposedHero +struct DLL_EXPORT DisposedHero { int ID; int portrait; //0xFF - default @@ -159,7 +359,7 @@ struct DisposedHero bool players[8]; //who can hire this hero }; -class CMapEvent +class DLL_EXPORT CMapEvent { public: std::string name, message; @@ -170,32 +370,7 @@ public: int firstOccurence; int nextOccurence; //after nextOccurance day event will occure; if it it 0, event occures only one time; }; - -struct Mapa -{ - Eformat version; // version of map Eformat - int twoLevel; // if map has underground level - int difficulty; // 0 easy - 4 impossible - int levelLimit; - bool areAnyPLayers; // if there are any playable players on map - std::string name; //name of map - std::string description; //and description - int height, width; - TerrainTile** terrain; - TerrainTile** undergroungTerrain; // used only if there is underground level - std::vector rumors; - std::vector disposedHeroes; - std::vector predefinedHeroes; - std::vector defy; // list of .def files - PlayerInfo players[8]; // info about players - std::vector teams; // teams[i] = team of player no i - LossCondition lossCondition; - EvictoryConditions victoryCondition; //victory conditions - CspecificVictoryConidtions * vicConDetails; // used only if vistory conditions aren't standard - int howManyTeams; - std::vector events; -}; -class CMapHeader +class DLL_EXPORT CMapHeader { public: Eformat version; // version of map Eformat @@ -214,7 +389,7 @@ public: int howManyTeams; CMapHeader(unsigned char *map); //an argument is a reference to string described a map (unpacked) }; -class CMapInfo : public CMapHeader +class DLL_EXPORT CMapInfo : public CMapHeader { public: std::string filename; @@ -231,7 +406,7 @@ public: }; -class mapSorter +class DLL_EXPORT mapSorter { public: ESortBy sortBy; @@ -276,4 +451,41 @@ public: }; mapSorter(ESortBy es):sortBy(es){}; }; +struct DLL_EXPORT Mapa +{ + Eformat version; // version of map Eformat + ui32 checksum; + int twoLevel; // if map has underground level + int difficulty; // 0 easy - 4 impossible + int levelLimit; + bool areAnyPLayers; // if there are any playable players on map + std::string name; //name of map + std::string description; //and description + int height, width; + TerrainTile*** terrain; + std::vector rumors; + std::vector disposedHeroes; + std::vector predefinedHeroes; + std::vector defy; // list of .def files with definitions from .h3m (may be custom) + std::set defs; // other defInfos - for randomized objects, objects added or modified by scripts + PlayerInfo players[8]; // info about players + std::vector teams; // teams[i] = team of player no i + LossCondition lossCondition; + EvictoryConditions victoryCondition; //victory conditions + CspecificVictoryConidtions * vicConDetails; // used only if vistory conditions aren't standard + int howManyTeams; + std::vector allowedSpell; //allowedSpell[spell_ID] - if the spell is allowed + std::vector allowedArtifact; //allowedArtifact[artifact_ID] - if the artifact is allowed + std::vector allowedAbilities; //allowedAbilities[ability_ID] - if the ability is allowed + std::vector allowedHeroes; //allowedHeroes[hero_ID] - if the hero is allowed + std::vector events; + + std::vector objects; + std::vector heroes; + std::vector towns; + + void initFromBytes(unsigned char * bufor); //creates map from decompressed .h3m data + Mapa(std::string filename); //creates map structure from .h3m file + CGHeroInstance * getHero(int ID, int mode=0); +}; #endif //MAPD_H diff --git a/mapHandler.cpp b/mapHandler.cpp index 0c79f51e4..f23d428b9 100644 --- a/mapHandler.cpp +++ b/mapHandler.cpp @@ -1,290 +1,101 @@ #include "stdafx.h" #include "mapHandler.h" -#include "hch/CSemiDefHandler.h" -#include "SDL_rotozoom.h" #include "SDL_Extensions.h" #include "CGameInfo.h" -#include "stdlib.h" +#include #include "hch/CLodHandler.h" #include "hch/CDefObjInfoHandler.h" #include #include "CGameState.h" #include "CLua.h" -#include "hch/CCastleHandler.h" #include "hch/CHeroHandler.h" #include "hch/CTownHandler.h" +#include "client/Graphics.h" #include #include +#include "hch/CObjectHandler.h" +#include "map.h" +#include "hch/CDefHandler.h" extern SDL_Surface * screen; - +std::string 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(); +} class OCM_HLP { public: - bool operator ()(const std::pair & a, const std::pair & b) + bool operator ()(const std::pair & a, const std::pair & b) { return (*a.first)<(*b.first); } } ocmptwo ; void alphaTransformDef(CGDefInfo * defInfo) -{ +{ SDL_Surface * alphaTransSurf = SDL_CreateRGBSurface(SDL_SWSURFACE, 12, 12, 32, 0x000000ff, 0x0000ff00, 0x00ff0000, 0xff000000); for(int yy=0;yyhandler->ourImages.size();yy++) { defInfo->handler->ourImages[yy].bitmap = CSDL_Ext::alphaTransform(defInfo->handler->ourImages[yy].bitmap); - //SDL_Surface * bufs = CSDL_Ext::secondAlphaTransform(defInfo->handler->ourImages[yy].bitmap, alphaTransSurf); - //SDL_FreeSurface(defInfo->handler->ourImages[yy].bitmap); - //defInfo->handler->ourImages[yy].bitmap = bufs; defInfo->handler->alphaTransformed = true; } SDL_FreeSurface(alphaTransSurf); } -int CMapHandler::pickHero(int owner) -{ - int h; - if(usedHeroes.find(h = CGI->scenarioOps.getIthPlayersSettings(owner).hero)==usedHeroes.end() && h>=0) //we haven't used selected hero - { - usedHeroes.insert(h); - return h; - } - int f = CGI->scenarioOps.getIthPlayersSettings(owner).castle; - int i=0; - do //try to find free hero of our faction - { - i++; - h = CGI->scenarioOps.getIthPlayersSettings(owner).castle*HEROES_PER_TYPE*2+(rand()%(HEROES_PER_TYPE*2));//cgi->scenarioOps.playerInfos[pru].hero = cgi-> - } while((usedHeroes.find(h)!=usedHeroes.end()) && i<175); - if(i>174) //probably no free heroes - there's no point in further search, we'll take first free - { - for(int j=0; j CMapHandler::pickObject(CGObjectInstance *obj) -{ - switch(obj->ID) - { - case 65: //random artifact - return std::pair(5,(rand()%136)+7); //tylko sensowny zakres - na poczatku sa katapulty itp, na koncu specjalne i blanki - case 66: //random treasure artifact - return std::pair(5,CGI->arth->treasures[rand()%CGI->arth->treasures.size()]->id); - case 67: //random minor artifact - return std::pair(5,CGI->arth->minors[rand()%CGI->arth->minors.size()]->id); - case 68: //random major artifact - return std::pair(5,CGI->arth->majors[rand()%CGI->arth->majors.size()]->id); - case 69: //random relic artifact - return std::pair(5,CGI->arth->relics[rand()%CGI->arth->relics.size()]->id); - case 70: //random hero - { - return std::pair(34,pickHero(obj->tempOwner)); - } - case 71: //random monster - return std::pair(54,rand()%(CGI->creh->creatures.size())); - case 72: //random monster lvl1 - return std::pair(54,CGI->creh->levelCreatures[1][rand()%CGI->creh->levelCreatures[1].size()]->idNumber); - case 73: //random monster lvl2 - return std::pair(54,CGI->creh->levelCreatures[2][rand()%CGI->creh->levelCreatures[2].size()]->idNumber); - case 74: //random monster lvl3 - return std::pair(54,CGI->creh->levelCreatures[3][rand()%CGI->creh->levelCreatures[3].size()]->idNumber); - case 75: //random monster lvl4 - return std::pair(54,CGI->creh->levelCreatures[4][rand()%CGI->creh->levelCreatures[4].size()]->idNumber); - case 76: //random resource - return std::pair(79,rand()%7); //now it's OH3 style, use %8 for mithril - case 77: //random town - { - int align = ((CCastleObjInfo*)obj->info)->alignment, - f; - if(align>PLAYER_LIMIT-1)//same as owner / random - { - if(obj->tempOwner > PLAYER_LIMIT-1) - f = -1; //random - else - f = CGI->scenarioOps.getIthPlayersSettings(obj->tempOwner).castle; - } - else - { - f = CGI->scenarioOps.getIthPlayersSettings(align).castle; - } - if(f<0) f = rand()%CGI->townh->towns.size(); - return std::pair(98,f); - } - case 162: //random monster lvl5 - return std::pair(54,CGI->creh->levelCreatures[5][rand()%CGI->creh->levelCreatures[5].size()]->idNumber); - case 163: //random monster lvl6 - return std::pair(54,CGI->creh->levelCreatures[6][rand()%CGI->creh->levelCreatures[6].size()]->idNumber); - case 164: //random monster lvl7 - return std::pair(54,CGI->creh->levelCreatures[7][rand()%CGI->creh->levelCreatures[7].size()]->idNumber); - case 216: //random dwelling - { - int faction = rand()%F_NUMBER; - CCreGen2ObjInfo* info =(CCreGen2ObjInfo*)obj->info; - if (info->asCastle) - { - for(int i=0;iobjh->objInstances.size();i++) - { - if(CGI->objh->objInstances[i]->ID==77 && dynamic_cast(CGI->objh->objInstances[i])->identifier == info->identifier) - { - randomizeObject(CGI->objh->objInstances[i]); //we have to randomize the castle first - faction = CGI->objh->objInstances[i]->subID; - break; - } - else if(CGI->objh->objInstances[i]->ID==98 && dynamic_cast(CGI->objh->objInstances[i])->identifier == info->identifier) - { - faction = CGI->objh->objInstances[i]->subID; - break; - } - } - } - else - { - while((!(info->castles[0]&(1<7) && (info->castles[1]&(1<<(faction-8)))) - break; - faction = rand()%F_NUMBER; - } - } - int level = ((info->maxLevel-info->minLevel) ? (rand()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel)); - int cid = CGI->townh->towns[faction].basicCreatures[level]; - for(int i=0;iobjh->cregens.size();i++) - if(CGI->objh->cregens[i]==cid) - return std::pair(17,i); - std::cout << "Cannot find a dwelling for creature "<(17,0); - } - case 217: - { - int faction = rand()%F_NUMBER; - CCreGenObjInfo* info =(CCreGenObjInfo*)obj->info; - if (info->asCastle) - { - for(int i=0;iobjh->objInstances.size();i++) - { - if(CGI->objh->objInstances[i]->ID==77 && dynamic_cast(CGI->objh->objInstances[i])->identifier == info->identifier) - { - randomizeObject(CGI->objh->objInstances[i]); //we have to randomize the castle first - faction = CGI->objh->objInstances[i]->subID; - break; - } - else if(CGI->objh->objInstances[i]->ID==98 && dynamic_cast(CGI->objh->objInstances[i])->identifier == info->identifier) - { - faction = CGI->objh->objInstances[i]->subID; - break; - } - } - } - else - { - while((!(info->castles[0]&(1<7) && (info->castles[1]&(1<<(faction-8)))) - break; - faction = rand()%F_NUMBER; - } - } - int cid = CGI->townh->towns[faction].basicCreatures[obj->subID]; - for(int i=0;iobjh->cregens.size();i++) - if(CGI->objh->cregens[i]==cid) - return std::pair(17,i); - std::cout << "Cannot find a dwelling for creature "<(17,0); - } - case 218: - { - CCreGen3ObjInfo* info =(CCreGen3ObjInfo*)obj->info; - int level = ((info->maxLevel-info->minLevel) ? (rand()%(info->maxLevel-info->minLevel)+info->minLevel) : (info->minLevel)); - int cid = CGI->townh->towns[obj->subID].basicCreatures[level]; - for(int i=0;iobjh->cregens.size();i++) - if(CGI->objh->cregens[i]==cid) - return std::pair(17,i); - std::cout << "Cannot find a dwelling for creature "<(17,0); - } - } - return std::pair(-1,-1); -} -void CMapHandler::randomizeObject(CGObjectInstance *cur) -{ - std::pair ran = pickObject(cur); - if(ran.first<0 || ran.second<0) //this is not a random object, or we couldn't find anything - { - if(cur->ID==98) //town - set def - { - CGTownInstance *t = dynamic_cast(cur); - if(t->hasCapitol()) - t->defInfo = capitols[t->subID]; - else if(t->hasFort()) - t->defInfo = CGI->dobjinfo->castles[t->subID]; - else - t->defInfo = villages[t->subID]; - if(!t->defInfo->handler) - { - t->defInfo->handler = CGI->spriteh->giveDef(t->defInfo->name); - alphaTransformDef(t->defInfo); - } - } - return; - } - else if(ran.first==34)//special code for hero - { - CGHeroInstance *h = dynamic_cast(cur); - if(!h) {std::cout<<"Wrong random hero at "<pos<ID = ran.first; - h->portrait = cur->subID = ran.second; - h->type = CGI->heroh->heroes[ran.second]; - CGI->heroh->heroInstances.push_back(h); - CGI->objh->objInstances.erase(std::find(CGI->objh->objInstances.begin(),CGI->objh->objInstances.end(),h)); - return; //TODO: maybe we should do something with definfo? - } - else if(ran.first==98)//special code for town - { - CGTownInstance *t = dynamic_cast(cur); - if(!t) {std::cout<<"Wrong random town at "<pos<ID = ran.first; - cur->subID = ran.second; - t->town = &CGI->townh->towns[ran.second]; - if(t->hasCapitol()) - t->defInfo = capitols[t->subID]; - else if(t->hasFort()) - t->defInfo = CGI->dobjinfo->castles[t->subID]; - else - t->defInfo = villages[t->subID]; - if(!t->defInfo->handler) - { - t->defInfo->handler = CGI->spriteh->giveDef(t->defInfo->name); - alphaTransformDef(t->defInfo); - } - //CGI->townh->townInstances.push_back(t); - return; - } - //we have to replace normal random object - cur->ID = ran.first; - cur->subID = ran.second; - cur->defInfo = CGI->dobjinfo->gobjs[ran.first][ran.second]; - if(!cur->defInfo){std::cout<<"Missing def declaration for "<ID<<" "<subID<defInfo->handler) //if we have to load def - { - cur->defInfo->handler = CGI->spriteh->giveDef(cur->defInfo->name); - alphaTransformDef(cur->defInfo); - } - -} -void CMapHandler::randomizeObjects() -{ - CGObjectInstance * cur; - for(int no=0; noobjh->objInstances.size(); ++no) - { - randomizeObject(CGI->objh->objInstances[no]); - if(CGI->objh->objInstances[no]->ID==26) - CGI->objh->objInstances[no]->defInfo->handler=NULL; - } -} void CMapHandler::prepareFOWDefs() { - fullHide = CGameInfo::mainObj->spriteh->giveDef("TSHRC.DEF"); - partialHide = CGameInfo::mainObj->spriteh->giveDef("TSHRE.DEF"); + fullHide = CDefHandler::giveDef("TSHRC.DEF"); + partialHide = CDefHandler::giveDef("TSHRE.DEF"); //adding necessary rotations Cimage nw = partialHide->ourImages[22]; nw.bitmap = CSDL_Ext::rotate01(nw.bitmap); @@ -329,64 +140,56 @@ void CMapHandler::prepareFOWDefs() { CSDL_Ext::alphaTransform(partialHide->ourImages[i].bitmap); } - //visibility.resize(reader->map.width+2*Woff); - //for(int gg=0; ggmap.width+2*Woff; ++gg) + //visibility.resize(map->width+2*Woff); + //for(int gg=0; ggwidth+2*Woff; ++gg) //{ - // visibility[gg].resize(reader->map.height+2*Hoff); - // for(int jj=0; jjmap.height+2*Hoff; ++jj) + // visibility[gg].resize(map->height+2*Hoff); + // for(int jj=0; jjheight+2*Hoff; ++jj) // visibility[gg][jj] = true; //} - visibility.resize(CGI->ac->map.width, Woff); - for (int i=0-Woff;iac->map.height,Hoff); - } - for (int i=0-Woff; iac->map.height+Hoff; ++j) - { - visibility[i][j].resize(CGI->ac->map.twoLevel+1,0); - for(int k=0; kac->map.twoLevel+1; ++k) - visibility[i][j][k]=true; - } - } + //visibility.resize(CGI->mh->map->width, Woff); + //for (int i=0-Woff;imh->map->height,Hoff); + //} + //for (int i=0-Woff; imh->map->height+Hoff; ++j) + // { + // visibility[i][j].resize(CGI->mh->map->twoLevel+1,0); + // for(int k=0; kmh->map->twoLevel+1; ++k) + // visibility[i][j][k]=true; + // } + //} - hideBitmap.resize(CGI->ac->map.width, Woff); - for (int i=0-Woff;imh->map->width); + for (int i=0;iac->map.height,Hoff); + hideBitmap[i].resize(CGI->mh->map->height); } - for (int i=0-Woff; iac->map.height+Hoff; ++j) + for (int j=0; jmh->map->height; ++j) { - hideBitmap[i][j].resize(CGI->ac->map.twoLevel+1,0); - for(int k=0; kac->map.twoLevel+1; ++k) + hideBitmap[i][j].resize(CGI->mh->map->twoLevel+1); + for(int k=0; kmh->map->twoLevel+1; ++k) hideBitmap[i][j][k] = rand()%fullHide->ourImages.size(); } } - - //visibility[6][7][1] = false; - //visibility[7][7][1] = false; - //visibility[6][8][1] = false; - //visibility[6][6][1] = false; - //visibility[5][8][1] = false; - //visibility[7][6][1] = false; - //visibility[6][9][1] = false; } void CMapHandler::roadsRiverTerrainInit() { //initializing road's and river's DefHandlers - roadDefs.push_back(CGameInfo::mainObj->spriteh->giveDef("dirtrd.def")); - roadDefs.push_back(CGameInfo::mainObj->spriteh->giveDef("gravrd.def")); - roadDefs.push_back(CGameInfo::mainObj->spriteh->giveDef("cobbrd.def")); - staticRiverDefs.push_back(CGameInfo::mainObj->spriteh->giveDef("clrrvr.def")); - staticRiverDefs.push_back(CGameInfo::mainObj->spriteh->giveDef("icyrvr.def")); - staticRiverDefs.push_back(CGameInfo::mainObj->spriteh->giveDef("mudrvr.def")); - staticRiverDefs.push_back(CGameInfo::mainObj->spriteh->giveDef("lavrvr.def")); + roadDefs.push_back(CDefHandler::giveDef("dirtrd.def")); + roadDefs.push_back(CDefHandler::giveDef("gravrd.def")); + roadDefs.push_back(CDefHandler::giveDef("cobbrd.def")); + staticRiverDefs.push_back(CDefHandler::giveDef("clrrvr.def")); + staticRiverDefs.push_back(CDefHandler::giveDef("icyrvr.def")); + staticRiverDefs.push_back(CDefHandler::giveDef("mudrvr.def")); + staticRiverDefs.push_back(CDefHandler::giveDef("lavrvr.def")); for(int g=0; gourImages.size(); ++h) @@ -402,62 +205,45 @@ void CMapHandler::roadsRiverTerrainInit() } } - //roadBitmaps = new SDL_Surface** [reader->map.width+2*Woff]; - //for (int ii=0;iimap.width+2*Woff;ii++) - // roadBitmaps[ii] = new SDL_Surface*[reader->map.height+2*Hoff]; // allocate memory - sizes.x = CGI->ac->map.width; - sizes.y = CGI->ac->map.height; - sizes.z = CGI->ac->map.twoLevel+1; - ttiles.resize(CGI->ac->map.width,Woff); + sizes.x = CGI->mh->map->width; + sizes.y = CGI->mh->map->height; + sizes.z = CGI->mh->map->twoLevel+1; + ttiles.resize(CGI->mh->map->width,Woff); for (int i=0-Woff;iac->map.height,Hoff); + ttiles[i].resize(CGI->mh->map->height,Hoff); } for (int i=0-Woff;iac->map.height+Hoff;j++) - ttiles[i][j].resize(CGI->ac->map.twoLevel+1,0); + for (int j=0-Hoff;jmh->map->height+Hoff;j++) + ttiles[i][j].resize(CGI->mh->map->twoLevel+1,0); } - for (int i=0; imap.width; i++) //jest po szerokoœci + for (int i=0; iwidth; i++) //jest po szerokoœci { - for (int j=0; jmap.height;j++) //po wysokoœci + for (int j=0; jheight;j++) //po wysokoœci { - for (int k=0; k<=reader->map.twoLevel; ++k) + for (int k=0; k<=map->twoLevel; ++k) { - TerrainTile** pomm = reader->map.terrain; ; - if (k==0) - pomm = reader->map.terrain; - else - pomm = reader->map.undergroungTerrain; - if(pomm[i][j].malle) + TerrainTile2 &pom(ttiles[i][j][k]); + pom.pos = int3(i, j, k); + pom.tileInfo = &(map->terrain[i][j][k]); + if(pom.tileInfo->malle) { int cDir; bool rotV, rotH; - if(k==0) - { - int roadpom = reader->map.terrain[i][j].malle-1, - impom = reader->map.terrain[i][j].roadDir; - SDL_Surface *pom1 = roadDefs[roadpom]->ourImages[impom].bitmap; - ttiles[i][j][k].roadbitmap.push_back(pom1); - cDir = reader->map.terrain[i][j].roadDir; - rotH = (reader->map.terrain[i][j].siodmyTajemniczyBajt >> 5) & 1; - rotV = (reader->map.terrain[i][j].siodmyTajemniczyBajt >> 4) & 1; - } - else - { - int pom111 = reader->map.undergroungTerrain[i][j].malle-1, - pom777 = reader->map.undergroungTerrain[i][j].roadDir; - SDL_Surface *pom1 = roadDefs[pom111]->ourImages[pom777].bitmap; - ttiles[i][j][k].roadbitmap.push_back(pom1); - cDir = reader->map.undergroungTerrain[i][j].roadDir; + int roadpom = pom.tileInfo->malle-1, + impom = pom.tileInfo->roadDir; + SDL_Surface *pom1 = roadDefs[roadpom]->ourImages[impom].bitmap; + ttiles[i][j][k].roadbitmap.push_back(pom1); + cDir = pom.tileInfo->roadDir; + + rotH = (pom.tileInfo->siodmyTajemniczyBajt >> 5) & 1; + rotV = (pom.tileInfo->siodmyTajemniczyBajt >> 4) & 1; - rotH = (reader->map.undergroungTerrain[i][j].siodmyTajemniczyBajt >> 5) & 1; - rotV = (reader->map.undergroungTerrain[i][j].siodmyTajemniczyBajt >> 4) & 1; - } if(rotH) { ttiles[i][j][k].roadbitmap[0] = CSDL_Ext::hFlip(ttiles[i][j][k].roadbitmap[0]); @@ -475,65 +261,22 @@ void CMapHandler::roadsRiverTerrainInit() } } - //initializing simple values - for (int i=0; iac->map.width; i++) //jest po szerokoœci + for (int i=0; iwidth; i++) //jest po szerokoœci { - for (int j=0; jac->map.height;j++) //po wysokoœci + for (int j=0; jheight;j++) //po wysokoœci { - for(int k=0; ktwoLevel; ++k) { - ttiles[i][j][k].pos = int3(i, j, k); - ttiles[i][j][k].blocked = false; - ttiles[i][j][k].visitable = false; - if(i<0 || j<0 || i>=CGI->ac->map.width || j>=CGI->ac->map.height) - { - ttiles[i][j][k].blocked = true; - continue; - } - ttiles[i][j][k].terType = (k==0 ? CGI->ac->map.terrain[i][j].tertype : CGI->ac->map.undergroungTerrain[i][j].tertype); - ttiles[i][j][k].malle = (k==0 ? CGI->ac->map.terrain[i][j].malle : CGI->ac->map.undergroungTerrain[i][j].malle); - ttiles[i][j][k].nuine = (k==0 ? CGI->ac->map.terrain[i][j].nuine : CGI->ac->map.undergroungTerrain[i][j].nuine); - ttiles[i][j][k].rivdir = (k==0 ? CGI->ac->map.terrain[i][j].rivDir : CGI->ac->map.undergroungTerrain[i][j].rivDir); - ttiles[i][j][k].roaddir = (k==0 ? CGI->ac->map.terrain[i][j].roadDir : CGI->ac->map.undergroungTerrain[i][j].roadDir); - - } - } - } - //simple values initialized - - for (int i=0; imap.width; i++) //jest po szerokoœci - { - for (int j=0; jmap.height;j++) //po wysokoœci - { - for(int k=0; k<=reader->map.twoLevel; ++k) - { - TerrainTile** pomm = reader->map.terrain; - if(k==0) - { - pomm = reader->map.terrain; - } - else - { - pomm = reader->map.undergroungTerrain; - } - if(pomm[i][j].nuine) + if(map->terrain[i][j][k].nuine) { int cDir; bool rotH, rotV; - if(k==0) - { - ttiles[i][j][k].rivbitmap.push_back(staticRiverDefs[reader->map.terrain[i][j].nuine-1]->ourImages[reader->map.terrain[i][j].rivDir].bitmap); - cDir = reader->map.terrain[i][j].rivDir; - rotH = (reader->map.terrain[i][j].siodmyTajemniczyBajt >> 3) & 1; - rotV = (reader->map.terrain[i][j].siodmyTajemniczyBajt >> 2) & 1; - } - else - { - ttiles[i][j][k].rivbitmap.push_back(staticRiverDefs[reader->map.undergroungTerrain[i][j].nuine-1]->ourImages[reader->map.undergroungTerrain[i][j].rivDir].bitmap); - cDir = reader->map.undergroungTerrain[i][j].rivDir; - rotH = (reader->map.undergroungTerrain[i][j].siodmyTajemniczyBajt >> 3) & 1; - rotV = (reader->map.undergroungTerrain[i][j].siodmyTajemniczyBajt >> 2) & 1; - } + + ttiles[i][j][k].rivbitmap.push_back(staticRiverDefs[map->terrain[i][j][k].nuine-1]->ourImages[map->terrain[i][j][k].rivDir].bitmap); + cDir = map->terrain[i][j][k].rivDir; + rotH = (map->terrain[i][j][k].siodmyTajemniczyBajt >> 3) & 1; + rotV = (map->terrain[i][j][k].siodmyTajemniczyBajt >> 2) & 1; + if(rotH) { ttiles[i][j][k].rivbitmap[0] = CSDL_Ext::hFlip(ttiles[i][j][k].rivbitmap[0]); @@ -553,56 +296,52 @@ void CMapHandler::roadsRiverTerrainInit() } void CMapHandler::borderAndTerrainBitmapInit() { - //terrainBitmap = new SDL_Surface **[reader->map.width+2*Woff]; - //for (int ii=0;iimap.width+2*Woff;ii++) - // terrainBitmap[ii] = new SDL_Surface*[reader->map.height+2*Hoff]; // allocate memory - - CDefHandler * bord = CGameInfo::mainObj->spriteh->giveDef("EDG.DEF"); + CDefHandler * bord = CDefHandler::giveDef("EDG.DEF"); bord->notFreeImgs = true; - for (int i=0-Woff; imap.width+Woff; i++) //jest po szerokoœci + for (int i=0-Woff; iwidth+Woff; i++) //jest po szerokoœci { - for (int j=0-Hoff; jmap.height+Hoff;j++) //po wysokoœci + for (int j=0-Hoff; jheight+Hoff;j++) //po wysokoœci { - for(int k=0; k<=reader->map.twoLevel; ++k) + for(int k=0; k<=map->twoLevel; ++k) { - if(i < 0 || i > (reader->map.width-1) || j < 0 || j > (reader->map.height-1)) + if(i < 0 || i > (map->width-1) || j < 0 || j > (map->height-1)) { if(i==-1 && j==-1) { ttiles[i][j][k].terbitmap.push_back(bord->ourImages[16].bitmap); continue; } - else if(i==-1 && j==(reader->map.height)) + else if(i==-1 && j==(map->height)) { ttiles[i][j][k].terbitmap.push_back(bord->ourImages[19].bitmap); continue; } - else if(i==(reader->map.width) && j==-1) + else if(i==(map->width) && j==-1) { ttiles[i][j][k].terbitmap.push_back(bord->ourImages[17].bitmap); continue; } - else if(i==(reader->map.width) && j==(reader->map.height)) + else if(i==(map->width) && j==(map->height)) { ttiles[i][j][k].terbitmap.push_back(bord->ourImages[18].bitmap); continue; } - else if(j == -1 && i > -1 && i < reader->map.height) + else if(j == -1 && i > -1 && i < map->height) { ttiles[i][j][k].terbitmap.push_back(bord->ourImages[22+rand()%2].bitmap); continue; } - else if(i == -1 && j > -1 && j < reader->map.height) + else if(i == -1 && j > -1 && j < map->height) { ttiles[i][j][k].terbitmap.push_back(bord->ourImages[33+rand()%2].bitmap); continue; } - else if(j == reader->map.height && i >-1 && i < reader->map.width) + else if(j == map->height && i >-1 && i < map->width) { ttiles[i][j][k].terbitmap.push_back(bord->ourImages[29+rand()%2].bitmap); continue; } - else if(i == reader->map.width && j > -1 && j < reader->map.height) + else if(i == map->width && j > -1 && j < map->height) { ttiles[i][j][k].terbitmap.push_back(bord->ourImages[25+rand()%2].bitmap); continue; @@ -613,31 +352,31 @@ void CMapHandler::borderAndTerrainBitmapInit() continue; } } - //TerrainTile zz = reader->map.terrain[i-Woff][j-Hoff]; + //TerrainTile zz = map->terrain[i-Woff][j-Hoff]; std::string name; if (k>0) - name = CSemiDefHandler::nameFromType(reader->map.undergroungTerrain[i][j].tertype); + name = nameFromType(map->terrain[i][j][1].tertype); else - name = CSemiDefHandler::nameFromType(reader->map.terrain[i][j].tertype); - for (unsigned int m=0; mdefs.size(); m++) + name = nameFromType(map->terrain[i][j][0].tertype); + for (unsigned int m=0; mdefs[m]->defName != name) + if (defs[m]->defName != name) continue; else { int ktora; if (k==0) - ktora = reader->map.terrain[i][j].terview; + ktora = map->terrain[i][j][0].terview; else - ktora = reader->map.undergroungTerrain[i][j].terview; - ttiles[i][j][k].terbitmap.push_back(reader->defs[m]->ourImages[ktora].bitmap); + ktora = map->terrain[i][j][1].terview; + ttiles[i][j][k].terbitmap.push_back(defs[m]->ourImages[ktora].bitmap); int zz; if (k==0) - zz = (reader->map.terrain[i][j].siodmyTajemniczyBajt)%4; + zz = (map->terrain[i][j][0].siodmyTajemniczyBajt)%4; else - zz = (reader->map.undergroungTerrain[i][j].siodmyTajemniczyBajt)%4; + zz = (map->terrain[i][j][1].siodmyTajemniczyBajt)%4; switch (zz) { case 1: @@ -673,15 +412,15 @@ void CMapHandler::borderAndTerrainBitmapInit() void CMapHandler::initObjectRects() { //initializing objects / rects - for(int f=0; fobjh->objInstances.size(); ++f) + for(int f=0; fobjects.size(); ++f) { - /*CGI->objh->objInstances[f]->pos.x+=1; - CGI->objh->objInstances[f]->pos.y+=1;*/ - if(!CGI->objh->objInstances[f]->defInfo) + /*map->objects[f]->pos.x+=1; + map->objects[f]->pos.y+=1;*/ + if(!map->objects[f]->defInfo) { continue; } - CDefHandler * curd = CGI->objh->objInstances[f]->defInfo->handler; + CDefHandler * curd = map->objects[f]->defInfo->handler; if(curd) { for(int fx=0; fxourImages[0].bitmap->w>>5; ++fx) //curd->ourImages[0].bitmap->w/32 @@ -693,21 +432,21 @@ void CMapHandler::initObjectRects() cr.h = 32; cr.x = fx<<5; //fx*32 cr.y = fy<<5; //fy*32 - std::pair toAdd = std::make_pair(CGI->objh->objInstances[f],cr); - - if((CGI->objh->objInstances[f]->pos.x + fx - curd->ourImages[0].bitmap->w/32+1)>=0 && (CGI->objh->objInstances[f]->pos.x + fx - curd->ourImages[0].bitmap->w/32+1)objh->objInstances[f]->pos.y + fy - curd->ourImages[0].bitmap->h/32+1)>=0 && (CGI->objh->objInstances[f]->pos.y + fy - curd->ourImages[0].bitmap->h/32+1) toAdd = std::make_pair(map->objects[f],cr); + + if((map->objects[f]->pos.x + fx - curd->ourImages[0].bitmap->w/32+1)>=0 && (map->objects[f]->pos.x + fx - curd->ourImages[0].bitmap->w/32+1)objects[f]->pos.y + fy - curd->ourImages[0].bitmap->h/32+1)>=0 && (map->objects[f]->pos.y + fy - curd->ourImages[0].bitmap->h/32+1)objh->objInstances[f]->pos.x + fx - curd->ourImages[0].bitmap->w/32] - //[CGI->objh->objInstances[f]->pos.y + fy - curd->ourImages[0].bitmap->h/32] - //[CGI->objh->objInstances[f]->pos.z]; - ttiles[CGI->objh->objInstances[f]->pos.x + fx - curd->ourImages[0].bitmap->w/32+1][CGI->objh->objInstances[f]->pos.y + fy - curd->ourImages[0].bitmap->h/32+1][CGI->objh->objInstances[f]->pos.z].objects.push_back(toAdd); + // [map->objects[f]->pos.x + fx - curd->ourImages[0].bitmap->w/32] + //[map->objects[f]->pos.y + fy - curd->ourImages[0].bitmap->h/32] + //[map->objects[f]->pos.z]; + ttiles[map->objects[f]->pos.x + fx - curd->ourImages[0].bitmap->w/32+1][map->objects[f]->pos.y + fy - curd->ourImages[0].bitmap->h/32+1][map->objects[f]->pos.z].objects.push_back(toAdd); } } // for(int fy=0; fyourImages[0].bitmap->h/32; ++fy) } //for(int fx=0; fxourImages[0].bitmap->w/32; ++fx) }//if curd - } // for(int f=0; fobjh->objInstances.size(); ++f) + } // for(int f=0; fobjects.size(); ++f) for(int ix=0; ixobjh->objInstances.size(); ++f) //calculationg blocked / visitable positions + //for(int f=0; fobjects.size(); ++f) //calculationg blocked / visitable positions + //{ + // if(!map->objects[f]->defInfo) + // continue; + // CDefHandler * curd = map->objects[f]->defInfo->handler; + // for(int fx=0; fx<8; ++fx) + // { + // for(int fy=0; fy<6; ++fy) + // { + // int xVal = map->objects[f]->pos.x + fx - 7; + // int yVal = map->objects[f]->pos.y + fy - 5; + // int zVal = map->objects[f]->pos.z; + // if(xVal>=0 && xVal=0 && yValobjects[f]->defInfo->visitMap[fy] >> (7 - fx)) & 1)) + // curt.tileInfo->visitable = true; + // if(!((map->objects[f]->defInfo->blockMap[fy] >> (7 - fx)) & 1)) + // curt.tileInfo->blocked = true; + // } + // } + // } + //} +} +void processDef (CGDefInfo* def) +{ + def->handler=CDefHandler::giveDef(def->name); + def->width = def->handler->ourImages[0].bitmap->w/32; + def->height = def->handler->ourImages[0].bitmap->h/32; + CGDefInfo* pom = CGI->dobjinfo->gobjs[def->id][def->subid]; + if(pom) { - if(!CGI->objh->objInstances[f]->defInfo) - continue; - CDefHandler * curd = CGI->objh->objInstances[f]->defInfo->handler; - for(int fx=0; fx<8; ++fx) + pom->handler = def->handler; + pom->width = pom->handler->ourImages[0].bitmap->w/32; + pom->height = pom->handler->ourImages[0].bitmap->h/32; + } + else + std::cout << "\t\tMinor warning: lacking def info for " << def->id << " " << def->subid <<" " << def->name << std::endl; + if(!def->handler->alphaTransformed) + { + for(int yy=0; yyhandler->ourImages.size(); ++yy) { - for(int fy=0; fy<6; ++fy) - { - int xVal = CGI->objh->objInstances[f]->pos.x + fx - 7; - int yVal = CGI->objh->objInstances[f]->pos.y + fy - 5; - int zVal = CGI->objh->objInstances[f]->pos.z; - if(xVal>=0 && xVal=0 && yValobjh->objInstances[f]->defInfo->visitMap[fy] >> (7 - fx)) & 1)) - curt.visitable = true; - if(!((CGI->objh->objInstances[f]->defInfo->blockMap[fy] >> (7 - fx)) & 1)) - curt.blocked = true; - } - } + def->handler->ourImages[yy].bitmap = CSDL_Ext::alphaTransform(def->handler->ourImages[yy].bitmap); + def->handler->alphaTransformed = true; } } } void CMapHandler::init() { - //loading castles' defs + timeHandler th; + th.getDif(); + loadDefs(); //loading castles' defs + THC std::cout<<"Reading terrain defs: "<>ccc; for(int i=0;idobjinfo->castles[i%ccc]); - ifs >> n->name; - if (!(n->handler = CGI->spriteh->giveDef(n->name))) - std::cout << "Cannot open "<name<scenarioOps.playerInfos.size();i++) - { - if(CGI->scenarioOps.playerInfos[i].castle==-1) { - int f; - do - { - f = rand()%F_NUMBER; - }while(!(reader->map.players[CGI->scenarioOps.playerInfos[i].color].allowedFactions & 1<scenarioOps.playerInfos[i].castle = f; + n = CGI->state->villages[i]; + map->defs.insert(CGI->state->forts[i]); + } + else + n = CGI->state->capitols[i%ccc]; + ifs >> n->name; + map->defs.insert(n); + } + std::cout<<"\tLoading town def info: "<heroes.size();i++) + { + if(!map->heroes[i]->defInfo->handler) + { + map->heroes[i]->defInfo->handler = graphics->flags1[0]; + map->heroes[i]->defInfo->width = map->heroes[i]->defInfo->handler->ourImages[0].bitmap->w/32; + map->heroes[i]->defInfo->height = map->heroes[i]->defInfo->handler->ourImages[0].bitmap->h/32; } } + + std::for_each(map->defy.begin(),map->defy.end(),processDef); //load h3m defs + std::for_each(map->defs.begin(),map->defs.end(),processDef); //and non-h3m defs + THC std::cout<<"\tUnpacking and handling defs: "<map.players[i].heroesNames.size();j++) + for(int j=0; jplayers[i].heroesNames.size();j++) { - usedHeroes.insert(reader->map.players[i].heroesNames[j].heroID); + usedHeroes.insert(map->players[i].heroesNames[j].heroID); } } + std::cout<<"\tChecking used heroes: "<map.defy.size(); ++h) //initializing loaded def handler's info - { - //std::string hlp = reader->map.defy[h]->name; - //std::transform(hlp.begin(), hlp.end(), hlp.begin(), (int(*)(int))toupper); - CGI->mh->loadedDefs.insert(std::make_pair(reader->map.defy[h]->name, reader->map.defy[h]->handler)); - } + for(int h=0; hdefy.size(); ++h) //initializing loaded def handler's info { + CGI->mh->loadedDefs.insert(std::make_pair(map->defy[h]->name, map->defy[h]->handler)); std::cout<<"\tCollecting loaded def's handlers: "<map.players[i].generateHeroAtMainTown && reader->map.players[i].hasMainTown) || (reader->map.players[i].hasMainTown && reader->map.version==RoE)) - { - int3 hpos = reader->map.players[i].posOfMainTown; - hpos.x+=1;// hpos.y+=1; - int j; - for(j=0;jscenarioOps.playerInfos.size();j++) - if(CGI->scenarioOps.playerInfos[j].color==i) - break; - if(j==CGI->scenarioOps.playerInfos.size()) - continue; - int h; //= CGI->scenarioOps.playerInfos[j].hero; - //if(h<0) - h=pickHero(i); - CGHeroInstance * nnn = (CGHeroInstance*)createObject(34,h,hpos,i); - nnn->defInfo->handler = CGI->heroh->flags1[0]; - CGI->heroh->heroInstances.push_back(nnn); - CGI->objh->objInstances.push_back(nnn); - } - } - std::cout<<"\tGiving starting heroes: "<>am; - battleBacks[i].resize(am); - for(int f=0; f>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>battleHeroes[i]; - } } -SDL_Surface * CMapHandler::terrainRect(int x, int y, int dx, int dy, int level, unsigned char anim, PseudoV< PseudoV< PseudoV > > & visibilityMap, bool otherHeroAnim, unsigned char heroAnim, SDL_Surface * extSurf, SDL_Rect * extRect) +SDL_Surface * CMapHandler::terrainRect(int x, int y, int dx, int dy, int level, unsigned char anim, std::vector< std::vector< std::vector > > * visibilityMap, bool otherHeroAnim, unsigned char heroAnim, SDL_Surface * extSurf, SDL_Rect * extRect) { if(!otherHeroAnim) heroAnim = anim; //the same, as it should be @@ -873,7 +587,7 @@ SDL_Surface * CMapHandler::terrainRect(int x, int y, int dx, int dy, int level, su = CSDL_Ext::newSurface(dx*32, dy*32, CSDL_Ext::std32bppSurface); } - if (((dx+x)>((reader->map.width+Woff)) || (dy+y)>((reader->map.height+Hoff))) || ((x<-Woff)||(y<-Hoff) ) ) + if (((dx+x)>((map->width+Woff)) || (dy+y)>((map->height+Hoff))) || ((x<-Woff)||(y<-Hoff) ) ) throw new std::string("terrainRect: out of range"); ////printing terrain for (int bx=0; bx(ttiles[x+bx][y+by][level].objects[h].first)); + const CGHeroInstance * themp = (dynamic_cast(ttiles[x+bx][y+by][level].objects[h].first)); if(themp && themp->moveDir && !themp->isStanding && themp->ID!=62) //last condition - this is not prison { @@ -966,7 +680,7 @@ SDL_Surface * CMapHandler::terrainRect(int x, int y, int dx, int dy, int level, CSDL_Ext::blit8bppAlphaTo24bpp(tb,&pp,su,&sr); pp.y+=imgVal*2-32; sr.y-=16; - SDL_BlitSurface(CGI->heroh->flags4[themp->getOwner()]->ourImages[gg+heroAnim%imgVal+35].bitmap, &pp, su, &sr); + SDL_BlitSurface(graphics->flags4[themp->getOwner()]->ourImages[gg+heroAnim%imgVal+35].bitmap, &pp, su, &sr); } else if(themp && themp->moveDir && themp->isStanding && themp->ID!=62) //last condition - this is not prison) { @@ -995,8 +709,7 @@ SDL_Surface * CMapHandler::terrainRect(int x, int y, int dx, int dy, int level, bufr.h = 64; bufr.w = 96; if(bufr.x-extRect->x>-64) - SDL_BlitSurface(CGI->heroh->flags4[themp->getOwner()]->ourImages[ getHeroFrameNum(themp->moveDir, !themp->isStanding) *8+(heroAnim/4)%imgVal].bitmap, NULL, su, &bufr); - themp->flagPrinted = true; + SDL_BlitSurface(graphics->flags4[themp->getOwner()]->ourImages[ getHeroFrameNum(themp->moveDir, !themp->isStanding) *8+(heroAnim/4)%imgVal].bitmap, NULL, su, &bufr); } } else @@ -1007,7 +720,7 @@ SDL_Surface * CMapHandler::terrainRect(int x, int y, int dx, int dy, int level, //setting appropriate flag color if((ttiles[x+bx][y+by][level].objects[h].first->tempOwner>=0 && ttiles[x+bx][y+by][level].objects[h].first->tempOwner<8) || ttiles[x+bx][y+by][level].objects[h].first->tempOwner==255) CSDL_Ext::setPlayerColor(ttiles[x+bx][y+by][level].objects[h].first->defInfo->handler->ourImages[(anim+phaseShift)%imgVal].bitmap, ttiles[x+bx][y+by][level].objects[h].first->tempOwner); - + CSDL_Ext::blit8bppAlphaTo24bpp(ttiles[x+bx][y+by][level].objects[h].first->defInfo->handler->ourImages[(anim+phaseShift)%imgVal].bitmap,&pp,su,&sr); } } @@ -1024,10 +737,10 @@ SDL_Surface * CMapHandler::terrainRect(int x, int y, int dx, int dy, int level, sr.x=bx*32; sr.h=sr.w=32; validateRectTerr(&sr, extRect); - - if(bx+x>=0 && by+y>=0 && bx+xmh->reader->map.width && by+ymh->reader->map.height && !visibilityMap[bx+x][by+y][level]) + + if(bx+x>=0 && by+y>=0 && bx+xmh->map->width && by+ymh->map->height && !(*visibilityMap)[bx+x][by+y][level]) { - SDL_Surface * hide = getVisBitmap(bx+x, by+y, visibilityMap, level); + SDL_Surface * hide = getVisBitmap(bx+x, by+y, *visibilityMap, level); CSDL_Ext::blit8bppAlphaTo24bpp(hide, &genRect(sr.h, sr.w, 0, 0), su, &sr); } } @@ -1038,7 +751,7 @@ SDL_Surface * CMapHandler::terrainRect(int x, int y, int dx, int dy, int level, { for (int by=0; byreader->map.width+(-1) || by+y>reader->map.height+(-1)) + if(bx+x<0 || by+y<0 || bx+x>map->width+(-1) || by+y>map->height+(-1)) { SDL_Rect sr; sr.y=by*32; @@ -1048,9 +761,9 @@ SDL_Surface * CMapHandler::terrainRect(int x, int y, int dx, int dy, int level, SDL_BlitSurface(ttiles[x+bx][y+by][level].terbitmap[anim%ttiles[x+bx][y+by][level].terbitmap.size()],&genRect(sr.h, sr.w, 0, 0),su,&sr); } - else + else { - if(MARK_BLOCKED_POSITIONS && ttiles[x+bx][y+by][level].blocked) //temporary hiding blocked positions + if(MARK_BLOCKED_POSITIONS && ttiles[x+bx][y+by][level].tileInfo->blocked) //temporary hiding blocked positions { SDL_Rect sr; sr.y=by*32; @@ -1068,7 +781,7 @@ SDL_Surface * CMapHandler::terrainRect(int x, int y, int dx, int dy, int level, SDL_FreeSurface(ns); } - if(MARK_VISITABLE_POSITIONS && ttiles[x+bx][y+by][level].visitable) //temporary hiding visitable positions + if(MARK_VISITABLE_POSITIONS && ttiles[x+bx][y+by][level].tileInfo->visitable) //temporary hiding visitable positions { SDL_Rect sr; sr.y=by*32; @@ -1092,261 +805,261 @@ SDL_Surface * CMapHandler::terrainRect(int x, int y, int dx, int dy, int level, //borders printed return su; } - -SDL_Surface * CMapHandler::terrBitmap(int x, int y) +SDL_Surface * CMapHandler::getVisBitmap(int x, int y, std::vector< std::vector< std::vector > > & visibilityMap, int lvl) { - return ttiles[x+Woff][y+Hoff][0].terbitmap[0]; -} + int size = visibilityMap.size()-1; //is tile visible. arrangement: (like num keyboard) + bool d7 = (x>0 && y>0) ? visibilityMap[x-1][y-1][lvl] : 0, //789 + d8 = (y>0) ? visibilityMap[x][y-1][lvl] : 0, //456 + d9 = (y>0 && x0) ? visibilityMap[x-1][y][lvl] : 0, + d5 = visibilityMap[x][y][lvl], + d6 = (x0 && y > > & visibilityMap, int lvl) -{ - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && !d8 && !d7 && !d3 && !d9 && !d1) { return fullHide->ourImages[hideBitmap[x][y][lvl]].bitmap; //fully hidden } - else if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) + else if(!d2 && !d6 && !d4 && !d8 && !d7 && d3 && !d9 && !d1) { return partialHide->ourImages[22].bitmap; //visible right bottom corner } - else if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) + else if(!d2 && !d6 && !d4 && !d8 && !d7 && !d3 && d9 && !d1) { return partialHide->ourImages[15].bitmap; //visible right top corner } - else if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) + else if(!d2 && !d6 && !d4 && !d8 && !d7 && !d3 && !d9 && d1) { //return CSDL_Ext::rotate01(partialHide->ourImages[22].bitmap); //visible left bottom corner return partialHide->ourImages[34].bitmap; //visible left bottom corner } - else if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) + else if(!d2 && !d6 && !d4 && !d8 && d7 && !d3 && !d9 && !d1) { //return CSDL_Ext::rotate01(partialHide->ourImages[15].bitmap); //visible left top corner return partialHide->ourImages[35].bitmap; } - else if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) + else if(!d2 && !d6 && !d4 && d8 && d7 && !d3 && d9 && !d1) { //return partialHide->ourImages[rand()%2].bitmap; //visible top return partialHide->ourImages[0].bitmap; //visible top } - else if(visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) + else if(d2 && !d6 && !d4 && !d8 && !d7 && d3 && !d9 && d1) { //return partialHide->ourImages[4+rand()%2].bitmap; //visble bottom return partialHide->ourImages[4].bitmap; //visble bottom } - else if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) + else if(!d2 && !d6 && d4 && !d8 && d7 && !d3 && !d9 && d1) { //return CSDL_Ext::rotate01(partialHide->ourImages[2+rand()%2].bitmap); //visible left //return CSDL_Ext::rotate01(partialHide->ourImages[2].bitmap); //visible left return partialHide->ourImages[36].bitmap; } - else if(!visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) + else if(!d2 && d6 && !d4 && !d8 && !d7 && d3 && d9 && !d1) { //return partialHide->ourImages[2+rand()%2].bitmap; //visible right return partialHide->ourImages[2].bitmap; //visible right } - else if(visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl]) + else if(d2 && d6 && !d4 && !d8 && !d7) { //return partialHide->ourImages[12+2*(rand()%2)].bitmap; //visible bottom, right - bottom, right; left top corner hidden return partialHide->ourImages[12].bitmap; //visible bottom, right - bottom, right; left top corner hidden } - else if(!visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) + else if(!d2 && d6 && !d4 && d8 && !d1) { return partialHide->ourImages[13].bitmap; //visible right, right - top; left bottom corner hidden } - else if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl] && !visibilityMap[x+1][y+1][lvl]) + else if(!d2 && !d6 && d4 && d8 && !d3) { //return CSDL_Ext::rotate01(partialHide->ourImages[13].bitmap); //visible top, top - left, left; right bottom corner hidden return partialHide->ourImages[37].bitmap; } - else if(visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x+1][y-1][lvl]) + else if(d2 && !d6 && d4 && !d8 && !d9) { //return CSDL_Ext::rotate01(partialHide->ourImages[12+2*(rand()%2)].bitmap); //visible left, left - bottom, bottom; right top corner hidden //return CSDL_Ext::rotate01(partialHide->ourImages[12].bitmap); //visible left, left - bottom, bottom; right top corner hidden return partialHide->ourImages[38].bitmap; } - else if(visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl]) + else if(d2 && d6 && d4 && d8) { return partialHide->ourImages[10].bitmap; //visible left, right, bottom and top } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && !d8 && !d7 && d3 && d9 && !d1) { return partialHide->ourImages[16].bitmap; //visible right corners } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && !d8 && d7 && !d3 && d9 && !d1) { return partialHide->ourImages[18].bitmap; //visible top corners } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && !d8 && d7 && !d3 && !d9 && d1) { //return CSDL_Ext::rotate01(partialHide->ourImages[16].bitmap); //visible left corners return partialHide->ourImages[39].bitmap; } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && !d8 && !d7 && d3 && !d9 && d1) { //return CSDL_Ext::hFlip(partialHide->ourImages[18].bitmap); //visible bottom corners return partialHide->ourImages[40].bitmap; } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && visibilityMap[x+1][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && !d8 && !d7 && !d3 && d9 && d1) { return partialHide->ourImages[17].bitmap; //visible right - top and bottom - left corners } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && !d8 && d7 && d3 && !d9 && !d1) { //return CSDL_Ext::hFlip(partialHide->ourImages[17].bitmap); //visible top - left and bottom - right corners return partialHide->ourImages[41].bitmap; } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && visibilityMap[x+1][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && !d8 && !d7 && d3 && d9 && d1) { return partialHide->ourImages[19].bitmap; //visible corners without left top } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && !d8 && d7 && d3 && d9 && !d1) { return partialHide->ourImages[20].bitmap; //visible corners without left bottom } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && visibilityMap[x+1][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && !d8 && d7 && !d3 && d9 && d1) { //return CSDL_Ext::rotate01(partialHide->ourImages[20].bitmap); //visible corners without right bottom return partialHide->ourImages[42].bitmap; } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && !d8 && d7 && d3 && !d9 && d1) { //return CSDL_Ext::rotate01(partialHide->ourImages[19].bitmap); //visible corners without right top return partialHide->ourImages[43].bitmap; } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && visibilityMap[x+1][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && !d8 && d7 && d3 && d9 && d1) { return partialHide->ourImages[21].bitmap; //visible all corners only } - if(visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl]) + if(d2 && d6 && d4 && !d8) { return partialHide->ourImages[6].bitmap; //hidden top } - if(visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl]) + if(d2 && !d6 && d4 && d8) { return partialHide->ourImages[7].bitmap; //hidden right } - if(!visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl]) + if(!d2 && d6 && d4 && d8) { return partialHide->ourImages[8].bitmap; //hidden bottom } - if(visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl]) + if(d2 && d6 && !d4 && d8) { //return CSDL_Ext::rotate01(partialHide->ourImages[7].bitmap); //hidden left return partialHide->ourImages[44].bitmap; } - if(!visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl]) + if(!d2 && d6 && d4 && !d8) { return partialHide->ourImages[9].bitmap; //hidden top and bottom } - if(visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl]) + if(d2 && !d6 && !d4 && d8) { return partialHide->ourImages[29].bitmap; //hidden left and right } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && !visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && d8 && d3 && !d1) { return partialHide->ourImages[24].bitmap; //visible top and right bottom corner } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && d8 && !d3 && d1) { //return CSDL_Ext::rotate01(partialHide->ourImages[24].bitmap); //visible top and left bottom corner return partialHide->ourImages[45].bitmap; } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && visibilityMap[x-1][y+1][lvl]) + if(!d2 && !d6 && !d4 && d8 && d3 && d1) { return partialHide->ourImages[33].bitmap; //visible top and bottom corners } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && visibilityMap[x+1][y-1][lvl]) + if(!d2 && !d6 && d4 && !d8 && !d3 && d9) { //return CSDL_Ext::rotate01(partialHide->ourImages[26].bitmap); //visible left and right top corner return partialHide->ourImages[46].bitmap; } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl]) + if(!d2 && !d6 && d4 && !d8 && d3 && !d9) { //return CSDL_Ext::rotate01(partialHide->ourImages[25].bitmap); //visible left and right bottom corner return partialHide->ourImages[47].bitmap; } - if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && visibilityMap[x+1][y-1][lvl]) + if(!d2 && !d6 && d4 && !d8 && d3 && d9) { return partialHide->ourImages[32].bitmap; //visible left and right corners } - if(visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y-1][lvl]) + if(d2 && !d6 && !d4 && !d8 && d7 && !d9) { //return CSDL_Ext::rotate01(partialHide->ourImages[30].bitmap); //visible bottom and left top corner return partialHide->ourImages[48].bitmap; } - if(visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && visibilityMap[x+1][y-1][lvl]) + if(d2 && !d6 && !d4 && !d8 && !d7 && d9) { return partialHide->ourImages[30].bitmap; //visible bottom and right top corner } - if(visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && visibilityMap[x+1][y-1][lvl]) + if(d2 && !d6 && !d4 && !d8 && d7 && d9) { return partialHide->ourImages[31].bitmap; //visible bottom and top corners } - if(!visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) + if(!d2 && d6 && !d4 && !d8 && !d7 && d1) { return partialHide->ourImages[25].bitmap; //visible right and left bottom corner } - if(!visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) + if(!d2 && d6 && !d4 && !d8 && d7 && !d1) { return partialHide->ourImages[26].bitmap; //visible right and left top corner } - if(!visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) + if(!d2 && d6 && !d4 && !d8 && d7 && d1) { //return CSDL_Ext::rotate01(partialHide->ourImages[32].bitmap); //visible right and left cornres return partialHide->ourImages[49].bitmap; } - if(visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl]) + if(d2 && d6 && !d4 && !d8 && d7) { return partialHide->ourImages[28].bitmap; //visible bottom, right - bottom, right; left top corner visible } - else if(!visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) + else if(!d2 && d6 && !d4 && d8 && d1) { return partialHide->ourImages[27].bitmap; //visible right, right - top; left bottom corner visible } - else if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl] && visibilityMap[x+1][y+1][lvl]) + else if(!d2 && !d6 && d4 && d8 && d3) { //return CSDL_Ext::rotate01(partialHide->ourImages[27].bitmap); //visible top, top - left, left; right bottom corner visible return partialHide->ourImages[50].bitmap; } - else if(visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x+1][y-1][lvl]) + else if(d2 && !d6 && d4 && !d8 && d9) { //return CSDL_Ext::rotate01(partialHide->ourImages[28].bitmap); //visible left, left - bottom, bottom; right top corner visible return partialHide->ourImages[51].bitmap; } //newly added - else if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) //visible t and tr + else if(!d2 && !d6 && !d4 && d8 && !d7 && !d3 && d9 && !d1) //visible t and tr { return partialHide->ourImages[0].bitmap; } - else if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) //visible t and tl + else if(!d2 && !d6 && !d4 && d8 && d7 && !d3 && !d9 && !d1) //visible t and tl { return partialHide->ourImages[1].bitmap; } - else if(visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) //visible b and br + else if(d2 && !d6 && !d4 && !d8 && !d7 && d3 && !d9 && !d1) //visible b and br { return partialHide->ourImages[4].bitmap; } - else if(visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) //visible b and bl + else if(d2 && !d6 && !d4 && !d8 && !d7 && !d3 && !d9 && d1) //visible b and bl { return partialHide->ourImages[5].bitmap; } - else if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) //visible l and tl + else if(!d2 && !d6 && d4 && !d8 && d7 && !d3 && !d9 && !d1) //visible l and tl { return partialHide->ourImages[36].bitmap; } - else if(!visibilityMap[x][y+1][lvl] && !visibilityMap[x+1][y][lvl] && visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && visibilityMap[x-1][y+1][lvl]) //visible l and bl + else if(!d2 && !d6 && d4 && !d8 && !d7 && !d3 && !d9 && d1) //visible l and bl { return partialHide->ourImages[36].bitmap; } - else if(!visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && !visibilityMap[x+1][y+1][lvl] && visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) //visible r and tr + else if(!d2 && d6 && !d4 && !d8 && !d7 && !d3 && d9 && !d1) //visible r and tr { return partialHide->ourImages[2].bitmap; } - else if(!visibilityMap[x][y+1][lvl] && visibilityMap[x+1][y][lvl] && !visibilityMap[x-1][y][lvl] && !visibilityMap[x][y-1][lvl] && !visibilityMap[x-1][y-1][lvl] && visibilityMap[x+1][y+1][lvl] && !visibilityMap[x+1][y-1][lvl] && !visibilityMap[x-1][y+1][lvl]) //visible r and br + else if(!d2 && d6 && !d4 && !d8 && !d7 && d3 && !d9 && !d1) //visible r and br { return partialHide->ourImages[3].bitmap; } @@ -1356,14 +1069,14 @@ SDL_Surface * CMapHandler::getVisBitmap(int x, int y, PseudoV< PseudoV< PseudoV< int CMapHandler::getCost(int3 &a, int3 &b, const CGHeroInstance *hero) { int ret=-1; - if(a.x>=CGI->mh->reader->map.width && a.y>=CGI->mh->reader->map.height) - ret = hero->type->heroClass->terrCosts[CGI->mh->ttiles[CGI->mh->reader->map.width-1][CGI->mh->reader->map.width-1][a.z].malle]; - else if(a.x>=CGI->mh->reader->map.width && a.ymh->reader->map.height) - ret = hero->type->heroClass->terrCosts[CGI->mh->ttiles[CGI->mh->reader->map.width-1][a.y][a.z].malle]; - else if(a.xmh->reader->map.width && a.y>=CGI->mh->reader->map.height) - ret = hero->type->heroClass->terrCosts[CGI->mh->ttiles[a.x][CGI->mh->reader->map.width-1][a.z].malle]; + if(a.x>=CGI->mh->map->width && a.y>=CGI->mh->map->height) + ret = hero->type->heroClass->terrCosts[CGI->mh->ttiles[CGI->mh->map->width-1][CGI->mh->map->width-1][a.z].tileInfo->malle]; + else if(a.x>=CGI->mh->map->width && a.ymh->map->height) + ret = hero->type->heroClass->terrCosts[CGI->mh->ttiles[CGI->mh->map->width-1][a.y][a.z].tileInfo->malle]; + else if(a.xmh->map->width && a.y>=CGI->mh->map->height) + ret = hero->type->heroClass->terrCosts[CGI->mh->ttiles[a.x][CGI->mh->map->width-1][a.z].tileInfo->malle]; else - ret = hero->type->heroClass->terrCosts[CGI->mh->ttiles[a.x][a.y][a.z].malle]; + ret = hero->type->heroClass->terrCosts[CGI->mh->ttiles[a.x][a.y][a.z].tileInfo->malle]; if(!(a.x==b.x || a.y==b.y)) ret*=1.41421; @@ -1371,103 +1084,17 @@ int CMapHandler::getCost(int3 &a, int3 &b, const CGHeroInstance *hero) return ret; } -std::vector < std::string > CMapHandler::getObjDescriptions(int3 pos) -{ - std::vector < std::pair > objs = ttiles[pos.x][pos.y][pos.z].objects; - std::vector ret; - for(int g=0; gpos.y-pos.y)) >= 0 && (5-(objs[g].first->pos.y-pos.y)) < 6 && (objs[g].first->pos.x-pos.x) >= 0 && (objs[g].first->pos.x-pos.x)<7 && objs[g].first->defInfo && - (((objs[g].first->defInfo->blockMap[5-(objs[g].first->pos.y-pos.y)])>>((objs[g].first->pos.x-pos.x)))&1)==0 - ) //checking position blocking - { - //unsigned char * blm = objs[g].first->defInfo->blockMap; - if (objs[g].first->state) - ret.push_back(objs[g].first->state->hoverText(objs[g].first)); - else - ret.push_back(CGI->objh->objects[objs[g].first->ID].name); - } - } - return ret; -} - -std::vector < CGObjectInstance * > CMapHandler::getVisitableObjs(int3 pos) -{ - std::vector < CGObjectInstance * > ret; - for(int h=0; hvisitableAt(- curi->pos.x + pos.x + curi->getWidth() - 1, -curi->pos.y + pos.y + curi->getHeight() - 1)) - ret.push_back(curi); - } - return ret; -} - -CGObjectInstance * CMapHandler::createObject(int id, int subid, int3 pos, int owner) -{ - CGObjectInstance * nobj; - switch(id) - { - case 34: //hero - { - CGHeroInstance * nobj; - nobj = new CGHeroInstance(); - nobj->pos = pos; - nobj->tempOwner = owner; - nobj->defInfo = new CGDefInfo(); - nobj->defInfo->id = 34; - nobj->defInfo->subid = subid; - nobj->defInfo->printPriority = 0; - nobj->type = CGI->heroh->heroes[subid]; - for(int i=0;i<6;i++) - { - nobj->defInfo->blockMap[i]=255; - nobj->defInfo->visitMap[i]=0; - } - nobj->ID = id; - nobj->subID = subid; - nobj->defInfo->handler=NULL; - nobj->defInfo->blockMap[5] = 253; - nobj->defInfo->visitMap[5] = 2; - nobj->artifWorn.resize(20); - nobj->artifacts.resize(20); - nobj->artifWorn[16] = &CGI->arth->artifacts[3]; - nobj->portrait = subid; - nobj->primSkills.resize(4); - nobj->primSkills[0] = nobj->type->heroClass->initialAttack; - nobj->primSkills[1] = nobj->type->heroClass->initialDefence; - nobj->primSkills[2] = nobj->type->heroClass->initialPower; - nobj->primSkills[3] = nobj->type->heroClass->initialKnowledge; - nobj->mana = 10 * nobj->primSkills[3]; - return nobj; - } - case 98: //town - nobj = new CGTownInstance; - break; - default: //rest of objects - nobj = new CGObjectInstance; - nobj->defInfo = CGI->dobjinfo->gobjs[id][subid]; - break; - } - nobj->ID = id; - nobj->subID = subid; - if(!nobj->defInfo) - std::cout <<"No def declaration for " <pos = pos; - //nobj->state = NULL;//new CLuaObjectScript(); - nobj->tempOwner = owner; - nobj->info = NULL; - nobj->defInfo->id = id; - nobj->defInfo->subid = subid; - - //assigning defhandler - if(nobj->ID==34 || nobj->ID==98) - return nobj; - nobj->defInfo = CGI->dobjinfo->gobjs[id][subid]; - if(!nobj->defInfo->handler) - nobj->defInfo->handler = CGI->spriteh->giveDef(nobj->defInfo->name); - return nobj; -} +//std::vector < CGObjectInstance * > CMapHandler::getVisitableObjs(int3 pos) +//{ +// std::vector < CGObjectInstance * > ret; +// for(int h=0; hvisitableAt(- curi->pos.x + pos.x + curi->getWidth() - 1, -curi->pos.y + pos.y + curi->getHeight() - 1)) +// ret.push_back(curi); +// } +// return ret; +//} std::string CMapHandler::getDefName(int id, int subid) { @@ -1520,7 +1147,7 @@ bool CMapHandler::hideObject(CGObjectInstance *obj) { if((obj->pos.x + fx - curd->ourImages[0].bitmap->w/32+1)>=0 && (obj->pos.x + fx - curd->ourImages[0].bitmap->w/32+1)pos.y + fy - curd->ourImages[0].bitmap->h/32+1)>=0 && (obj->pos.y + fy - curd->ourImages[0].bitmap->h/32+1) > & ctile = ttiles[obj->pos.x + fx - curd->ourImages[0].bitmap->w/32+1][obj->pos.y + fy - curd->ourImages[0].bitmap->h/32+1][obj->pos.z].objects; + std::vector < std::pair > & ctile = ttiles[obj->pos.x + fx - curd->ourImages[0].bitmap->w/32+1][obj->pos.y + fy - curd->ourImages[0].bitmap->h/32+1][obj->pos.z].objects; for(int dd=0; ddid==obj->id) @@ -1532,80 +1159,69 @@ bool CMapHandler::hideObject(CGObjectInstance *obj) } //for(int fx=0; fxourImages[0].bitmap->w/32; ++fx) return true; } - -std::string CMapHandler::getRandomizedDefName(CGDefInfo *di, CGObjectInstance * obj) -{ - return std::string(); -} - bool CMapHandler::removeObject(CGObjectInstance *obj) { hideObject(obj); - std::vector::iterator db = std::find(CGI->objh->objInstances.begin(), CGI->objh->objInstances.end(), obj); - recalculateHideVisPosUnderObj(*db); - delete *db; - CGI->objh->objInstances.erase(db); + recalculateHideVisPosUnderObj(obj); return true; } bool CMapHandler::recalculateHideVisPos(int3 &pos) { - ttiles[pos.x][pos.y][pos.z].visitable = false; - ttiles[pos.x][pos.y][pos.z].blocked = false; - for(int i=0; idefInfo->handler; - for(int fx=0; fx<8; ++fx) - { - for(int fy=0; fy<6; ++fy) - { - int xVal = ttiles[pos.x][pos.y][pos.z].objects[i].first->pos.x + fx - 7; - int yVal = ttiles[pos.x][pos.y][pos.z].objects[i].first->pos.y + fy - 5; - int zVal = ttiles[pos.x][pos.y][pos.z].objects[i].first->pos.z; - if(xVal>=0 && xVal=0 && yValdefInfo->visitMap[fy] >> (7 - fx)) & 1)) - curt.visitable = true; - if(!((ttiles[pos.x][pos.y][pos.z].objects[i].first->defInfo->blockMap[fy] >> (7 - fx)) & 1)) - curt.blocked = true; - } - } - } - } + //ttiles[pos.x][pos.y][pos.z].tileInfo->visitable = false; + //ttiles[pos.x][pos.y][pos.z].tileInfo->blocked = false; + //for(int i=0; idefInfo->handler; + // for(int fx=0; fx<8; ++fx) + // { + // for(int fy=0; fy<6; ++fy) + // { + // int xVal = ttiles[pos.x][pos.y][pos.z].objects[i].first->pos.x + fx - 7; + // int yVal = ttiles[pos.x][pos.y][pos.z].objects[i].first->pos.y + fy - 5; + // int zVal = ttiles[pos.x][pos.y][pos.z].objects[i].first->pos.z; + // if(xVal>=0 && xVal=0 && yValdefInfo->visitMap[fy] >> (7 - fx)) & 1)) + // curt.tileInfo->visitable = true; + // if(!((ttiles[pos.x][pos.y][pos.z].objects[i].first->defInfo->blockMap[fy] >> (7 - fx)) & 1)) + // curt.tileInfo->blocked = true; + // } + // } + // } + //} return true; } bool CMapHandler::recalculateHideVisPosUnderObj(CGObjectInstance *obj, bool withBorder) { - if(withBorder) - { - for(int fx=-1; fx<=obj->defInfo->handler->ourImages[0].bitmap->w/32; ++fx) - { - for(int fy=-1; fy<=obj->defInfo->handler->ourImages[0].bitmap->h/32; ++fy) - { - if((obj->pos.x + fx - obj->defInfo->handler->ourImages[0].bitmap->w/32+1)>=0 && (obj->pos.x + fx - obj->defInfo->handler->ourImages[0].bitmap->w/32+1)pos.y + fy - obj->defInfo->handler->ourImages[0].bitmap->h/32+1)>=0 && (obj->pos.y + fy - obj->defInfo->handler->ourImages[0].bitmap->h/32+1)pos.x + fx - obj->defInfo->handler->ourImages[0].bitmap->w/32 +1, obj->pos.y + fy - obj->defInfo->handler->ourImages[0].bitmap->h/32 + 1, obj->pos.z); - recalculateHideVisPos(tempPos); - } - } - } - } - else - { - for(int fx=0; fxdefInfo->handler->ourImages[0].bitmap->w/32; ++fx) - { - for(int fy=0; fydefInfo->handler->ourImages[0].bitmap->h/32; ++fy) - { - if((obj->pos.x + fx - obj->defInfo->handler->ourImages[0].bitmap->w/32+1)>=0 && (obj->pos.x + fx - obj->defInfo->handler->ourImages[0].bitmap->w/32+1)pos.y + fy - obj->defInfo->handler->ourImages[0].bitmap->h/32+1)>=0 && (obj->pos.y + fy - obj->defInfo->handler->ourImages[0].bitmap->h/32+1)pos.x + fx - obj->defInfo->handler->ourImages[0].bitmap->w/32 +1, obj->pos.y + fy - obj->defInfo->handler->ourImages[0].bitmap->h/32 + 1, obj->pos.z); - recalculateHideVisPos(tempPos); - } - } - } - } + //if(withBorder) + //{ + // for(int fx=-1; fx<=obj->defInfo->handler->ourImages[0].bitmap->w/32; ++fx) + // { + // for(int fy=-1; fy<=obj->defInfo->handler->ourImages[0].bitmap->h/32; ++fy) + // { + // if((obj->pos.x + fx - obj->defInfo->handler->ourImages[0].bitmap->w/32+1)>=0 && (obj->pos.x + fx - obj->defInfo->handler->ourImages[0].bitmap->w/32+1)pos.y + fy - obj->defInfo->handler->ourImages[0].bitmap->h/32+1)>=0 && (obj->pos.y + fy - obj->defInfo->handler->ourImages[0].bitmap->h/32+1)pos.x + fx - obj->defInfo->handler->ourImages[0].bitmap->w/32 +1, obj->pos.y + fy - obj->defInfo->handler->ourImages[0].bitmap->h/32 + 1, obj->pos.z)); + // } + // } + // } + //} + //else + //{ + // for(int fx=0; fxdefInfo->handler->ourImages[0].bitmap->w/32; ++fx) + // { + // for(int fy=0; fydefInfo->handler->ourImages[0].bitmap->h/32; ++fy) + // { + // if((obj->pos.x + fx - obj->defInfo->handler->ourImages[0].bitmap->w/32+1)>=0 && (obj->pos.x + fx - obj->defInfo->handler->ourImages[0].bitmap->w/32+1)pos.y + fy - obj->defInfo->handler->ourImages[0].bitmap->h/32+1)>=0 && (obj->pos.y + fy - obj->defInfo->handler->ourImages[0].bitmap->h/32+1)pos.x + fx - obj->defInfo->handler->ourImages[0].bitmap->w/32 +1, obj->pos.y + fy - obj->defInfo->handler->ourImages[0].bitmap->h/32 + 1, obj->pos.z)); + // } + // } + // } + //} return true; } @@ -1632,7 +1248,11 @@ unsigned char CMapHandler::getHeroFrameNum(const unsigned char &dir, const bool case 8: return 11; default: - return -1; //should never happen +#ifndef __GNUC__ + throw std::exception("Something very wrong1."); +#else + throw std::exception(); +#endif } } else //if(isMoving) @@ -1656,7 +1276,11 @@ unsigned char CMapHandler::getHeroFrameNum(const unsigned char &dir, const bool case 8: return 14; default: - return -1; //should never happen +#ifndef __GNUC__ + throw std::exception("Something very wrong2."); +#else + throw std::exception(); +#endif } } } @@ -1739,3 +1363,27 @@ unsigned char CMapHandler::getDir(const int3 &a, const int3 &b) } return -2; //shouldn't happen } + + +void CMapHandler::loadDefs() +{ + std::set loadedTypes; + for (int i=0; iwidth; i++) + { + for (int j=0; jwidth; j++) + { + if (loadedTypes.find(map->terrain[i][j][0].tertype)==loadedTypes.end()) + { + CDefHandler *sdh = CDefHandler::giveDef(nameFromType(map->terrain[i][j][0].tertype).c_str()); + loadedTypes.insert(map->terrain[i][j][0].tertype); + defs.push_back(sdh); + } + if (map->twoLevel && loadedTypes.find(map->terrain[i][j][1].tertype)==loadedTypes.end()) + { + CDefHandler *sdh = CDefHandler::giveDef(nameFromType(map->terrain[i][j][1].tertype).c_str()); + loadedTypes.insert(map->terrain[i][j][1].tertype); + defs.push_back(sdh); + } + } + } +} diff --git a/mapHandler.h b/mapHandler.h index f9989a8c4..5b1d4f664 100644 --- a/mapHandler.h +++ b/mapHandler.h @@ -1,37 +1,29 @@ #ifndef MAPHANDLER_H #define MAPHANDLER_H - -#include "hch/CAmbarCendamo.h" -#include "hch/CSemiDefHandler.h" -#include "CGameInfo.h" -#include "hch/CDefHandler.h" -#include -#include "hch/CObjectHandler.h" +#include "global.h" +#include #include +#include const int Woff = 12; //width of map's frame const int Hoff = 8; +class CGObjectInstance; +class CGHeroInstance; +struct Mapa; +class CGDefInfo; +class CGObjectInstance; +class CDefHandler; +struct TerrainTile; + struct TerrainTile2 { - int3 pos; //this tile's position - EterrainType terType; //type of terrain tile - - Eroad malle; //type of road - unsigned char roaddir; //type of road tile - - Eriver nuine; //type of river - unsigned char rivdir; //type of river tile - + int3 pos; + const TerrainTile *tileInfo; std::vector terbitmap; //frames of terrain animation std::vector rivbitmap; //frames of river animation std::vector roadbitmap; //frames of road animation - bool visitable; //false = not visitable; true = visitable - bool blocked; //false = free; true = blocked; - - std::vector < std::pair > objects; //poiters to objects being on this tile with rects to be easier to blit this tile on screen - std::vector visitableObjects; //pointers to objects hero is visiting being on this tile - + std::vector < std::pair > objects; //poiters to objects being on this tile with rects to be easier to blit this tile on screen }; //pathfinder @@ -42,6 +34,18 @@ template class PseudoV public: int offset; std::vector inver; + PseudoV(){}; + PseudoV(std::vector &src, int rest, int Offset, const T& fill) + { + inver.resize(Offset*2+rest); + offset=Offset; + for(int i=0; i > > ttiles; int3 sizes; - CAmbarCendamo * reader; + Mapa * map; std::set usedHeroes; CDefHandler * fullHide; CDefHandler * partialHide; - PseudoV< PseudoV< PseudoV > > visibility; //true means that pointed place is visible //not used now - //std::vector< std::vector > undVisibility; //true means that pointed place is visible std::vector roadDefs; std::vector staticRiverDefs; + std::vector defs; std::map loadedDefs; //pointers to loaded defs (key is filename, uppercase) - std::map villages, forts, capitols; - 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 - PseudoV< PseudoV< PseudoV > > hideBitmap; //specifies number of graphic that should be used to fully hide a tile + std::vector > > hideBitmap; //specifies number of graphic that should be used to fully hide a tile - char & visAccess(int x, int y); - char & undVisAccess(int x, int y); - SDL_Surface mirrorImage(SDL_Surface *src); //what is this?? - SDL_Surface * getVisBitmap(int x, int y, PseudoV< PseudoV< PseudoV > > & visibilityMap, int lvl); + void loadDefs(); + SDL_Surface * getVisBitmap(int x, int y, std::vector< std::vector< std::vector > > & visibilityMap, int lvl); int getCost(int3 & a, int3 & b, const CGHeroInstance * hero); std::vector< std::string > getObjDescriptions(int3 pos); //returns desriptions of objects blocking given position - std::vector< CGObjectInstance * > getVisitableObjs(int3 pos); //returns vector of visitable objects at certain position + //std::vector< CGObjectInstance * > getVisitableObjs(int3 pos); //returns vector of visitable objects at certain position CGObjectInstance * createObject(int id, int subid, int3 pos, int owner=254); //creates a new object with a certain id and subid std::string getDefName(int id, int subid); //returns name of def for object with given id and subid bool printObject(CGObjectInstance * obj); //puts appropriate things to ttiles, so obj will be visible on map @@ -94,20 +92,13 @@ public: bool recalculateHideVisPos(int3& pos); //recalculates position for hidden / visitable positions bool recalculateHideVisPosUnderObj(CGObjectInstance * obj, bool withBorder = false); //recalculates position for hidden / visitable positions under given object void init(); - int pickHero(int owner); - std::pair pickObject(CGObjectInstance *obj); - void randomizeObject(CGObjectInstance *cur); void calculateBlockedPos(); void initObjectRects(); void borderAndTerrainBitmapInit(); void roadsRiverTerrainInit(); void prepareFOWDefs(); - void randomizeObjects(); - SDL_Surface * terrainRect(int x, int y, int dx, int dy, int level=0, unsigned char anim=0, PseudoV< PseudoV< PseudoV > > & visibilityMap = CGI->mh->visibility, bool otherHeroAnim = false, unsigned char heroAnim = 0, SDL_Surface * extSurf = NULL, SDL_Rect * extRect = NULL); //if extSurf is specified, blit to it - SDL_Surface * terrBitmap(int x, int y); - SDL_Surface * undTerrBitmap(int x, int y); - std::string getRandomizedDefName(CGDefInfo* di, CGObjectInstance * obj = NULL); //objinstance needed only for heroes and towns + SDL_Surface * terrainRect(int x, int y, int dx, int dy, int level=0, unsigned char anim=0, std::vector< std::vector< std::vector > > * visibilityMap = NULL, bool otherHeroAnim = false, unsigned char heroAnim = 0, SDL_Surface * extSurf = NULL, SDL_Rect * extRect = NULL); //if extSurf is specified, blit to it unsigned char getHeroFrameNum(const unsigned char & dir, const bool & isMoving) const; //terrainRect helper function void validateRectTerr(SDL_Rect * val, const SDL_Rect * ext); //terrainRect helper static unsigned char getDir(const int3 & a, const int3 & b); //returns direction number in range 0 - 7 (0 is left top, clockwise) [direction: form a to b] diff --git a/server/CGameHandler.cpp b/server/CGameHandler.cpp new file mode 100644 index 000000000..0e3c4c6e2 --- /dev/null +++ b/server/CGameHandler.cpp @@ -0,0 +1,907 @@ +#include +#include +#include +#include +#include "CGameHandler.h" +#include "CScriptCallback.h" +#include "../CLua.h" +#include "../CGameState.h" +#include "../StartInfo.h" +#include "../map.h" +#include "../lib/NetPacks.h" +#include "../lib/Connection.h" +#include "../CLua.h" +#include "../hch/CObjectHandler.h" +#include "../hch/CTownHandler.h" +#include "../hch/CBuildingHandler.h" +#include "../hch/CHeroHandler.h" +#include "boost/date_time/posix_time/posix_time_types.hpp" //no i/o just types +#include "../lib/VCMI_Lib.h" +#include "../lib/CondSh.h" +#include +extern bool end2; +#include "../lib/BattleAction.h" +#ifdef min +#undef min +#endif +#ifdef max +#undef max +#endif +#define NEW_ROUND BattleNextRound bnr;\ + bnr.round = gs->curB->round + 1;\ + sendAndApply(&bnr); +boost::condition_variable cTurn; +boost::mutex mTurn; +boost::shared_mutex gsm; + + +CondSh battleMadeAction; +CondSh battleResult(NULL); + +class CMP_stack +{ +public: + bool operator ()(const CStack* a, const CStack* b) + { + return (a->creature->speed)>(b->creature->speed); + } +} cmpst ; + +double distance(int3 a, int3 b) +{ + return std::sqrt( (double)(a.x-b.x)*(a.x-b.x) + (a.y-b.y)*(a.y-b.y) ); +} +//bool CGameState::checkFunc(int obid, std::string name) +//{ +// if (objscr.find(obid)!=objscr.end()) +// { +// if(objscr[obid].find(name)!=objscr[obid].end()) +// { +// return true; +// } +// } +// return false; +//} + +void CGameHandler::handleCPPObjS(std::map * mapa, CCPPObjectScript * script) +{ + std::vector tempv = script->yourObjects(); + for (unsigned i=0;i(gs->map->objects[ID]); + if(hero->exp >= VLC->heroh->reqExp(hero->level+1)) //new level + { + //hero->level++; + + //give prim skill + std::cout << hero->name <<" got level "<level<::*g = (hero->level>9) ? (&std::pair::second) : (&std::pair::first); + for(;xtype->heroClass->primChance[x].*g; + if(rprimSkills[x]++; + + std::set choice; + + std::set basicAndAdv, expert, none; + for(int i=0;isecSkills.size();i++) + { + if(hero->secSkills[i].second < 2) + basicAndAdv.insert(hero->secSkills[i].first); + else + expert.insert(hero->secSkills[i].first); + none.erase(hero->secSkills[i].first); + } + if(hero->secSkills.size() < hero->type->heroClass->skillLimit) //free skill slot + { + choice.insert(hero->type->heroClass->chooseSecSkill(none)); //new skill + } + else + { + int s = hero->type->heroClass->chooseSecSkill(basicAndAdv); + choice.insert(s); + basicAndAdv.erase(s); + } + if(basicAndAdv.size()) + { + choice.insert(hero->type->heroClass->chooseSecSkill(basicAndAdv)); //new skill + } + else if(hero->secSkills.size() < hero->type->heroClass->skillLimit) + { + choice.insert(hero->type->heroClass->chooseSecSkill(none)); //new skill + } + + } + //TODO - powiadomic interfejsy, sprawdzic czy nie ma awansu itp + } +} + +void CGameHandler::startBattle(CCreatureSet army1, CCreatureSet army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2) +{ + + BattleInfo *curB = new BattleInfo; + //battle start + { + battleResult.set(NULL); + std::vector & stacks = (curB->stacks); + + curB->army1=army1; + curB->army2=army2; + curB->hero1=(hero1)?(hero1->id):(-1); + curB->hero2=(hero1)?(hero1->id):(-1); + curB->side1=(hero1)?(hero1->tempOwner):(-1); + curB->side2=(hero2)?(hero2->tempOwner):(-1); + curB->round = -2; + curB->activeStack = -1; + for(std::map >::iterator i = army1.slots.begin(); i!=army1.slots.end(); i++) + { + stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero1->tempOwner, stacks.size(), true)); + stacks[stacks.size()-1]->ID = stacks.size()-1; + } + //initialization of positions + switch(army1.slots.size()) //for attacker + { + case 0: + break; + case 1: + stacks[0]->position = 86; //6 + break; + case 2: + stacks[0]->position = 35; //3 + stacks[1]->position = 137; //9 + break; + case 3: + stacks[0]->position = 35; //3 + stacks[1]->position = 86; //6 + stacks[2]->position = 137; //9 + break; + case 4: + stacks[0]->position = 1; //1 + stacks[1]->position = 69; //5 + stacks[2]->position = 103; //7 + stacks[3]->position = 171; //11 + break; + case 5: + stacks[0]->position = 1; //1 + stacks[1]->position = 35; //3 + stacks[2]->position = 86; //6 + stacks[3]->position = 137; //9 + stacks[4]->position = 171; //11 + break; + case 6: + stacks[0]->position = 1; //1 + stacks[1]->position = 35; //3 + stacks[2]->position = 69; //5 + stacks[3]->position = 103; //7 + stacks[4]->position = 137; //9 + stacks[5]->position = 171; //11 + break; + case 7: + stacks[0]->position = 1; //1 + stacks[1]->position = 35; //3 + stacks[2]->position = 69; //5 + stacks[3]->position = 86; //6 + stacks[4]->position = 103; //7 + stacks[5]->position = 137; //9 + stacks[6]->position = 171; //11 + break; + default: //fault + break; + } + for(std::map >::iterator i = army2.slots.begin(); i!=army2.slots.end(); i++) + stacks.push_back(new CStack(&VLC->creh->creatures[i->second.first],i->second.second,hero2 ? hero2->tempOwner : 255, stacks.size(), false)); + switch(army2.slots.size()) //for defender + { + case 0: + break; + case 1: + stacks[0+army1.slots.size()]->position = 100; //6 + break; + case 2: + stacks[0+army1.slots.size()]->position = 49; //3 + stacks[1+army1.slots.size()]->position = 151; //9 + break; + case 3: + stacks[0+army1.slots.size()]->position = 49; //3 + stacks[1+army1.slots.size()]->position = 100; //6 + stacks[2+army1.slots.size()]->position = 151; //9 + break; + case 4: + stacks[0+army1.slots.size()]->position = 15; //1 + stacks[1+army1.slots.size()]->position = 83; //5 + stacks[2+army1.slots.size()]->position = 117; //7 + stacks[3+army1.slots.size()]->position = 185; //11 + break; + case 5: + stacks[0+army1.slots.size()]->position = 15; //1 + stacks[1+army1.slots.size()]->position = 49; //3 + stacks[2+army1.slots.size()]->position = 100; //6 + stacks[3+army1.slots.size()]->position = 151; //9 + stacks[4+army1.slots.size()]->position = 185; //11 + break; + case 6: + stacks[0+army1.slots.size()]->position = 15; //1 + stacks[1+army1.slots.size()]->position = 49; //3 + stacks[2+army1.slots.size()]->position = 83; //5 + stacks[3+army1.slots.size()]->position = 117; //7 + stacks[4+army1.slots.size()]->position = 151; //9 + stacks[5+army1.slots.size()]->position = 185; //11 + break; + case 7: + stacks[0+army1.slots.size()]->position = 15; //1 + stacks[1+army1.slots.size()]->position = 49; //3 + stacks[2+army1.slots.size()]->position = 83; //5 + stacks[3+army1.slots.size()]->position = 100; //6 + stacks[4+army1.slots.size()]->position = 117; //7 + stacks[5+army1.slots.size()]->position = 151; //9 + stacks[6+army1.slots.size()]->position = 185; //11 + break; + default: //fault + break; + } + for(unsigned g=0; gposition%17)==1 && stacks[g]->creature->isDoubleWide()) + { + stacks[g]->position += 1; + } + else if((stacks[g]->position%17)==15 && stacks[g]->creature->isDoubleWide()) + { + stacks[g]->position -= 1; + } + } + std::stable_sort(stacks.begin(),stacks.end(),cmpst); + + //block engaged players + if(hero1->tempOwnertempOwner] += 10; + if(hero2 && hero2->tempOwnertempOwner] += 10; + + //send info about battles + BattleStart bs; + bs.info = curB; + sendAndApply(&bs); + + NEW_ROUND; + } + + //tactic round + { + NEW_ROUND; + if( (hero1 && hero1->getSecSkillLevel(19)>=0) || + ( hero2 && hero2->getSecSkillLevel(19)>=0) )//someone has tactics + { + //TODO: tactic round (round -1) + } + } + + //main loop + while(!battleResult.get()) //till the end of the battle ;] + { + NEW_ROUND; + std::vector & stacks = (gs->curB->stacks); + const BattleInfo & curB = *gs->curB; + + //stack loop + for(unsigned i=0;ialive) continue;//indicates imposiibility of making action for this dead unit + BattleSetActiveStack sas; + sas.stack = stacks[i]->ID; + sendAndApply(&sas); + + //wait for response about battle action + + boost::unique_lock lock(battleMadeAction.mx); + while(!battleMadeAction.data) + battleMadeAction.cond.wait(lock); + battleMadeAction.data = false; + } + } + + //end battle, remove all info, free memory + sendAndApply(battleResult.data); + delete battleResult.data; + //for(int i=0;i players, CConnection &c) +{ + try + { + ui16 pom; + while(!end2) + { + c >> pom; + bool blockvis = false; + switch(pom) + { + case 100: //my interface ended its turn + { + mTurn.lock(); + states[gs->currentPlayer] = 0; + mTurn.unlock(); + cTurn.notify_all(); + break; + } + case 500: + { + si32 id; + c >> id; + RemoveHero rh(id); + sendAndApply(&rh); + break; + } + case 501://interface wants to move hero + { + int3 start, end; + si32 id; + c >> id >> start >> end; + int3 hmpos = end + int3(-1,0,0); + TerrainTile t = gs->map->terrain[hmpos.x][hmpos.y][hmpos.z]; + CGHeroInstance *h = static_cast(gs->map->objects[id]); + int cost = (int)((double)h->getTileCost(t.tertype,t.malle,t.nuine) * distance(start,end)); + + TryMoveHero tmh; + tmh.id = id; + tmh.start = start; + tmh.end = end; + tmh.result = 0; + tmh.movePoints = h->movement; + + if((h->getOwner() != gs->currentPlayer) || //not turn of that hero + (distance(start,end)>=1.5) || //tiles are not neighouring + (h->movement < cost) || //lack of movement points + (t.tertype == rock) || //rock + (!h->canWalkOnSea() && t.tertype == water) || + (t.blocked && !t.visitable) ) //tile is blocked andnot visitable + goto fail; + + + //check if there is blocking visitable object + blockvis = false; + tmh.movePoints = h->movement = (h->movement-cost); //take move points + BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects) + { + if(obj->blockVisit) + { + blockvis = true; + break; + } + } + + + //we start moving + if(blockvis)//interaction with blocking object (like resources) + { + sendAndApply(&tmh); //failed to move to that tile but we visit object + BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects) + { + if (obj->blockVisit) + { + //if(gs->checkFunc(obj->ID,"heroVisit")) //script function + // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID); + if(obj->state) //hard-coded function + obj->state->onHeroVisit(obj->id,h->subID); + } + } + break; + } + else //normal move + { + tmh.result = 1; + + BOOST_FOREACH(CGObjectInstance *obj, gs->map->terrain[start.x][start.y][start.z].visitableObjects) + { + //TODO: allow to handle this in script-languages + if(obj->state) //hard-coded function + obj->state->onHeroLeave(obj->id,h->subID); + } + + //reveal fog of war + int heroSight = h->getSightDistance(); + int xbeg = start.x - heroSight - 2; + if(xbeg < 0) + xbeg = 0; + int xend = start.x + heroSight + 2; + if(xend >= gs->map->width) + xend = gs->map->width; + int ybeg = start.y - heroSight - 2; + if(ybeg < 0) + ybeg = 0; + int yend = start.y + heroSight + 2; + if(yend >= gs->map->height) + yend = gs->map->height; + for(int xd=xbeg; xdgetSightDistance()*h->getSightDistance()) + { + if(gs->players[h->getOwner()].fogOfWarMap[xd][yd][hmpos.z] == 0) + { + tmh.fowRevealed.insert(int3(xd,yd,hmpos.z)); + } + } + } + } + + sendAndApply(&tmh); + + BOOST_FOREACH(CGObjectInstance *obj, t.visitableObjects)//call objects if they are visited + { + //if(gs->checkFunc(obj->ID,"heroVisit")) //script function + // gs->objscr[obj->ID]["heroVisit"]->onHeroVisit(obj,h->subID); + if(obj->state) //hard-coded function + obj->state->onHeroVisit(obj->id,h->id); + } + } + break; + fail: + sendAndApply(&tmh); + break; + } + case 502: //swap creatures in garrison + { + ui8 what, p1, p2; si32 id1, id2; + c >> what >> id1 >> p1 >> id2 >> p2; + CArmedInstance *s1 = static_cast(gs->map->objects[id1]), + *s2 = static_cast(gs->map->objects[id2]); + CCreatureSet *S1 = &s1->army, *S2 = &s2->army; + + if(what==1) //swap + { + int 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); + } + else if(what==2)//merge + { + if(S1->slots[p1].first != S2->slots[p2].first) break; //not same creature + S2->slots[p2].second += S1->slots[p1].second; + S1->slots[p1].first = NULL; + S1->slots[p1].second = 0; + S1->slots.erase(p1); + } + else if(what==3) //split + { + si32 val; + c >> val; + if(S2->slots.find(p2) != S2->slots.end()) break; //slot not free + 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); + } + SetGarrisons sg; + sg.garrs[id1] = *S1; + if(s1 != s2) + sg.garrs[id2] = *S2; + sendAndApply(&sg); + break; + } + case 503: + { + si32 id; + ui8 pos; + c >> id >> pos; + CArmedInstance *s1 = static_cast(gs->map->objects[id]); + s1->army.slots.erase(pos); + SetGarrisons sg; + sg.garrs[id] = s1->army; + sendAndApply(&sg); + break; + } + case 504: + { + si32 tid, bid; + c >> tid >> bid; + CGTownInstance * t = static_cast(gs->map->objects[tid]); + CBuilding * b = VLC->buildh->buildings[t->subID][bid]; + for(int i=0;iresources[i] > gs->players[t->tempOwner].resources[i]) + break; //no res + //TODO: check requirements + //TODO: check if building isn't forbidden + + NewStructures ns; + ns.tid = tid; + if(bid>36) //upg dwelling + { + if(t->getHordeLevel(0) == (bid-37)) + ns.bid.insert(19); + else if(t->getHordeLevel(1) == (bid-37)) + ns.bid.insert(25); + } + else if(bid >= 30) //bas. dwelling + { + SetStrInfo ssi; + ssi.tid = tid; + ssi.cres = t->strInfo.creatures; + ssi.cres[bid-30] = VLC->creh->creatures[t->town->basicCreatures[bid-30]].growth; + sendAndApply(&ssi); + } + + ns.bid.insert(bid); + ns.builded = t->builded + 1; + sendAndApply(&ns); + + SetResources sr; + sr.player = t->tempOwner; + sr.res = gs->players[t->tempOwner].resources; + for(int i=0;i<7;i++) + sr.res[i]-=b->resources[i]; + sendAndApply(&sr); + + break; + } + case 3002: + { + BattleAction ba; + c >> ba; + switch(ba.actionType) + { + case 2: //walk + { + CStack *curStack = gs->curB->getStack(ba.stackNumber), + *stackAtEnd = gs->curB->getStackT(ba.destinationTile); + + //initing necessary tables + bool accessibility[187]; + if(curStack->creature->isDoubleWide()) + { + gs->curB->getAccessibilityMapForTwoHex(accessibility,curStack->attackerOwned); + accessibility[curStack->attackerOwned ? curStack->position+1 : curStack->position-1]=true;//OUR second tile is for US accessible + } + else + gs->curB->getAccessibilityMap(accessibility); + accessibility[curStack->position] = true; //OUR tile is for US accessible + + //if(!stackAtEnd && !accessibility[dest]) + // return false; + + //if(dists[dest] > curStack->creature->speed && !(stackAtEnd && dists[dest] == curStack->creature->speed+1)) //we can attack a stack if we can go to adjacent hex + // return false; + + std::vector path = gs->curB->getPath(curStack->position,ba.destinationTile,accessibility); + int tilesToMove = std::max((int)path.size()-curStack->creature->speed, 0); + for(int v=path.size()-1; v>=tilesToMove; --v) + { + if(v!=0 || !stackAtEnd) //it's not the last step or the last tile is free + { + //inform clients about move + BattleStackMoved sm; + sm.stack = curStack->ID; + sm.tile = path[v]; + if(v==path.size()-1)//move start - set flag + sm.flags |= 1; + if(v==0 || (stackAtEnd && v==1)) //move end - set flag + sm.flags |= 2; + sendAndApply(&sm); + } + else //if it's last step and we should attack unit at the end + { + //LOCPLINT->battleStackAttacking(ID, path[v]); + ////counting dealt damage + //int finalDmg = calculateDmg(curStack, curB->stacks[numberOfStackAtEnd]); + + ////applying damages + //int cresKilled = finalDmg / curB->stacks[numberOfStackAtEnd]->creature->hitPoints; + //int damageFirst = finalDmg % curB->stacks[numberOfStackAtEnd]->creature->hitPoints; + + //if( curB->stacks[numberOfStackAtEnd]->firstHPleft <= damageFirst ) + //{ + // curB->stacks[numberOfStackAtEnd]->amount -= 1; + // curB->stacks[numberOfStackAtEnd]->firstHPleft += curB->stacks[numberOfStackAtEnd]->creature->hitPoints - damageFirst; + //} + //else + //{ + // curB->stacks[numberOfStackAtEnd]->firstHPleft -= damageFirst; + //} + + //int cresInstackBefore = curB->stacks[numberOfStackAtEnd]->amount; + //curB->stacks[numberOfStackAtEnd]->amount -= cresKilled; + //if(curB->stacks[numberOfStackAtEnd]->amount<=0) //stack killed + //{ + // curB->stacks[numberOfStackAtEnd]->amount = 0; + // LOCPLINT->battleStackKilled(curB->stacks[numberOfStackAtEnd]->ID, finalDmg, std::min(cresKilled, cresInstackBefore) , ID, false); + // curB->stacks[numberOfStackAtEnd]->alive = false; + //} + //else + //{ + // LOCPLINT->battleStackIsAttacked(curB->stacks[numberOfStackAtEnd]->ID, finalDmg, std::min(cresKilled, cresInstackBefore), ID, false); + //} + + //damage applied + } + } + //curB->stackActionPerformed = true; + //LOCPLINT->actionFinished(BattleAction()); + break; + } + case 3: //defend + { + break; + } + case 4: //retreat/flee + { + //TODO: check if fleeing is possible (e.g. enemy may have Shackles of War) + //TODO: calculate casualties + //TODO: remove retreating hero from map and place it in recrutation list + BattleResult *br = new BattleResult; + br->result = 1; + battleResult.set(br); + break; + } + case 6: //walk or attack + { + //battleMoveCreatureStack(ba.stackNumber, ba.destinationTile); + //battleAttackCreatureStack(ba.stackNumber, ba.destinationTile); + break; + } + case 7: //shoot + { + //battleShootCreatureStack(ba.stackNumber, ba.destinationTile); + break; + } + } + battleMadeAction.setn(true); + //sprawdzic czy po tej akcji ktoras strona nie wygrala bitwy + break; + } + default: +#ifndef __GNUC__ + throw std::exception("Not supported client message!"); +#else + throw std::exception(); +#endif + break; + } + } + } + catch (const std::exception& e) + { + std::cerr << e.what() << std::endl; + end2 = true; + } + catch (const std::exception * e) + { + std::cerr << e->what()<< std::endl; + end2 = true; + delete e; + } + catch(...) + { + end2 = true; + } +} +CGameHandler::CGameHandler(void) +{ + gs = NULL; +} + +CGameHandler::~CGameHandler(void) +{ + delete gs; +} +void CGameHandler::init(StartInfo *si, int Seed) +{ + Mapa *map = new Mapa(si->mapname); + gs = new CGameState(); + gs->init(si,map,Seed); + + /****************************LUA OBJECT SCRIPTS************************************************/ + //std::vector * lf = CLuaHandler::searchForScripts("scripts/lua/objects"); //files + //for (int i=0; isize(); i++) + //{ + // try + // { + // std::vector * temp = CLuaHandler::functionList((*lf)[i]); + // CLuaObjectScript * objs = new CLuaObjectScript((*lf)[i]); + // CLuaCallback::registerFuncs(objs->is); + // //objs + // for (int j=0; jsize(); 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 >(obid,std::map())); + // (*skrypty)[obid].insert(std::pair(fname,objs)); + // } + // delete temp; + // }HANDLE_EXCEPTION + //} + + //delete lf; +} +int lowestSpeed(CGHeroInstance * chi) +{ + std::map >::iterator i = chi->army.slots.begin(); + int ret = VLC->creh->creatures[(*i++).second.first].speed; + for (;i!=chi->army.slots.end();i++) + { + ret = std::min(ret,VLC->creh->creatures[(*i).second.first].speed); + } + return ret; +} +int 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 CGameHandler::newTurn() +{ + NewTurn n; + n.day = gs->day + 1; + + for ( std::map::iterator i=gs->players.begin() ; i!=gs->players.end();i++) + { + if(i->first>=PLAYER_LIMIT) continue; + NewTurn::Resources r; + r.player = i->first; + for(int j=0;jsecond.resources[j]; + + for (unsigned j=0;j<(*i).second.heroes.size();j++) //handle heroes + { + NewTurn::Hero h; + h.id = (*i).second.heroes[j]->id; + h.move = valMovePoints((*i).second.heroes[j]); + h.mana = (*i).second.heroes[j]->mana; + n.heroes.insert(h); + } + for(unsigned j=0;jsecond.towns.size();j++)//handle towns + { + i->second.towns[j]->builded=0; + //if(gs->getDate(1)==1) //first day of week + //{ + // for(int k=0;ksecond.towns[j]->creatureDwelling(k))//there is dwelling (k-level) + // i->second.towns[j]->strInfo.creatures[k]+=i->second.towns[j]->creatureGrowth(k); + // } + //} + if((gs->day) && i->firstsecond.towns[j]->dailyIncome(); + } + n.res.insert(r); + } + sendAndApply(&n); + for (std::set::iterator i=cppscripts.begin();i!=cppscripts.end();i++) + { + (*i)->newTurn(); + } +} +void CGameHandler::run() +{ + BOOST_FOREACH(CConnection *cc, conns) + {//init conn. + ui8 quantity, pom; + //ui32 seed; + (*cc) << gs->scenarioOps->mapname << gs->map->checksum << gs->seed; + (*cc) >> quantity; + for(int i=0;i> pom; + gsm.lock(); + connections[pom] = cc; + gsm.unlock(); + } + } + + for(std::set::iterator i = conns.begin(); i!=conns.end();i++) + { + std::set pom; + for(std::map::iterator j = connections.begin(); j!=connections.end();j++) + if(j->second == *i) + pom.insert(j->first); + + boost::thread(boost::bind(&CGameHandler::handleConnection,this,pom,boost::ref(**i))); + } + + /****************************SCRIPTS************************************************/ + //std::map > * skrypty = &objscr; //alias for easier access + /****************************C++ OBJECT SCRIPTS************************************************/ + std::map scripts; + CScriptCallback * csc = new CScriptCallback(); + csc->gh = this; + 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)); + + /****************************INITIALIZING OBJECT SCRIPTS************************************************/ + //std::string temps("newObject"); + for (unsigned i=0; imap->objects.size(); i++) + { + //c++ scripts + if (scripts.find(gs->map->objects[i]->ID) != scripts.end()) + { + gs->map->objects[i]->state = scripts[gs->map->objects[i]->ID]; + gs->map->objects[i]->state->newObject(gs->map->objects[i]->id); + } + else + { + gs->map->objects[i]->state = NULL; + } + + //// lua scripts + //if(checkFunc(map->objects[i]->ID,temps)) + // (*skrypty)[map->objects[i]->ID][temps]->newObject(map->objects[i]); + } + + while (!end2) + { + newTurn(); + for(std::map::iterator i = gs->players.begin(); i != gs->players.end(); i++) + { + if((i->second.towns.size()==0 && i->second.heroes.size()==0) || i->second.color<0 || i->first>=PLAYER_LIMIT ) continue; //players has not towns/castle - loser + states[i->first] = 1; + gs->currentPlayer = i->first; + *connections[i->first] << ui16(100) << i->first; + //wait till turn is done + boost::unique_lock lock(mTurn); + while(states[i->first] && !end2) + { + boost::posix_time::time_duration p; + p= boost::posix_time::seconds(1); + boost::xtime time={0,0}; + time.sec = static_cast(p.total_seconds()); + cTurn.timed_wait(lock,time); + } + } + } +} diff --git a/server/CGameHandler.h b/server/CGameHandler.h new file mode 100644 index 000000000..47683243b --- /dev/null +++ b/server/CGameHandler.h @@ -0,0 +1,58 @@ +#pragma once +#include "../global.h" +#include +#include "../CGameState.h" +#include "../lib/Connection.h" +#ifndef _MSC_VER +#include +#endif +class CVCMIServer; +class CGameState; +//class CConnection; +struct StartInfo; +class CCPPObjectScript; +class CScriptCallback; +template struct CPack; +class CGHeroInstance; +class CGameHandler +{ + + CGameState *gs; + std::set cppscripts; //C++ scripts + //std::map > objscr; //non-C++ scripts + + CVCMIServer *s; + std::map connections; //player color -> connection to clinet with interface of that player + std::map states; //player color -> player state + std::set conns; + + void handleCPPObjS(std::map * mapa, CCPPObjectScript * script); + void changePrimSkill(int ID, int which, int val, bool abs=false); + void startBattle(CCreatureSet army1, CCreatureSet army2, int3 tile, CGHeroInstance *hero1, CGHeroInstance *hero2); //use hero=NULL for no hero + + +public: + CGameHandler(void); + ~CGameHandler(void); + void init(StartInfo *si, int Seed); + void handleConnection(std::set players, CConnection &c); + template void sendToAllClients(CPack * info) + { + for(std::set::iterator i=conns.begin(); i!=conns.end();i++) + { + (*i)->wmx->lock(); + **i << info->getType() << *info->This(); + (*i)->wmx->unlock(); + } + } + template void sendAndApply(CPack * info) + { + gs->apply(info); + sendToAllClients(info); + } + void run(); + void newTurn(); + + friend class CVCMIServer; + friend class CScriptCallback; +}; diff --git a/server/CScriptCallback.cpp b/server/CScriptCallback.cpp new file mode 100644 index 000000000..0c9abd64a --- /dev/null +++ b/server/CScriptCallback.cpp @@ -0,0 +1,244 @@ +#include "CScriptCallback.h" +#include "../lib/Connection.h" +#include "CVCMIServer.h" +#include "CGameHandler.h" +#include "../CGameState.h" +#include "../map.h" +#include "../hch/CObjectHandler.h" +#include "../hch/CTownHandler.h" +#include "../hch/CHeroHandler.h" +#include "../lib/NetPacks.h" +#include "../lib/VCMI_Lib.h" +#include +#include +#include +CScriptCallback::CScriptCallback(void) +{ +} + +CScriptCallback::~CScriptCallback(void) +{ +} +void CScriptCallback::setBlockVis(int objid, bool bv) +{ + SetObjectProperty sop(objid,2,bv); + gh->sendAndApply(&sop); +} +void CScriptCallback::setOwner(int objid, ui8 owner) +{ + SetObjectProperty sop(objid,1,owner); + gh->sendAndApply(&sop); +} +const CGObjectInstance* CScriptCallback::getObj(int objid) +{ + return gh->gs->map->objects[objid]; +} +const CGHeroInstance* CScriptCallback::getHero(int objid) +{ + return static_cast(gh->gs->map->objects[objid]); +} +const CGTownInstance* CScriptCallback::getTown(int objid) +{ + return static_cast(gh->gs->map->objects[objid]); +} +void CScriptCallback::setHoverName(int objid, MetaString* name) +{ + SetHoverName shn(objid, *name); + gh->sendAndApply(&shn); +} +int3 CScriptCallback::getPos(CGObjectInstance * ob) +{ + return ob->pos; +} +void CScriptCallback::changePrimSkill(int ID, int which, int val, bool abs) +{ + gh->changePrimSkill(ID, which, val, abs); +} + +int CScriptCallback::getHeroOwner(int heroID) +{ + return gh->gs->map->objects[heroID]->tempOwner; +} +void CScriptCallback::showInfoDialog(InfoWindow *iw) +{ + gh->sendToAllClients(iw); + //TODO: upewniac sie ze mozemy to zrzutowac (przy customowych interfejsach cos moze sie kopnac) + //if (player>=0) + //{ + // CGameInterface * temp = sv->playerint[player]; + // if (temp->human) + // ((CPlayerInterface*)(temp))->showInfoDialog(text,*components); + // return; + //} + //else + //{ + // typedef std::pair intf; + // BOOST_FOREACH(intf & i, sv->playerint) + // { + // if (i.second->human) + // ((CPlayerInterface*)(i.second))->showInfoDialog(text,*components); + // } + //} +} + +void CScriptCallback::showSelDialog(int player, std::string text, std::vector*components, IChosen * asker) +{ + //CGameInterface * temp = sv->playerint[player]; + //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 -1; +} +int CScriptCallback::getDate(int mode) +{ + return gh->gs->getDate(mode); +} +void CScriptCallback::giveResource(int player, int which, int val) +{ + SetResource sr; + sr.player = player; + sr.resid = which; + sr.val = (gh->gs->players[player].resources[which]+val); + gh->sendAndApply(&sr); +} +void CScriptCallback::showCompInfo(ShowInInfobox * comp) +{ + gh->sendToAllClients(comp); +} +void CScriptCallback::heroVisitCastle(int obj, int heroID) +{ + //CGTownInstance * n; + //if(n = dynamic_cast(ob)) + //{ + // n->visitingHero = CGI->state->map->getHero(heroID,0); + // gh->gs->map->getHero(heroID,0)->visitedTown = n; + // sv->playerint[getHeroOwner(heroID)]->heroVisitsTown(CGI->state->map->getHero(heroID,0),n); + //} + //else + // return; +} + +void CScriptCallback::stopHeroVisitCastle(int obj, int heroID) +{ + //CGTownInstance * n; + //if(n = dynamic_cast(ob)) + //{ + // CGI->state->map->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 = gh->gs->map->getHero(hid,0); + if(position<0) + { + for(unsigned i=0;iartifacts.size();i++) + { + if(!h->artifacts[i]) + { + h->artifacts[i] = artid; + return; + } + } + h->artifacts.push_back(artid); + return; + } + else + { + if(h->artifWorn[position]) //slot is occupied + { + giveHeroArtifact(h->artifWorn[position],hid,-1); + } + h->artifWorn[position] = artid; + } +} + +void CScriptCallback::startBattle(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2) //use hero=NULL for no hero +{ + boost::thread(boost::bind(&CGameHandler::startBattle,gh,*(CCreatureSet *)army1,*(CCreatureSet *)army2,tile,(CGHeroInstance *)hero1,(CGHeroInstance *)hero2)); +} +void CScriptCallback::startBattle(int heroID, CCreatureSet army, int3 tile) //for hero<=>neutral army +{ + CGHeroInstance* h = const_cast(getHero(heroID)); + startBattle(&h->army,&army,tile,h,NULL); + //gh->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); +// +// 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; +} diff --git a/server/CScriptCallback.h b/server/CScriptCallback.h new file mode 100644 index 000000000..a4ee7794f --- /dev/null +++ b/server/CScriptCallback.h @@ -0,0 +1,64 @@ +#pragma once +#include "../global.h" +#include +class CVCMIServer; +class CGameHandler; +class SComponent; +class CSelectableComponent; +class IChosen; +class CCreatureSet; +class CGHeroInstance; +class CGObjectInstance; +class CGHeroInstance; +class CGTownInstance; +class CGameState; +struct lua_State; +struct MetaString; +struct InfoWindow; +struct ShowInInfobox; +class CScriptCallback +{ + CScriptCallback(void); +public: + ~CScriptCallback(void); + CGameHandler *gh; + + //get info + static int3 getPos(CGObjectInstance * ob); + int getHeroOwner(int heroID); + int getSelectedHero(); + int getDate(int mode=0); + const CGObjectInstance* getObj(int objid); + const CGHeroInstance* getHero(int objid); + const CGTownInstance* getTown(int objid); + + //do sth + void setBlockVis(int objid, bool bv); + void setOwner(int objid, ui8 owner); + void setHoverName(int objid, MetaString * name); + void changePrimSkill(int ID, int which, int val, bool abs=false); + void showInfoDialog(InfoWindow *iw); + void showSelDialog(int player, std::string text, std::vector*components, IChosen * asker); + void giveResource(int player, int which, int val); + void showCompInfo(ShowInInfobox * comp); + void heroVisitCastle(int obj, int heroID); + void stopHeroVisitCastle(int obj, int heroID); + void giveHeroArtifact(int artid, int hid, int position); //pos==-1 - first free slot in backpack + void startBattle(const CCreatureSet * army1, const CCreatureSet * army2, int3 tile, const CGHeroInstance *hero1, const CGHeroInstance *hero2); //use hero=NULL for no hero + void startBattle(int heroID, CCreatureSet army, int3 tile); //for hero<=>neutral army + + //friends + friend class CGameHandler; +}; +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 class CGameHandler; +}; \ No newline at end of file diff --git a/server/CVCMIServer.cpp b/server/CVCMIServer.cpp new file mode 100644 index 000000000..f69159bbe --- /dev/null +++ b/server/CVCMIServer.cpp @@ -0,0 +1,142 @@ +#include +#include +#include +#include "../global.h" +#include "../lib/Connection.h" +#include "zlib.h" +#ifndef __GNUC__ +#include +#endif +#include "CVCMIServer.h" +#include +#include +#include "../StartInfo.h" +#include "../map.h" +#include "../hch/CLodHandler.h" +#include "../lib/VCMI_Lib.h" +#include "CGameHandler.h" +std::string NAME = NAME_VER + std::string(" (server)"); +using boost::asio::ip::tcp; +using namespace boost; +using namespace boost::asio; +using namespace boost::asio::ip; + +bool end2 = false; + +CVCMIServer::CVCMIServer() +: io(new io_service()), acceptor(new tcp::acceptor(*io, tcp::endpoint(tcp::v4(), 3030))) +{ +} +CVCMIServer::~CVCMIServer() +{ + //delete io; + //delete acceptor; +} + +void CVCMIServer::newGame(CConnection *c) +{ + CGameHandler gh; + boost::system::error_code error; + StartInfo *si = new StartInfo; + ui8 clients; + *c >> clients; //how many clients should be connected - TODO: support more than one + *c >> *si; //get start options + int problem; +#ifdef _MSC_VER + FILE *f; + problem = fopen_s(&f,si->mapname.c_str(),"r"); +#else + FILE * f = fopen(si->mapname.c_str(),"r"); + problem = !f; +#endif + if(problem) + { + *c << ui8(problem); //WRONG! + return; + } + else + { + fclose(f); + *c << ui8(0); //OK! + } + + gh.init(si,rand()); + + CConnection* cc; //tcp::socket * ss; + for(int i=0; iio_service()); + acceptor->accept(*s,error); + if(error) //retry + { + std::cout<<"Cannot establish connection - retrying..." << std::endl; + i--; + continue; + } + cc = new CConnection(s,NAME,std::cout); + } + gh.conns.insert(cc); + } + + gh.run(); +} +void CVCMIServer::start() +{ + boost::system::error_code error; + std::cout<<"Listening for connections at port " << acceptor->local_endpoint().port() << std::endl; + tcp::socket * s = new tcp::socket(acceptor->io_service()); + acceptor->accept(*s,error); + if (error) + { + std::cout<<"Got connection but there is an error " << std::endl; + return; + } + CConnection *connection = new CConnection(s,NAME,std::cout); + std::cout<<"Got connection!" << std::endl; + while(!end2) + { + uint8_t mode; + *connection >> mode; + switch (mode) + { + case 0: + connection->socket->close(); + exit(0); + break; + case 1: + connection->socket->close(); + return; + break; + case 2: + newGame(connection); + break; + } + } +} + +#ifndef __GNUC__ +int _tmain(int argc, _TCHAR* argv[]) +#else +int main(int argc, _TCHAR* argv[]) +#endif +{ + CLodHandler h3bmp; + h3bmp.init("Data\\H3bitmap.lod","Data"); + initDLL(&h3bmp); + srand ( (unsigned int)time(NULL) ); + try + { + io_service io_service; + CVCMIServer server; + while(!end2) + server.start(); + io_service.run(); + } HANDLE_EXCEPTION + return 0; +} diff --git a/server/CVCMIServer.h b/server/CVCMIServer.h new file mode 100644 index 000000000..9263988ab --- /dev/null +++ b/server/CVCMIServer.h @@ -0,0 +1,32 @@ +#pragma once +#include "../global.h" +#include +class CConnection; +namespace boost +{ + namespace asio + { + class io_service; + namespace ip + { + class tcp; + } + template class socket_acceptor_service; + template + class basic_socket_acceptor; + } +}; + +class CVCMIServer +{ + boost::asio::io_service *io; + boost::asio::basic_socket_acceptor > * acceptor; + std::map connections; + std::set conns; +public: + CVCMIServer(); + ~CVCMIServer(); + void setUpConnection(CConnection *c, std::string mapname, si32 checksum); + void newGame(CConnection *c); + void start(); +}; diff --git a/server/Makefile.am b/server/Makefile.am new file mode 100644 index 000000000..464f9b0ac --- /dev/null +++ b/server/Makefile.am @@ -0,0 +1,16 @@ +AUTOMAKE_OPTIONS=foreign +bin_PROGRAMS = vcmiserver +vcmiserver_LDADD = $(BOOST_SYSTEM_LIB) $(BOOST_FILESYSTEM_LIB) $(BOOST_THREAD_LIB) +#vcmi_LDADD = $(BOOST_SYSTEM_LIB) $(BOOST_FILESYSTEM_LIB) $(BOOST_THREAD_LIB) +#AM_CXXFLAGS = $(BOOST_CPPFLAGS) +vcmiserver_LDFLAGS = -L$(top_builddir)/lib +vcmiserver_LDADD += -lvcmi +vcmiserver_SOURCES = \ +./CGameHandler.cpp \ +../CLua.cpp \ +./CScriptCallback.cpp \ +./CVCMIServer.cpp \ +./CGameHandler.h \ +../CLua.h \ +./CScriptCallback.h \ +./CVCMIServer.h diff --git a/tools/Defopruj/wyprujdef.vcproj b/server/VCMI_server.vcproj similarity index 54% rename from tools/Defopruj/wyprujdef.vcproj rename to server/VCMI_server.vcproj index 04c7e480c..34dd0ad1d 100644 --- a/tools/Defopruj/wyprujdef.vcproj +++ b/server/VCMI_server.vcproj @@ -2,10 +2,9 @@ @@ -18,11 +17,10 @@ + + + + + + + + + + + + + + + + + + + - - - - - - + + @@ -230,18 +271,20 @@ UniqueIdentifier="{93995380-89BD-4b04-88EB-625FBE52EBFB}" > + + + + - - - - diff --git a/stdafx.h b/stdafx.h index 358187380..b6ef3cd8a 100644 --- a/stdafx.h +++ b/stdafx.h @@ -14,6 +14,7 @@ #endif #include #include +#include #include #include #include "global.h" diff --git a/timeHandler.h b/timeHandler.h index a230b3dbe..e6656ac9f 100644 --- a/timeHandler.h +++ b/timeHandler.h @@ -6,7 +6,7 @@ class timeHandler { public: clock_t start, last, mem; - timeHandler():start(clock()){last=0;mem=0;}; + timeHandler():start(clock()){last=clock();mem=0;}; long getDif(){long ret=clock()-last;last=clock();return ret;}; void update(){last=clock();}; void remember(){mem=clock();}; diff --git a/tools/Defopruj/AssemblyInfo.cpp b/tools/Defopruj/AssemblyInfo.cpp deleted file mode 100644 index 0557e2815..000000000 --- a/tools/Defopruj/AssemblyInfo.cpp +++ /dev/null @@ -1,38 +0,0 @@ -using namespace System; -using namespace System::Reflection; -using namespace System::Runtime::CompilerServices; -using namespace System::Runtime::InteropServices; -using namespace System::Security::Permissions; - -// -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -// -[assembly:AssemblyTitleAttribute("wyprujdef")]; -[assembly:AssemblyDescriptionAttribute("Cudowne narzêdzie pozwalaj¹ce w szybkimczasie wypruæ defy.")]; -[assembly:AssemblyConfigurationAttribute("")]; -[assembly:AssemblyCompanyAttribute("VCMI Team")]; -[assembly:AssemblyProductAttribute("wyprujdef")]; -[assembly:AssemblyCopyrightAttribute("Copyright (c) 2008")]; -[assembly:AssemblyTrademarkAttribute("")]; -[assembly:AssemblyCultureAttribute("")]; - -// -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the value or you can default the Revision and Build Numbers -// by using the '*' as shown below: - -[assembly:AssemblyVersionAttribute("1.0.*")]; - -[assembly:ComVisible(false)]; - -[assembly:CLSCompliantAttribute(true)]; - -[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)]; diff --git a/tools/Defopruj/CDefHandler.cpp b/tools/Defopruj/CDefHandler.cpp deleted file mode 100644 index bf1376c19..000000000 Binary files a/tools/Defopruj/CDefHandler.cpp and /dev/null differ diff --git a/tools/Defopruj/CDefHandler.h b/tools/Defopruj/CDefHandler.h deleted file mode 100644 index c084827cf..000000000 Binary files a/tools/Defopruj/CDefHandler.h and /dev/null differ diff --git a/tools/Defopruj/Oknopruj.cpp b/tools/Defopruj/Oknopruj.cpp deleted file mode 100644 index 19cb20e38..000000000 --- a/tools/Defopruj/Oknopruj.cpp +++ /dev/null @@ -1,62 +0,0 @@ -#include "Oknopruj.h" -#include "tchar.h" -#include "CDefHandler.h" -#include "Oknopruj.h" -#include -#include -using namespace System; -using namespace wyprujdef; -std::string Oknopruj::ToString(System::String^ src) -{ - std::string dest; - using namespace System::Runtime::InteropServices; - const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(src)).ToPointer(); - dest = chars; - Marshal::FreeHGlobal(IntPtr((void*)chars)); - return dest; -} -void Oknopruj::wyprujDefyZPlikow(array ^pliki) -{ - progressBar1->Maximum = pliki->Length; - progressBar1->Value = 0; - CDefHandler * defik; - for each(String ^ plik in pliki) - { - progressBar1->Value++; - if(!((plik->EndsWith(".def")||(plik->EndsWith(".DEF"))))) - continue; - defik = new CDefHandler(); - defik->openDef(ToString(plik)); - - int to=1; - std::string bmpname; - if (rall->Checked) - { - to = defik->ourImages.size(); - } - - for (int i=0;iSubstring(0,plik->Length-4)) << '_' << i << "_.bmp"; - SDL_SaveBMP(defik->ourImages[i].bitmap,oss.str().c_str()); - } - - - delete defik; - } -} -[STAThreadAttribute] -int WinMain() -{ - String^ folder = (System::IO::Directory::GetCurrentDirectory()); - array^ pliki = IO::Directory::GetFiles(folder); - Oknopruj ^ okno = gcnew Oknopruj(); - Application::Run(okno); - exit(0); -} - -void Oknopruj::runSearch() -{ - wyprujDefyZPlikow(IO::Directory::GetFiles(pathBox->Text)); -}// wyprujdef.cpp : main project file. diff --git a/tools/Defopruj/Oknopruj.h b/tools/Defopruj/Oknopruj.h deleted file mode 100644 index a4bd45b1c..000000000 --- a/tools/Defopruj/Oknopruj.h +++ /dev/null @@ -1,235 +0,0 @@ -#pragma once -#include -using namespace System; -using namespace System::ComponentModel; -using namespace System::Collections; -using namespace System::Windows::Forms; -using namespace System::Data; -using namespace System::Drawing; - - -namespace wyprujdef { - - /// - /// Summary for Oknopruj - /// - /// WARNING: If you change the name of this class, you will need to change the - /// 'Resource File Name' property for the managed resource compiler tool - /// associated with all .resx files this class depends on. Otherwise, - /// the designers will not be able to interact properly with localized - /// resources associated with this form. - /// - public ref class Oknopruj : public System::Windows::Forms::Form - { - public: - - static std::string ToString(System::String^ src); - void runSearch(); - void wyprujDefyZPlikow(array ^pliki); - - Oknopruj(void) - { - InitializeComponent(); - } - - protected: - /// - /// Clean up any resources being used. - /// - ~Oknopruj() - { - if (components) - { - delete components; - } - } - private: System::Windows::Forms::MenuStrip^ menuStrip1; - protected: - private: System::Windows::Forms::ToolStripMenuItem^ rUNToolStripMenuItem; - private: System::Windows::Forms::ToolStripMenuItem^ getProgramDirToolStripMenuItem; - private: System::Windows::Forms::ToolStripMenuItem^ browseToolStripMenuItem; - - private: System::Windows::Forms::ToolStripMenuItem^ vCMIHomepageToolStripMenuItem; - private: System::Windows::Forms::ProgressBar^ progressBar1; - private: System::Windows::Forms::TextBox^ pathBox; - - private: System::Windows::Forms::Label^ label1; - private: System::DirectoryServices::DirectorySearcher^ directorySearcher1; - private: System::Windows::Forms::FolderBrowserDialog^ folderBrowserDialog1; - private: System::Windows::Forms::RadioButton^ rfirst; - private: System::Windows::Forms::RadioButton^ rall; - - - - - - private: - /// - /// Required designer variable. - /// - System::ComponentModel::Container ^components; - -#pragma region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - void InitializeComponent(void) - { - this->menuStrip1 = (gcnew System::Windows::Forms::MenuStrip()); - this->rUNToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); - this->getProgramDirToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); - this->browseToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); - this->vCMIHomepageToolStripMenuItem = (gcnew System::Windows::Forms::ToolStripMenuItem()); - this->progressBar1 = (gcnew System::Windows::Forms::ProgressBar()); - this->pathBox = (gcnew System::Windows::Forms::TextBox()); - this->label1 = (gcnew System::Windows::Forms::Label()); - this->directorySearcher1 = (gcnew System::DirectoryServices::DirectorySearcher()); - this->folderBrowserDialog1 = (gcnew System::Windows::Forms::FolderBrowserDialog()); - this->rfirst = (gcnew System::Windows::Forms::RadioButton()); - this->rall = (gcnew System::Windows::Forms::RadioButton()); - this->menuStrip1->SuspendLayout(); - this->SuspendLayout(); - // - // menuStrip1 - // - this->menuStrip1->Items->AddRange(gcnew cli::array< System::Windows::Forms::ToolStripItem^ >(4) {this->rUNToolStripMenuItem, - this->getProgramDirToolStripMenuItem, this->browseToolStripMenuItem, this->vCMIHomepageToolStripMenuItem}); - this->menuStrip1->Location = System::Drawing::Point(0, 0); - this->menuStrip1->Name = L"menuStrip1"; - this->menuStrip1->Size = System::Drawing::Size(308, 24); - this->menuStrip1->TabIndex = 0; - this->menuStrip1->Text = L"menuStrip1"; - // - // rUNToolStripMenuItem - // - this->rUNToolStripMenuItem->Name = L"rUNToolStripMenuItem"; - this->rUNToolStripMenuItem->Size = System::Drawing::Size(44, 20); - this->rUNToolStripMenuItem->Text = L"RUN!"; - this->rUNToolStripMenuItem->Click += gcnew System::EventHandler(this, &Oknopruj::rUNToolStripMenuItem_Click); - // - // getProgramDirToolStripMenuItem - // - this->getProgramDirToolStripMenuItem->Name = L"getProgramDirToolStripMenuItem"; - this->getProgramDirToolStripMenuItem->Size = System::Drawing::Size(94, 20); - this->getProgramDirToolStripMenuItem->Text = L"Get program dir"; - this->getProgramDirToolStripMenuItem->Click += gcnew System::EventHandler(this, &Oknopruj::getProgramDirToolStripMenuItem_Click); - // - // browseToolStripMenuItem - // - this->browseToolStripMenuItem->Name = L"browseToolStripMenuItem"; - this->browseToolStripMenuItem->Size = System::Drawing::Size(66, 20); - this->browseToolStripMenuItem->Text = L"Browse..."; - this->browseToolStripMenuItem->Click += gcnew System::EventHandler(this, &Oknopruj::browseToolStripMenuItem_Click); - // - // vCMIHomepageToolStripMenuItem - // - this->vCMIHomepageToolStripMenuItem->Name = L"vCMIHomepageToolStripMenuItem"; - this->vCMIHomepageToolStripMenuItem->Size = System::Drawing::Size(97, 20); - this->vCMIHomepageToolStripMenuItem->Text = L"VCMI homepage"; - this->vCMIHomepageToolStripMenuItem->Click += gcnew System::EventHandler(this, &Oknopruj::vCMIHomepageToolStripMenuItem_Click); - // - // progressBar1 - // - this->progressBar1->Location = System::Drawing::Point(12, 96); - this->progressBar1->Name = L"progressBar1"; - this->progressBar1->Size = System::Drawing::Size(284, 14); - this->progressBar1->TabIndex = 1; - // - // pathBox - // - this->pathBox->Location = System::Drawing::Point(12, 50); - this->pathBox->Name = L"pathBox"; - this->pathBox->Size = System::Drawing::Size(276, 20); - this->pathBox->TabIndex = 2; - // - // label1 - // - this->label1->AutoSize = true; - this->label1->Location = System::Drawing::Point(137, 34); - this->label1->Name = L"label1"; - this->label1->Size = System::Drawing::Size(32, 13); - this->label1->TabIndex = 3; - this->label1->Text = L"Path:"; - // - // directorySearcher1 - // - this->directorySearcher1->ClientTimeout = System::TimeSpan::Parse(L"-00:00:01"); - this->directorySearcher1->ServerPageTimeLimit = System::TimeSpan::Parse(L"-00:00:01"); - this->directorySearcher1->ServerTimeLimit = System::TimeSpan::Parse(L"-00:00:01"); - // - // rfirst - // - this->rfirst->AutoSize = true; - this->rfirst->Checked = true; - this->rfirst->Location = System::Drawing::Point(12, 73); - this->rfirst->Name = L"rfirst"; - this->rfirst->Size = System::Drawing::Size(128, 17); - this->rfirst->TabIndex = 4; - this->rfirst->TabStop = true; - this->rfirst->Text = L"Extract only first frame"; - this->rfirst->UseVisualStyleBackColor = true; - // - // rall - // - this->rall->AutoSize = true; - this->rall->Location = System::Drawing::Point(183, 73); - this->rall->Name = L"rall"; - this->rall->Size = System::Drawing::Size(105, 17); - this->rall->TabIndex = 4; - this->rall->Text = L"Extract all frames"; - this->rall->UseVisualStyleBackColor = true; - // - // Oknopruj - // - this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); - this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; - this->ClientSize = System::Drawing::Size(308, 120); - this->Controls->Add(this->rall); - this->Controls->Add(this->rfirst); - this->Controls->Add(this->label1); - this->Controls->Add(this->pathBox); - this->Controls->Add(this->progressBar1); - this->Controls->Add(this->menuStrip1); - this->MainMenuStrip = this->menuStrip1; - this->MaximizeBox = false; - this->Name = L"Oknopruj"; - this->ShowIcon = false; - this->Text = L"Defopruj 1.0"; - this->Load += gcnew System::EventHandler(this, &Oknopruj::Oknopruj_Load); - this->menuStrip1->ResumeLayout(false); - this->menuStrip1->PerformLayout(); - this->ResumeLayout(false); - this->PerformLayout(); - - } -#pragma endregion -private: System::Void rUNToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) - { - runSearch(); - } -private: System::Void Oknopruj_Load(System::Object^ sender, System::EventArgs^ e) - { - pathBox->Text = IO::Directory::GetCurrentDirectory(); - } -private: System::Void getProgramDirToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) - { - pathBox->Text = IO::Directory::GetCurrentDirectory(); - } -private: System::Void browseToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) - { - if (folderBrowserDialog1->ShowDialog()==System::Windows::Forms::DialogResult::OK) - { - pathBox->Text = folderBrowserDialog1->SelectedPath; - } - } -private: System::Void aboutToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) - { - - } -private: System::Void vCMIHomepageToolStripMenuItem_Click(System::Object^ sender, System::EventArgs^ e) - { - Diagnostics::Process::Start(gcnew String("http://antypika.aplus.pl/vcmi")); - } -}; -} diff --git a/tools/Defsorter/Form1.Designer.cs b/tools/Defsorter/Form1.Designer.cs deleted file mode 100644 index 3fc634049..000000000 --- a/tools/Defsorter/Form1.Designer.cs +++ /dev/null @@ -1,99 +0,0 @@ -namespace DefSorter -{ - partial class Form1 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.button1 = new System.Windows.Forms.Button(); - this.label1 = new System.Windows.Forms.Label(); - this.label2 = new System.Windows.Forms.Label(); - this.progressBar1 = new System.Windows.Forms.ProgressBar(); - this.SuspendLayout(); - // - // button1 - // - this.button1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.button1.Location = new System.Drawing.Point(41, 35); - this.button1.Name = "button1"; - this.button1.Size = new System.Drawing.Size(138, 27); - this.button1.TabIndex = 0; - this.button1.Text = "Posortuj defy!"; - this.button1.UseVisualStyleBackColor = true; - this.button1.Click += new System.EventHandler(this.button1_Click); - // - // label1 - // - this.label1.AutoSize = true; - this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label1.Location = new System.Drawing.Point(12, 9); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(114, 18); - this.label1.TabIndex = 1; - this.label1.Text = "Defów wykryto: "; - // - // label2 - // - this.label2.AutoSize = true; - this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 11F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label2.Location = new System.Drawing.Point(146, 9); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(52, 18); - this.label2.TabIndex = 2; - this.label2.Text = "XXXX"; - // - // progressBar1 - // - this.progressBar1.Location = new System.Drawing.Point(4, 73); - this.progressBar1.Name = "progressBar1"; - this.progressBar1.Size = new System.Drawing.Size(202, 19); - this.progressBar1.TabIndex = 3; - // - // Form1 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(210, 97); - this.Controls.Add(this.progressBar1); - this.Controls.Add(this.label2); - this.Controls.Add(this.label1); - this.Controls.Add(this.button1); - this.Name = "Form1"; - this.Text = "Def sorter by Tow"; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Button button1; - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.ProgressBar progressBar1; - } -} - diff --git a/tools/Defsorter/Form1.cs b/tools/Defsorter/Form1.cs deleted file mode 100644 index 529a3f06f..000000000 --- a/tools/Defsorter/Form1.cs +++ /dev/null @@ -1,242 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; -using System.IO; -using System.Collections; -namespace DefSorter -{ - public partial class Form1 : Form - { - int bledy; - public Form1() - { - InitializeComponent(); - int ile = 0; - bledy = 0; - string[] pliczki = Directory.GetFiles(Directory.GetCurrentDirectory()); - foreach (string ss in pliczki) - { - if ((!(ss.EndsWith(".DEF")))&&(!(ss.EndsWith(".def")))) - continue; - else ile++; - } - label2.Text = ile.ToString(); - progressBar1.Visible = false; - } - - private void button1_Click(object sender, EventArgs e) - { - int s12 = 0, s13 = 0, s14 = 0, s15 = 0, s16 = 0, s17 = 0, s18 = 0, - s19 = 0, s20 = 0, s21 = 0; - Form2 pozegnanie = new Form2(); - ArrayList defy = new ArrayList(); - string[] pliczki = Directory.GetFiles(Directory.GetCurrentDirectory(),"*.DEF"); - progressBar1.Visible = true; - progressBar1.Minimum = progressBar1.Value = 0; - progressBar1.Maximum = Convert.ToInt32(label2.Text); - foreach (string ss in pliczki) - { - if ((!(ss.EndsWith(".DEF"))) && (!(ss.EndsWith(".def")))) - continue; - FileStream czytacz = File.OpenRead(ss); - int coTo = czytacz.ReadByte(); - czytacz.Close(); - int poczP = ss.LastIndexOf('\\'); - string nazwa = ss.Substring(poczP + 1, ss.Length - poczP - 1); - try - { - switch (coTo) - { - case 64: - if (!Directory.Exists("40Spell")) - Directory.CreateDirectory("40Spell"); - File.Copy(ss, "40Spell\\" + nazwa); - s12++; - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSK")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSK", "40Spell\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSK"); - } - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSG")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSG", "40Spell\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSG"); - } - break; - case 65: - if (!Directory.Exists("41SpriteDef")) - Directory.CreateDirectory("41SpriteDef"); - File.Copy(ss, "41SpriteDef\\" + nazwa); - s13++; - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSK")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSK", "41SpriteDef\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSK"); - } - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSG")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSG", "41SpriteDef\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSG"); - } - break; - case 66: - if (!Directory.Exists("42Creature")) - Directory.CreateDirectory("42Creature"); - File.Copy(ss, "42Creature\\" + nazwa); - s14++; - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSK")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSK", "42Creature\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSK"); - } - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSG")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSG", "42Creature\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSG"); - } - break; - case 67: - if (!Directory.Exists("43AdvObject")) - Directory.CreateDirectory("43AdvObject"); - File.Copy(ss, "43AdvObject\\" + nazwa); - s15++; - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSK")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSK", "43AdvObject\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSK"); - } - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSG")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSG", "43AdvObject\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSG"); - } - break; - case 68: - if (!Directory.Exists("44Hero")) - Directory.CreateDirectory("44Hero"); - File.Copy(ss, "44Hero\\" + nazwa); - s16++; - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSK")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSK", "44Hero\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSK"); - } - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSG")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSG", "44Hero\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSG"); - } - break; - case 69: - if (!Directory.Exists("45Terrain")) - Directory.CreateDirectory("45Terrain"); - File.Copy(ss, "45Terrain\\" + nazwa); - s17++; - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4)+".MSK")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4)+".MSK","45Terrain\\"+nazwa.Substring(0, nazwa.Length - 4)+".MSK"); - } - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4)+".MSG")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4)+".MSG","45Terrain\\"+nazwa.Substring(0, nazwa.Length - 4)+".MSG"); - } - break; - case 70: - if (!Directory.Exists("46Cursor")) - Directory.CreateDirectory("46Cursor"); - File.Copy(ss, "46Cursor\\" + nazwa); - s18++; - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSK")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSK", "46Cursor\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSK"); - } - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSG")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSG", "46Cursor\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSG"); - } - break; - case 71: - if (!Directory.Exists("47Interface")) - Directory.CreateDirectory("47Interface"); - File.Copy(ss, "47Interface\\" + nazwa); - s19++; - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSK")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSK", "47Interface\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSK"); - } - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSG")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSG", "47Interface\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSG"); - } - break; - case 72: - if (!Directory.Exists("48Spriteframe")) - Directory.CreateDirectory("48Spriteframe"); - File.Copy(ss, "48Spriteframe\\" + nazwa); - s20++; - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSK")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSK", "48Spriteframe\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSK"); - } - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSG")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSG", "48Spriteframe\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSG"); - } - break; - case 73: - if (!Directory.Exists("49CombatHero")) - Directory.CreateDirectory("49CombatHero"); - File.Copy(ss, "49CombatHero\\" + nazwa); - s21++; - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSK")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSK", "49CombatHero\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSK"); - } - if (File.Exists(nazwa.Substring(0, nazwa.Length - 4) + ".MSG")) - { - File.Copy(nazwa.Substring(0, nazwa.Length - 4) + ".MSG", "49CombatHero\\" + nazwa.Substring(0, nazwa.Length - 4) + ".MSG"); - } - break; - } - } - catch (Exception ee) - { - bledy++; - Form3 niedobrze = new Form3(); - niedobrze.textBox1.Text += ee.Message; - DialogResult res = niedobrze.ShowDialog(); - switch (res) - { - case DialogResult.Ignore: - break; - case DialogResult.Cancel: - try { Directory.Delete("40Spell"); }catch(Exception){}; - try { Directory.Delete("41SpriteDef"); }catch(Exception){}; - try { Directory.Delete("42Creature"); }catch(Exception){}; - try { Directory.Delete("43AdvObject"); }catch(Exception){}; - try { Directory.Delete("45Terrain"); }catch(Exception){}; - try { Directory.Delete("46Cursor"); }catch(Exception){}; - try { Directory.Delete("47Interface"); }catch(Exception){}; - try { Directory.Delete("48Spriteframe"); }catch(Exception){}; - try { Directory.Delete("49CombatHero"); }catch(Exception){}; - Application.Exit(); - break; - } - } - progressBar1.Value++; - if (progressBar1.Value % 100 == 5) - this.Update(); - } - progressBar1.Visible = false; - pozegnanie.label12.Text = s12.ToString(); - pozegnanie.label13.Text = s13.ToString(); - pozegnanie.label14.Text = s14.ToString(); - pozegnanie.label15.Text = s15.ToString(); - pozegnanie.label16.Text = s16.ToString(); - pozegnanie.label17.Text = s17.ToString(); - pozegnanie.label18.Text = s18.ToString(); - pozegnanie.label19.Text = s19.ToString(); - pozegnanie.label20.Text = s20.ToString(); - pozegnanie.label21.Text = s21.ToString(); - pozegnanie.label34.Text = bledy.ToString(); - if (bledy == 0) - pozegnanie.label35.Text = ":)"; - pozegnanie.Show(); - pozegnanie.Activate(); - } - } -} \ No newline at end of file diff --git a/tools/Defsorter/Form2.Designer.cs b/tools/Defsorter/Form2.Designer.cs deleted file mode 100644 index bc700e17f..000000000 --- a/tools/Defsorter/Form2.Designer.cs +++ /dev/null @@ -1,517 +0,0 @@ -namespace DefSorter -{ - partial class Form2 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.label1 = new System.Windows.Forms.Label(); - this.label2 = new System.Windows.Forms.Label(); - this.label3 = new System.Windows.Forms.Label(); - this.label4 = new System.Windows.Forms.Label(); - this.label5 = new System.Windows.Forms.Label(); - this.label6 = new System.Windows.Forms.Label(); - this.label7 = new System.Windows.Forms.Label(); - this.label8 = new System.Windows.Forms.Label(); - this.label9 = new System.Windows.Forms.Label(); - this.label10 = new System.Windows.Forms.Label(); - this.label11 = new System.Windows.Forms.Label(); - this.label12 = new System.Windows.Forms.Label(); - this.label13 = new System.Windows.Forms.Label(); - this.label14 = new System.Windows.Forms.Label(); - this.label15 = new System.Windows.Forms.Label(); - this.label16 = new System.Windows.Forms.Label(); - this.label17 = new System.Windows.Forms.Label(); - this.label18 = new System.Windows.Forms.Label(); - this.label19 = new System.Windows.Forms.Label(); - this.label20 = new System.Windows.Forms.Label(); - this.label21 = new System.Windows.Forms.Label(); - this.label22 = new System.Windows.Forms.Label(); - this.label23 = new System.Windows.Forms.Label(); - this.label24 = new System.Windows.Forms.Label(); - this.label25 = new System.Windows.Forms.Label(); - this.label26 = new System.Windows.Forms.Label(); - this.label27 = new System.Windows.Forms.Label(); - this.label28 = new System.Windows.Forms.Label(); - this.label29 = new System.Windows.Forms.Label(); - this.label30 = new System.Windows.Forms.Label(); - this.label31 = new System.Windows.Forms.Label(); - this.label32 = new System.Windows.Forms.Label(); - this.button1 = new System.Windows.Forms.Button(); - this.label33 = new System.Windows.Forms.Label(); - this.label34 = new System.Windows.Forms.Label(); - this.label35 = new System.Windows.Forms.Label(); - this.SuspendLayout(); - // - // label1 - // - this.label1.AutoSize = true; - this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label1.Location = new System.Drawing.Point(12, 9); - this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(255, 17); - this.label1.TabIndex = 0; - this.label1.Text = "Szczęśliwie posortowano. Wg kategorii:"; - // - // label2 - // - this.label2.AutoSize = true; - this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label2.Location = new System.Drawing.Point(12, 26); - this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(59, 17); - this.label2.TabIndex = 1; - this.label2.Text = "40Spell:"; - // - // label3 - // - this.label3.AutoSize = true; - this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label3.Location = new System.Drawing.Point(12, 43); - this.label3.Name = "label3"; - this.label3.Size = new System.Drawing.Size(87, 17); - this.label3.TabIndex = 1; - this.label3.Text = "41SpriteDef:"; - // - // label4 - // - this.label4.AutoSize = true; - this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label4.Location = new System.Drawing.Point(12, 60); - this.label4.Name = "label4"; - this.label4.Size = new System.Drawing.Size(83, 17); - this.label4.TabIndex = 1; - this.label4.Text = "42Creature:"; - // - // label5 - // - this.label5.AutoSize = true; - this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label5.Location = new System.Drawing.Point(12, 77); - this.label5.Name = "label5"; - this.label5.Size = new System.Drawing.Size(93, 17); - this.label5.TabIndex = 1; - this.label5.Text = "43AdvObject:"; - // - // label6 - // - this.label6.AutoSize = true; - this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label6.Location = new System.Drawing.Point(12, 94); - this.label6.Name = "label6"; - this.label6.Size = new System.Drawing.Size(59, 17); - this.label6.TabIndex = 1; - this.label6.Text = "44Hero:"; - // - // label7 - // - this.label7.AutoSize = true; - this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label7.Location = new System.Drawing.Point(12, 111); - this.label7.Name = "label7"; - this.label7.Size = new System.Drawing.Size(74, 17); - this.label7.TabIndex = 1; - this.label7.Text = "45Terrain:"; - // - // label8 - // - this.label8.AutoSize = true; - this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label8.Location = new System.Drawing.Point(12, 128); - this.label8.Name = "label8"; - this.label8.Size = new System.Drawing.Size(70, 17); - this.label8.TabIndex = 1; - this.label8.Text = "46Cursor:"; - // - // label9 - // - this.label9.AutoSize = true; - this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label9.Location = new System.Drawing.Point(12, 145); - this.label9.Name = "label9"; - this.label9.Size = new System.Drawing.Size(83, 17); - this.label9.TabIndex = 1; - this.label9.Text = "47Interface:"; - // - // label10 - // - this.label10.AutoSize = true; - this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label10.Location = new System.Drawing.Point(12, 162); - this.label10.Name = "label10"; - this.label10.Size = new System.Drawing.Size(101, 17); - this.label10.TabIndex = 1; - this.label10.Text = "48Spriteframe:"; - // - // label11 - // - this.label11.AutoSize = true; - this.label11.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label11.Location = new System.Drawing.Point(12, 179); - this.label11.Name = "label11"; - this.label11.Size = new System.Drawing.Size(107, 17); - this.label11.TabIndex = 1; - this.label11.Text = "49CombatHero:"; - this.label11.Click += new System.EventHandler(this.label11_Click); - // - // label12 - // - this.label12.AutoSize = true; - this.label12.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label12.Location = new System.Drawing.Point(125, 26); - this.label12.Name = "label12"; - this.label12.Size = new System.Drawing.Size(48, 17); - this.label12.TabIndex = 2; - this.label12.Text = "XXXX"; - // - // label13 - // - this.label13.AutoSize = true; - this.label13.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label13.Location = new System.Drawing.Point(125, 43); - this.label13.Name = "label13"; - this.label13.Size = new System.Drawing.Size(48, 17); - this.label13.TabIndex = 2; - this.label13.Text = "XXXX"; - // - // label14 - // - this.label14.AutoSize = true; - this.label14.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label14.Location = new System.Drawing.Point(125, 60); - this.label14.Name = "label14"; - this.label14.Size = new System.Drawing.Size(48, 17); - this.label14.TabIndex = 2; - this.label14.Text = "XXXX"; - // - // label15 - // - this.label15.AutoSize = true; - this.label15.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label15.Location = new System.Drawing.Point(125, 77); - this.label15.Name = "label15"; - this.label15.Size = new System.Drawing.Size(48, 17); - this.label15.TabIndex = 2; - this.label15.Text = "XXXX"; - // - // label16 - // - this.label16.AutoSize = true; - this.label16.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label16.Location = new System.Drawing.Point(125, 94); - this.label16.Name = "label16"; - this.label16.Size = new System.Drawing.Size(48, 17); - this.label16.TabIndex = 2; - this.label16.Text = "XXXX"; - // - // label17 - // - this.label17.AutoSize = true; - this.label17.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label17.Location = new System.Drawing.Point(125, 111); - this.label17.Name = "label17"; - this.label17.Size = new System.Drawing.Size(48, 17); - this.label17.TabIndex = 2; - this.label17.Text = "XXXX"; - // - // label18 - // - this.label18.AutoSize = true; - this.label18.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label18.Location = new System.Drawing.Point(125, 128); - this.label18.Name = "label18"; - this.label18.Size = new System.Drawing.Size(48, 17); - this.label18.TabIndex = 2; - this.label18.Text = "XXXX"; - // - // label19 - // - this.label19.AutoSize = true; - this.label19.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label19.Location = new System.Drawing.Point(125, 145); - this.label19.Name = "label19"; - this.label19.Size = new System.Drawing.Size(48, 17); - this.label19.TabIndex = 2; - this.label19.Text = "XXXX"; - // - // label20 - // - this.label20.AutoSize = true; - this.label20.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label20.Location = new System.Drawing.Point(125, 162); - this.label20.Name = "label20"; - this.label20.Size = new System.Drawing.Size(48, 17); - this.label20.TabIndex = 2; - this.label20.Text = "XXXX"; - // - // label21 - // - this.label21.AutoSize = true; - this.label21.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label21.Location = new System.Drawing.Point(125, 179); - this.label21.Name = "label21"; - this.label21.Size = new System.Drawing.Size(48, 17); - this.label21.TabIndex = 2; - this.label21.Text = "XXXX"; - // - // label22 - // - this.label22.AutoSize = true; - this.label22.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label22.Location = new System.Drawing.Point(179, 26); - this.label22.Name = "label22"; - this.label22.Size = new System.Drawing.Size(49, 17); - this.label22.TabIndex = 3; - this.label22.Text = "defów."; - // - // label23 - // - this.label23.AutoSize = true; - this.label23.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label23.Location = new System.Drawing.Point(179, 43); - this.label23.Name = "label23"; - this.label23.Size = new System.Drawing.Size(49, 17); - this.label23.TabIndex = 3; - this.label23.Text = "defów."; - // - // label24 - // - this.label24.AutoSize = true; - this.label24.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label24.Location = new System.Drawing.Point(179, 60); - this.label24.Name = "label24"; - this.label24.Size = new System.Drawing.Size(49, 17); - this.label24.TabIndex = 3; - this.label24.Text = "defów."; - // - // label25 - // - this.label25.AutoSize = true; - this.label25.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label25.Location = new System.Drawing.Point(179, 77); - this.label25.Name = "label25"; - this.label25.Size = new System.Drawing.Size(49, 17); - this.label25.TabIndex = 3; - this.label25.Text = "defów."; - // - // label26 - // - this.label26.AutoSize = true; - this.label26.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label26.Location = new System.Drawing.Point(179, 94); - this.label26.Name = "label26"; - this.label26.Size = new System.Drawing.Size(49, 17); - this.label26.TabIndex = 3; - this.label26.Text = "defów."; - // - // label27 - // - this.label27.AutoSize = true; - this.label27.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label27.Location = new System.Drawing.Point(179, 111); - this.label27.Name = "label27"; - this.label27.Size = new System.Drawing.Size(49, 17); - this.label27.TabIndex = 3; - this.label27.Text = "defów."; - // - // label28 - // - this.label28.AutoSize = true; - this.label28.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label28.Location = new System.Drawing.Point(179, 128); - this.label28.Name = "label28"; - this.label28.Size = new System.Drawing.Size(49, 17); - this.label28.TabIndex = 3; - this.label28.Text = "defów."; - // - // label29 - // - this.label29.AutoSize = true; - this.label29.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label29.Location = new System.Drawing.Point(179, 145); - this.label29.Name = "label29"; - this.label29.Size = new System.Drawing.Size(49, 17); - this.label29.TabIndex = 3; - this.label29.Text = "defów."; - // - // label30 - // - this.label30.AutoSize = true; - this.label30.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label30.Location = new System.Drawing.Point(179, 162); - this.label30.Name = "label30"; - this.label30.Size = new System.Drawing.Size(49, 17); - this.label30.TabIndex = 3; - this.label30.Text = "defów."; - // - // label31 - // - this.label31.AutoSize = true; - this.label31.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label31.Location = new System.Drawing.Point(179, 179); - this.label31.Name = "label31"; - this.label31.Size = new System.Drawing.Size(49, 17); - this.label31.TabIndex = 3; - this.label31.Text = "defów."; - // - // label32 - // - this.label32.AutoSize = true; - this.label32.Location = new System.Drawing.Point(12, 221); - this.label32.Name = "label32"; - this.label32.Size = new System.Drawing.Size(258, 13); - this.label32.TabIndex = 4; - this.label32.Text = "Defy zostaly umieszczone w odpowiednich folderach."; - // - // button1 - // - this.button1.Location = new System.Drawing.Point(98, 237); - this.button1.Name = "button1"; - this.button1.Size = new System.Drawing.Size(75, 23); - this.button1.TabIndex = 5; - this.button1.Text = "Koniec!"; - this.button1.UseVisualStyleBackColor = true; - this.button1.Click += new System.EventHandler(this.button1_Click); - // - // label33 - // - this.label33.AutoSize = true; - this.label33.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label33.Location = new System.Drawing.Point(12, 196); - this.label33.Name = "label33"; - this.label33.Size = new System.Drawing.Size(57, 17); - this.label33.TabIndex = 1; - this.label33.Text = "BÅ‚Ä™dów:"; - this.label33.Click += new System.EventHandler(this.label11_Click); - // - // label34 - // - this.label34.AutoSize = true; - this.label34.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label34.Location = new System.Drawing.Point(125, 196); - this.label34.Name = "label34"; - this.label34.Size = new System.Drawing.Size(48, 17); - this.label34.TabIndex = 2; - this.label34.Text = "XXXX"; - // - // label35 - // - this.label35.AutoSize = true; - this.label35.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(238))); - this.label35.Location = new System.Drawing.Point(179, 196); - this.label35.Name = "label35"; - this.label35.Size = new System.Drawing.Size(17, 17); - this.label35.TabIndex = 3; - this.label35.Text = ":("; - // - // Form2 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(276, 272); - this.Controls.Add(this.button1); - this.Controls.Add(this.label32); - this.Controls.Add(this.label35); - this.Controls.Add(this.label31); - this.Controls.Add(this.label29); - this.Controls.Add(this.label30); - this.Controls.Add(this.label27); - this.Controls.Add(this.label28); - this.Controls.Add(this.label26); - this.Controls.Add(this.label25); - this.Controls.Add(this.label24); - this.Controls.Add(this.label23); - this.Controls.Add(this.label22); - this.Controls.Add(this.label34); - this.Controls.Add(this.label21); - this.Controls.Add(this.label20); - this.Controls.Add(this.label19); - this.Controls.Add(this.label18); - this.Controls.Add(this.label17); - this.Controls.Add(this.label16); - this.Controls.Add(this.label15); - this.Controls.Add(this.label14); - this.Controls.Add(this.label13); - this.Controls.Add(this.label12); - this.Controls.Add(this.label33); - this.Controls.Add(this.label11); - this.Controls.Add(this.label10); - this.Controls.Add(this.label9); - this.Controls.Add(this.label8); - this.Controls.Add(this.label7); - this.Controls.Add(this.label6); - this.Controls.Add(this.label5); - this.Controls.Add(this.label4); - this.Controls.Add(this.label3); - this.Controls.Add(this.label2); - this.Controls.Add(this.label1); - this.Name = "Form2"; - this.Text = "UdaÅ‚o siÄ™! :)"; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - private System.Windows.Forms.Label label1; - private System.Windows.Forms.Label label2; - private System.Windows.Forms.Label label3; - private System.Windows.Forms.Label label4; - private System.Windows.Forms.Label label5; - private System.Windows.Forms.Label label6; - private System.Windows.Forms.Label label7; - private System.Windows.Forms.Label label8; - private System.Windows.Forms.Label label9; - private System.Windows.Forms.Label label10; - private System.Windows.Forms.Label label11; - private System.Windows.Forms.Label label22; - private System.Windows.Forms.Label label23; - private System.Windows.Forms.Label label24; - private System.Windows.Forms.Label label25; - private System.Windows.Forms.Label label26; - private System.Windows.Forms.Label label27; - private System.Windows.Forms.Label label28; - private System.Windows.Forms.Label label29; - private System.Windows.Forms.Label label30; - private System.Windows.Forms.Label label31; - private System.Windows.Forms.Label label32; - private System.Windows.Forms.Button button1; - public System.Windows.Forms.Label label12; - public System.Windows.Forms.Label label13; - public System.Windows.Forms.Label label14; - public System.Windows.Forms.Label label15; - public System.Windows.Forms.Label label16; - public System.Windows.Forms.Label label17; - public System.Windows.Forms.Label label18; - public System.Windows.Forms.Label label19; - public System.Windows.Forms.Label label20; - public System.Windows.Forms.Label label21; - private System.Windows.Forms.Label label33; - public System.Windows.Forms.Label label34; - public System.Windows.Forms.Label label35; - } -} \ No newline at end of file diff --git a/tools/Defsorter/Form2.cs b/tools/Defsorter/Form2.cs deleted file mode 100644 index fd6ba816f..000000000 --- a/tools/Defsorter/Form2.cs +++ /dev/null @@ -1,28 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -namespace DefSorter -{ - public partial class Form2 : Form - { - public Form2() - { - InitializeComponent(); - } - - private void button1_Click(object sender, EventArgs e) - { - Application.Exit(); - } - - private void label11_Click(object sender, EventArgs e) - { - - } - } -} \ No newline at end of file diff --git a/tools/Defsorter/Form3.Designer.cs b/tools/Defsorter/Form3.Designer.cs deleted file mode 100644 index bee160a5b..000000000 --- a/tools/Defsorter/Form3.Designer.cs +++ /dev/null @@ -1,101 +0,0 @@ -namespace DefSorter -{ - partial class Form3 - { - /// - /// Required designer variable. - /// - private System.ComponentModel.IContainer components = null; - - /// - /// Clean up any resources being used. - /// - /// true if managed resources should be disposed; otherwise, false. - protected override void Dispose(bool disposing) - { - if (disposing && (components != null)) - { - components.Dispose(); - } - base.Dispose(disposing); - } - - #region Windows Form Designer generated code - - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - private void InitializeComponent() - { - this.textBox1 = new System.Windows.Forms.TextBox(); - this.button1 = new System.Windows.Forms.Button(); - this.button2 = new System.Windows.Forms.Button(); - this.button3 = new System.Windows.Forms.Button(); - this.SuspendLayout(); - // - // textBox1 - // - this.textBox1.Location = new System.Drawing.Point(12, 12); - this.textBox1.Multiline = true; - this.textBox1.Name = "textBox1"; - this.textBox1.ReadOnly = true; - this.textBox1.Size = new System.Drawing.Size(268, 209); - this.textBox1.TabIndex = 0; - // - // button1 - // - this.button1.DialogResult = System.Windows.Forms.DialogResult.Ignore; - this.button1.Location = new System.Drawing.Point(12, 231); - this.button1.Name = "button1"; - this.button1.Size = new System.Drawing.Size(75, 23); - this.button1.TabIndex = 1; - this.button1.Text = "PomiÅ„"; - this.button1.UseVisualStyleBackColor = true; - // - // button2 - // - this.button2.Location = new System.Drawing.Point(205, 231); - this.button2.Name = "button2"; - this.button2.Size = new System.Drawing.Size(75, 23); - this.button2.TabIndex = 1; - this.button2.Text = "Harakiri"; - this.button2.UseVisualStyleBackColor = true; - this.button2.Click += new System.EventHandler(this.button2_Click); - // - // button3 - // - this.button3.DialogResult = System.Windows.Forms.DialogResult.Cancel; - this.button3.Location = new System.Drawing.Point(93, 231); - this.button3.Name = "button3"; - this.button3.Size = new System.Drawing.Size(106, 23); - this.button3.TabIndex = 1; - this.button3.Text = "Anuluj wszystko"; - this.button3.UseVisualStyleBackColor = true; - // - // Form3 - // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); - this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; - this.ClientSize = new System.Drawing.Size(292, 266); - this.Controls.Add(this.button3); - this.Controls.Add(this.button2); - this.Controls.Add(this.button1); - this.Controls.Add(this.textBox1); - this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; - this.Name = "Form3"; - this.Text = "Nastapil blad :("; - this.ResumeLayout(false); - this.PerformLayout(); - - } - - #endregion - - public System.Windows.Forms.TextBox textBox1; - public System.Windows.Forms.Button button1; - public System.Windows.Forms.Button button2; - public System.Windows.Forms.Button button3; - - } -} \ No newline at end of file diff --git a/tools/Defsorter/Form3.cs b/tools/Defsorter/Form3.cs deleted file mode 100644 index 0419b3921..000000000 --- a/tools/Defsorter/Form3.cs +++ /dev/null @@ -1,23 +0,0 @@ -using System; -using System.Collections.Generic; -using System.ComponentModel; -using System.Data; -using System.Drawing; -using System.Text; -using System.Windows.Forms; - -namespace DefSorter -{ - public partial class Form3 : Form - { - public Form3() - { - InitializeComponent(); - } - - private void button2_Click(object sender, EventArgs e) - { - Application.Exit(); - } - } -} \ No newline at end of file diff --git a/tools/Defsorter/Program.cs b/tools/Defsorter/Program.cs deleted file mode 100644 index bcf07661f..000000000 --- a/tools/Defsorter/Program.cs +++ /dev/null @@ -1,20 +0,0 @@ -using System; -using System.Collections.Generic; -using System.Windows.Forms; - -namespace DefSorter -{ - static class Program - { - /// - /// The main entry point for the application. - /// - [STAThread] - static void Main() - { - Application.EnableVisualStyles(); - Application.SetCompatibleTextRenderingDefault(false); - Application.Run(new Form1()); - } - } -} \ No newline at end of file diff --git a/tools/Obwodziciel/BNAMES.txt b/tools/Obwodziciel/BNAMES.txt deleted file mode 100644 index 82caf4c15..000000000 --- a/tools/Obwodziciel/BNAMES.txt +++ /dev/null @@ -1,44 +0,0 @@ -0 Mage guild 1 -1 Mage guild 2 -2 Mage guild 3 -3 Mage guild 4 -4 Mage guild 5 -5 tavern -6 shipyard when it's present:)) -7 fort -8 citadel -9 castle -10 village hall -11 town hall -12 city hall -13 capitol -14 marketplace -15 resource silo -16 blacksmith -17 lighthouse(0) mystic pond(1) artifact merchants(2,5,8) veil of darkness(4) escape tunnel(6) cage of warlords(7) -18 horde buildings for non-upgraded creatures: Griffins, dwarves, stone gargoyles, imps, skeletons, troglodytes, goblins, gnolls, pixies. -19 horde buildings for upgraded creatures Royal griffins, battle dwarves, obsidian gargoyles, familiars, skeleton warriors, infernal troglodytes, hobgoblins, gnoll marauders, sprites -20 Ship at the Shipyard -21 stables(0) fountain of fortune(1) lookout tower(2) brimstone clouds(3) necromancy amplifier(4) mana vortex(5) freelancer's guild(6) glyphs of fear(7) magic university(8) -22 brotherhood of sword(0) dwarven treasury(1) library(2) castle gates(3) skeleton transformer(4) portal of summoning(5) ballista yard(6) blood obelisk(7) -23 wall of Knowledge.(2) order of fire(3) academy of battle scholars(5) hall of valhalla(6) -24 horde buildings for non-upgraded creatures: dendroid guards, hell hounds -25 horde buildings for upgraded creatures: Dendroid soldiers, Cerberi -26 Grail -27 Houses near city hall -28 Houses near municipal -29 Houses near Capitol -30 dwelling 1 -31 dwelling 2 -32 dwelling 3 -33 dwelling 4 -34 dwelling 5 -35 dwelling 6 -36 dwelling 7 -37 upgraded dwelling 1 -38 upgraded dwelling 2 -39 upgraded dwelling 3 -40 upgraded dwelling 4 -41 upgraded dwelling 5 -42 upgraded dwelling 6 -43 upgraded dwelling 7 diff --git a/tools/Obwodziciel/Form1.h b/tools/Obwodziciel/Form1.h deleted file mode 100644 index 3cae61c21..000000000 --- a/tools/Obwodziciel/Form1.h +++ /dev/null @@ -1,791 +0,0 @@ -#pragma once -#include -#include - -namespace Obwodziciel { - - using namespace System; - using namespace System::ComponentModel; - using namespace System::Collections; - using namespace System::Windows::Forms; - using namespace System::Data; - using namespace System::Drawing; - -std::string ToString(System::String^ src) -{ - std::string dest; - using namespace System::Runtime::InteropServices; - const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(src)).ToPointer(); - dest = chars; - Marshal::FreeHGlobal(IntPtr((void*)chars)); - return dest; -} - /// - /// Summary for Form1 - /// - /// WARNING: If you change the name of this class, you will need to change the - /// 'Resource File Name' property for the managed resource compiler tool - /// associated with all .resx files this class depends on. Otherwise, - /// the designers will not be able to interact properly with localized - /// resources associated with this form. - /// - public ref class Form1 : public System::Windows::Forms::Form - { - public: - value struct BuildingEntry - { - int townID, ID; - String^ defname; - }; - Form1(void) - { - InitializeComponent(); - source1->Text = IO::Directory::GetCurrentDirectory(); - source2->Text = IO::Directory::GetCurrentDirectory(); - - IO::StreamReader ^sr = gcnew IO::StreamReader(IO::Directory::GetCurrentDirectory()+L"\\BNAMES.TXT"); - int i=0; - while(!sr->EndOfStream) - { - String ^ n = sr->ReadLine(); - //n = (i.ToString()) + L". " + n; - buildingTypes->Items->Add(n); - i++; - } - buildingTypes->SelectedIndex=0; - sr->Close(); - delete sr; - - sr = gcnew IO::StreamReader(IO::Directory::GetCurrentDirectory()+L"\\TOWNTYPE.TXT"); - while(!sr->EndOfStream) - { - String ^ n = sr->ReadLine(); - castleType->Items->Add(n); - } - castleType->SelectedIndex = 0; - - std::ifstream bb("buildings.txt"); - std::string pom; - while(!bb.eof()) - { - BuildingEntry be; - bb >> be.townID >> be.ID >> pom >> i >> i; - be.defname = gcnew String(pom.c_str()); - lista.Add(be); - } - bb.close(); - bb.clear(); - - out = gcnew IO::StreamWriter("wynik.txt"); - } - - protected: - /// - /// Clean up any resources being used. - /// - ~Form1() - { - if (components) - { - delete components; - } - out->Close(); - } - private: System::Windows::Forms::PictureBox^ pictureBox1; - protected: - private: System::Windows::Forms::PictureBox^ pictureBox2; - private: System::Windows::Forms::ListBox^ listBox1; - private: System::Windows::Forms::ListBox^ listBox2; - private: System::Windows::Forms::TextBox^ searchpat1; - private: System::Windows::Forms::Label^ label1; - private: System::Windows::Forms::TextBox^ searchpat2; - private: System::Windows::Forms::Label^ label2; - private: System::Windows::Forms::Button^ search1; - private: System::Windows::Forms::Button^ search2; - private: System::Windows::Forms::Label^ label3; - private: System::Windows::Forms::Label^ label4; - private: System::Windows::Forms::Button^ prev1; - private: System::Windows::Forms::Button^ next1; - private: System::Windows::Forms::Button^ prev2; - private: System::Windows::Forms::Button^ next2; - private: System::Windows::Forms::Button^ assign1; - private: System::Windows::Forms::Button^ assign2; - private: System::Windows::Forms::ListBox^ possibilites1; - private: System::Windows::Forms::ListBox^ possibilites2; - private: System::Windows::Forms::Button^ confirm1; - private: System::Windows::Forms::Button^ confirm2; - private: System::Windows::Forms::TextBox^ source1; - private: System::Windows::Forms::Label^ label5; - private: System::Windows::Forms::TextBox^ source2; - private: System::Windows::Forms::Label^ label6; - private: System::Windows::Forms::Button^ browse1; - private: System::Windows::Forms::Button^ button1; - private: System::Windows::Forms::Button^ browse2; - private: System::Windows::Forms::Label^ label7; - private: System::Windows::Forms::Label^ label8; - private: System::Windows::Forms::Label^ label9; - - - - private: System::Windows::Forms::Label^ label10; - private: System::Windows::Forms::FolderBrowserDialog^ folderBrowserDialog1; - - - private: - /// - /// Required designer variable. - /// - - int b1, b2; - IO::StreamWriter ^out; - System::Collections::Generic::List lista; - private: System::Windows::Forms::ComboBox^ buildingTypes; -private: System::Windows::Forms::ComboBox^ castleType; - - System::ComponentModel::Container ^components; - -#pragma region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - void InitializeComponent(void) - { - this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox()); - this->pictureBox2 = (gcnew System::Windows::Forms::PictureBox()); - this->listBox1 = (gcnew System::Windows::Forms::ListBox()); - this->listBox2 = (gcnew System::Windows::Forms::ListBox()); - this->searchpat1 = (gcnew System::Windows::Forms::TextBox()); - this->label1 = (gcnew System::Windows::Forms::Label()); - this->searchpat2 = (gcnew System::Windows::Forms::TextBox()); - this->label2 = (gcnew System::Windows::Forms::Label()); - this->search1 = (gcnew System::Windows::Forms::Button()); - this->search2 = (gcnew System::Windows::Forms::Button()); - this->label3 = (gcnew System::Windows::Forms::Label()); - this->label4 = (gcnew System::Windows::Forms::Label()); - this->prev1 = (gcnew System::Windows::Forms::Button()); - this->next1 = (gcnew System::Windows::Forms::Button()); - this->prev2 = (gcnew System::Windows::Forms::Button()); - this->next2 = (gcnew System::Windows::Forms::Button()); - this->assign1 = (gcnew System::Windows::Forms::Button()); - this->assign2 = (gcnew System::Windows::Forms::Button()); - this->possibilites1 = (gcnew System::Windows::Forms::ListBox()); - this->possibilites2 = (gcnew System::Windows::Forms::ListBox()); - this->confirm1 = (gcnew System::Windows::Forms::Button()); - this->confirm2 = (gcnew System::Windows::Forms::Button()); - this->source1 = (gcnew System::Windows::Forms::TextBox()); - this->label5 = (gcnew System::Windows::Forms::Label()); - this->source2 = (gcnew System::Windows::Forms::TextBox()); - this->label6 = (gcnew System::Windows::Forms::Label()); - this->browse1 = (gcnew System::Windows::Forms::Button()); - this->button1 = (gcnew System::Windows::Forms::Button()); - this->browse2 = (gcnew System::Windows::Forms::Button()); - this->label7 = (gcnew System::Windows::Forms::Label()); - this->label8 = (gcnew System::Windows::Forms::Label()); - this->label9 = (gcnew System::Windows::Forms::Label()); - this->label10 = (gcnew System::Windows::Forms::Label()); - this->folderBrowserDialog1 = (gcnew System::Windows::Forms::FolderBrowserDialog()); - this->buildingTypes = (gcnew System::Windows::Forms::ComboBox()); - this->castleType = (gcnew System::Windows::Forms::ComboBox()); - (cli::safe_cast(this->pictureBox1))->BeginInit(); - (cli::safe_cast(this->pictureBox2))->BeginInit(); - this->SuspendLayout(); - // - // pictureBox1 - // - this->pictureBox1->Location = System::Drawing::Point(12, 38); - this->pictureBox1->Name = L"pictureBox1"; - this->pictureBox1->Size = System::Drawing::Size(450, 298); - this->pictureBox1->TabIndex = 0; - this->pictureBox1->TabStop = false; - // - // pictureBox2 - // - this->pictureBox2->Location = System::Drawing::Point(522, 38); - this->pictureBox2->Name = L"pictureBox2"; - this->pictureBox2->Size = System::Drawing::Size(450, 298); - this->pictureBox2->TabIndex = 0; - this->pictureBox2->TabStop = false; - // - // listBox1 - // - this->listBox1->FormattingEnabled = true; - this->listBox1->HorizontalScrollbar = true; - this->listBox1->Location = System::Drawing::Point(12, 342); - this->listBox1->Name = L"listBox1"; - this->listBox1->Size = System::Drawing::Size(167, 186); - this->listBox1->TabIndex = 1; - this->listBox1->SelectedIndexChanged += gcnew System::EventHandler(this, &Form1::listBox1_SelectedIndexChanged); - // - // listBox2 - // - this->listBox2->FormattingEnabled = true; - this->listBox2->HorizontalScrollbar = true; - this->listBox2->Location = System::Drawing::Point(805, 342); - this->listBox2->Name = L"listBox2"; - this->listBox2->Size = System::Drawing::Size(167, 186); - this->listBox2->TabIndex = 1; - this->listBox2->SelectedIndexChanged += gcnew System::EventHandler(this, &Form1::listBox2_SelectedIndexChanged); - // - // searchpat1 - // - this->searchpat1->Location = System::Drawing::Point(185, 363); - this->searchpat1->Name = L"searchpat1"; - this->searchpat1->Size = System::Drawing::Size(173, 20); - this->searchpat1->TabIndex = 2; - this->searchpat1->Text = L"TOCS*.bmp"; - // - // label1 - // - this->label1->AutoSize = true; - this->label1->Location = System::Drawing::Point(243, 345); - this->label1->Name = L"label1"; - this->label1->Size = System::Drawing::Size(77, 13); - this->label1->TabIndex = 3; - this->label1->Text = L"Search pattern"; - // - // searchpat2 - // - this->searchpat2->Location = System::Drawing::Point(626, 361); - this->searchpat2->Name = L"searchpat2"; - this->searchpat2->Size = System::Drawing::Size(173, 20); - this->searchpat2->TabIndex = 2; - this->searchpat2->Text = L"TBCS*.bmp"; - // - // label2 - // - this->label2->AutoSize = true; - this->label2->Location = System::Drawing::Point(664, 345); - this->label2->Name = L"label2"; - this->label2->Size = System::Drawing::Size(77, 13); - this->label2->TabIndex = 3; - this->label2->Text = L"Search pattern"; - // - // search1 - // - this->search1->Location = System::Drawing::Point(185, 393); - this->search1->Name = L"search1"; - this->search1->Size = System::Drawing::Size(103, 21); - this->search1->TabIndex = 4; - this->search1->Text = L"Search"; - this->search1->UseVisualStyleBackColor = true; - this->search1->Click += gcnew System::EventHandler(this, &Form1::search1_Click); - // - // search2 - // - this->search2->Location = System::Drawing::Point(696, 391); - this->search2->Name = L"search2"; - this->search2->Size = System::Drawing::Size(103, 21); - this->search2->TabIndex = 4; - this->search2->Text = L"Search"; - this->search2->UseVisualStyleBackColor = true; - this->search2->Click += gcnew System::EventHandler(this, &Form1::search2_Click); - // - // label3 - // - this->label3->AutoSize = true; - this->label3->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 18, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, - static_cast(238))); - this->label3->Location = System::Drawing::Point(160, 6); - this->label3->Name = L"label3"; - this->label3->Size = System::Drawing::Size(81, 29); - this->label3->TabIndex = 5; - this->label3->Text = L"POLE"; - // - // label4 - // - this->label4->AutoSize = true; - this->label4->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 18, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, - static_cast(238))); - this->label4->Location = System::Drawing::Point(743, 6); - this->label4->Name = L"label4"; - this->label4->Size = System::Drawing::Size(93, 29); - this->label4->TabIndex = 5; - this->label4->Text = L"IMAGE"; - // - // prev1 - // - this->prev1->Enabled = false; - this->prev1->Location = System::Drawing::Point(294, 393); - this->prev1->Name = L"prev1"; - this->prev1->Size = System::Drawing::Size(64, 21); - this->prev1->TabIndex = 6; - this->prev1->Text = L"<-"; - this->prev1->UseVisualStyleBackColor = true; - this->prev1->Click += gcnew System::EventHandler(this, &Form1::prev1_Click); - // - // next1 - // - this->next1->Enabled = false; - this->next1->Location = System::Drawing::Point(364, 393); - this->next1->Name = L"next1"; - this->next1->Size = System::Drawing::Size(64, 21); - this->next1->TabIndex = 6; - this->next1->Text = L"->"; - this->next1->UseVisualStyleBackColor = true; - this->next1->Click += gcnew System::EventHandler(this, &Form1::next1_Click); - // - // prev2 - // - this->prev2->Enabled = false; - this->prev2->Location = System::Drawing::Point(556, 391); - this->prev2->Name = L"prev2"; - this->prev2->Size = System::Drawing::Size(64, 21); - this->prev2->TabIndex = 6; - this->prev2->Text = L"<-"; - this->prev2->UseVisualStyleBackColor = true; - this->prev2->Click += gcnew System::EventHandler(this, &Form1::prev2_Click); - // - // next2 - // - this->next2->Enabled = false; - this->next2->Location = System::Drawing::Point(626, 391); - this->next2->Name = L"next2"; - this->next2->Size = System::Drawing::Size(64, 21); - this->next2->TabIndex = 6; - this->next2->Text = L"->"; - this->next2->UseVisualStyleBackColor = true; - this->next2->Click += gcnew System::EventHandler(this, &Form1::next2_Click); - // - // assign1 - // - this->assign1->Location = System::Drawing::Point(434, 391); - this->assign1->Name = L"assign1"; - this->assign1->Size = System::Drawing::Size(116, 22); - this->assign1->TabIndex = 7; - this->assign1->Text = L"Assign there >"; - this->assign1->UseVisualStyleBackColor = true; - this->assign1->Click += gcnew System::EventHandler(this, &Form1::assign1_Click); - // - // assign2 - // - this->assign2->Location = System::Drawing::Point(434, 414); - this->assign2->Name = L"assign2"; - this->assign2->Size = System::Drawing::Size(116, 22); - this->assign2->TabIndex = 7; - this->assign2->Text = L"< Assign there"; - this->assign2->UseVisualStyleBackColor = true; - this->assign2->Click += gcnew System::EventHandler(this, &Form1::assign2_Click); - // - // possibilites1 - // - this->possibilites1->FormattingEnabled = true; - this->possibilites1->HorizontalScrollbar = true; - this->possibilites1->Location = System::Drawing::Point(185, 422); - this->possibilites1->Name = L"possibilites1"; - this->possibilites1->Size = System::Drawing::Size(120, 108); - this->possibilites1->TabIndex = 8; - this->possibilites1->SelectedIndexChanged += gcnew System::EventHandler(this, &Form1::possibilites1_SelectedIndexChanged); - // - // possibilites2 - // - this->possibilites2->FormattingEnabled = true; - this->possibilites2->HorizontalScrollbar = true; - this->possibilites2->Location = System::Drawing::Point(679, 422); - this->possibilites2->Name = L"possibilites2"; - this->possibilites2->Size = System::Drawing::Size(120, 108); - this->possibilites2->TabIndex = 8; - this->possibilites2->SelectedIndexChanged += gcnew System::EventHandler(this, &Form1::possibilites2_SelectedIndexChanged); - // - // confirm1 - // - this->confirm1->Location = System::Drawing::Point(312, 422); - this->confirm1->Name = L"confirm1"; - this->confirm1->Size = System::Drawing::Size(116, 25); - this->confirm1->TabIndex = 9; - this->confirm1->Text = L"Confirm"; - this->confirm1->UseVisualStyleBackColor = true; - this->confirm1->Click += gcnew System::EventHandler(this, &Form1::confirm1_Click); - // - // confirm2 - // - this->confirm2->Location = System::Drawing::Point(557, 422); - this->confirm2->Name = L"confirm2"; - this->confirm2->Size = System::Drawing::Size(116, 25); - this->confirm2->TabIndex = 9; - this->confirm2->Text = L"Confirm"; - this->confirm2->UseVisualStyleBackColor = true; - this->confirm2->Click += gcnew System::EventHandler(this, &Form1::confirm2_Click); - // - // source1 - // - this->source1->Location = System::Drawing::Point(312, 468); - this->source1->Name = L"source1"; - this->source1->Size = System::Drawing::Size(116, 20); - this->source1->TabIndex = 10; - // - // label5 - // - this->label5->AutoSize = true; - this->label5->Location = System::Drawing::Point(335, 452); - this->label5->Name = L"label5"; - this->label5->Size = System::Drawing::Size(73, 13); - this->label5->TabIndex = 11; - this->label5->Text = L"Source folder:"; - // - // source2 - // - this->source2->Location = System::Drawing::Point(556, 468); - this->source2->Name = L"source2"; - this->source2->Size = System::Drawing::Size(116, 20); - this->source2->TabIndex = 10; - // - // label6 - // - this->label6->AutoSize = true; - this->label6->Location = System::Drawing::Point(579, 452); - this->label6->Name = L"label6"; - this->label6->Size = System::Drawing::Size(73, 13); - this->label6->TabIndex = 11; - this->label6->Text = L"Source folder:"; - // - // browse1 - // - this->browse1->Location = System::Drawing::Point(312, 494); - this->browse1->Name = L"browse1"; - this->browse1->Size = System::Drawing::Size(116, 23); - this->browse1->TabIndex = 12; - this->browse1->Text = L"Browse"; - this->browse1->UseVisualStyleBackColor = true; - this->browse1->Click += gcnew System::EventHandler(this, &Form1::browse1_Click); - // - // button1 - // - this->button1->Location = System::Drawing::Point(557, 494); - this->button1->Name = L"button1"; - this->button1->Size = System::Drawing::Size(116, 23); - this->button1->TabIndex = 12; - this->button1->Text = L"Browse"; - this->button1->UseVisualStyleBackColor = true; - // - // browse2 - // - this->browse2->Location = System::Drawing::Point(556, 494); - this->browse2->Name = L"browse2"; - this->browse2->Size = System::Drawing::Size(116, 23); - this->browse2->TabIndex = 12; - this->browse2->Text = L"Browse"; - this->browse2->UseVisualStyleBackColor = true; - this->browse2->Click += gcnew System::EventHandler(this, &Form1::browse2_Click); - // - // label7 - // - this->label7->AutoSize = true; - this->label7->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, - static_cast(238))); - this->label7->Location = System::Drawing::Point(440, 472); - this->label7->Name = L"label7"; - this->label7->Size = System::Drawing::Size(104, 20); - this->label7->TabIndex = 13; - this->label7->Text = L"Obwodziciel"; - // - // label8 - // - this->label8->AutoSize = true; - this->label8->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, - static_cast(238))); - this->label8->Location = System::Drawing::Point(442, 492); - this->label8->Name = L"label8"; - this->label8->Size = System::Drawing::Size(102, 20); - this->label8->TabIndex = 13; - this->label8->Text = L"VCMI Team"; - // - // label9 - // - this->label9->AutoSize = true; - this->label9->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 12, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, - static_cast(238))); - this->label9->Location = System::Drawing::Point(459, 512); - this->label9->Name = L"label9"; - this->label9->Size = System::Drawing::Size(66, 20); - this->label9->TabIndex = 13; - this->label9->Text = L"© 2008"; - // - // label10 - // - this->label10->AutoSize = true; - this->label10->Location = System::Drawing::Point(463, 344); - this->label10->Name = L"label10"; - this->label10->Size = System::Drawing::Size(58, 13); - this->label10->TabIndex = 16; - this->label10->Text = L"Building ID"; - // - // buildingTypes - // - this->buildingTypes->FormattingEnabled = true; - this->buildingTypes->Location = System::Drawing::Point(365, 364); - this->buildingTypes->Name = L"buildingTypes"; - this->buildingTypes->Size = System::Drawing::Size(255, 21); - this->buildingTypes->TabIndex = 17; - // - // castleType - // - this->castleType->FormattingEnabled = true; - this->castleType->Location = System::Drawing::Point(434, 445); - this->castleType->Name = L"castleType"; - this->castleType->Size = System::Drawing::Size(116, 21); - this->castleType->TabIndex = 18; - // - // Form1 - // - this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); - this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; - this->ClientSize = System::Drawing::Size(984, 535); - this->Controls->Add(this->castleType); - this->Controls->Add(this->buildingTypes); - this->Controls->Add(this->label10); - this->Controls->Add(this->label9); - this->Controls->Add(this->label8); - this->Controls->Add(this->label7); - this->Controls->Add(this->browse2); - this->Controls->Add(this->button1); - this->Controls->Add(this->browse1); - this->Controls->Add(this->label6); - this->Controls->Add(this->label5); - this->Controls->Add(this->source2); - this->Controls->Add(this->source1); - this->Controls->Add(this->confirm2); - this->Controls->Add(this->confirm1); - this->Controls->Add(this->possibilites2); - this->Controls->Add(this->possibilites1); - this->Controls->Add(this->assign2); - this->Controls->Add(this->assign1); - this->Controls->Add(this->next2); - this->Controls->Add(this->next1); - this->Controls->Add(this->prev2); - this->Controls->Add(this->prev1); - this->Controls->Add(this->label4); - this->Controls->Add(this->label3); - this->Controls->Add(this->search2); - this->Controls->Add(this->search1); - this->Controls->Add(this->label2); - this->Controls->Add(this->label1); - this->Controls->Add(this->searchpat2); - this->Controls->Add(this->searchpat1); - this->Controls->Add(this->listBox2); - this->Controls->Add(this->listBox1); - this->Controls->Add(this->pictureBox2); - this->Controls->Add(this->pictureBox1); - this->Name = L"Form1"; - this->Text = L"Obwodziciel 1.00"; - (cli::safe_cast(this->pictureBox1))->EndInit(); - (cli::safe_cast(this->pictureBox2))->EndInit(); - this->ResumeLayout(false); - this->PerformLayout(); - - } -#pragma endregion - private: System::Void browse1_Click(System::Object^ sender, System::EventArgs^ e) { - folderBrowserDialog1->ShowDialog(); - source1->Text = folderBrowserDialog1->SelectedPath; - } -private: System::Void browse2_Click(System::Object^ sender, System::EventArgs^ e) { - folderBrowserDialog1->ShowDialog(); - source2->Text = folderBrowserDialog1->SelectedPath; - } -private: System::Void search1_Click(System::Object^ sender, System::EventArgs^ e) { - listBox1->Items->Clear(); - array^ pliki = IO::Directory::GetFiles(source1->Text,searchpat1->Text); - for each(String^ plik in pliki) - { - listBox1->Items->Add(plik); - } - if(listBox1->Items->Count>0) - listBox1->SelectedIndex=0; - } -private: System::Void search2_Click(System::Object^ sender, System::EventArgs^ e) { - listBox2->Items->Clear(); - array^ pliki = IO::Directory::GetFiles(source2->Text,searchpat2->Text); - for each(String^ plik in pliki) - { - listBox2->Items->Add(plik); - } - if(listBox2->Items->Count>0) - listBox2->SelectedIndex=0; - } -private: System::Void listBox1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { - if(listBox1->SelectedIndex<0) - return; - pictureBox1->Image = gcnew Drawing::Bitmap(dynamic_cast(listBox1->SelectedItem)); - } -private: System::Void listBox2_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { - if(listBox2->SelectedIndex<0) - return; - String^ s = dynamic_cast(listBox2->SelectedItem); - pictureBox2->Image = gcnew Drawing::Bitmap(s); - s = s->Substring(s->LastIndexOf(L"\\")+1); - s = s->Replace(L"_0_",L""); - s = s->Replace(L".bmp",L".def"); - s = s->Replace(L".BMP",L".def"); - for each(BuildingEntry b in lista) - { - if(b.defname == s) - buildingTypes->SelectedIndex = b.ID; - } - } -private: System::Void assign2_Click(System::Object^ sender, System::EventArgs^ e) { - possibilites1->Items->Clear(); - for each(Object^ item in listBox1->Items) - { - String^ path = dynamic_cast(item); - Bitmap ^b = gcnew Bitmap(path); - if( (b->Width == pictureBox2->Image->Width) && (b->Height == pictureBox2->Image->Height) ) - possibilites1->Items->Add(path); - delete b; - } - if (possibilites1->Items->Count>0) - { - possibilites1->SelectedIndex=0; - } - } -private: System::Void assign1_Click(System::Object^ sender, System::EventArgs^ e) { - possibilites2->Items->Clear(); - for each(Object^ item in listBox2->Items) - { - String^ path = dynamic_cast(item); - Bitmap ^b = gcnew Bitmap(path); - if( (b->Width == pictureBox1->Image->Width) && (b->Height == pictureBox1->Image->Height) ) - possibilites2->Items->Add(path); - delete b; - } - if (possibilites2->Items->Count>0) - { - possibilites2->SelectedIndex=0; - } - } -private: System::Void possibilites1_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { - if(possibilites1->SelectedIndex<0) - return; - String^ s = dynamic_cast(possibilites1->SelectedItem); - pictureBox1->Image = gcnew Drawing::Bitmap(s); - s = s->Substring(s->LastIndexOf(L"\\")+1); - s = s->Replace(L"_0_",L""); - s = s->Replace(L".bmp",L".def"); - s = s->Replace(L".BMP",L".def"); - for each(BuildingEntry b in lista) - { - if(b.defname == s) - buildingTypes->SelectedIndex = b.ID; - } - } -private: System::Void possibilites2_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) { - if(possibilites2->SelectedIndex<0) - return; - String^ s = dynamic_cast(possibilites2->SelectedItem); - pictureBox2->Image = gcnew Drawing::Bitmap(s); - s = s->Substring(s->LastIndexOf(L"\\")+1); - s = s->Replace(L"_0_",L""); - s = s->Replace(L".bmp",L".def"); - s = s->Replace(L".BMP",L".def"); - for each(BuildingEntry b in lista) - { - if(b.defname == s) - buildingTypes->SelectedIndex = b.ID; - } - } - void confirm(bool first) - { - try - { - //out format: - // townId ID defname bordername areaname - - String^ s, ^s2, ^s3; - if(first) - { - s = dynamic_cast(possibilites2->SelectedItem); - } - else - { - s = dynamic_cast(listBox2->SelectedItem); - } - s = s->Substring(s->LastIndexOf(L"\\")+1); - s = s->Replace(L"_0_",L""); - s = s->Replace(L".bmp",L".def"); - s = s->Replace(L".BMP",L".def"); - - if(!first) - { - s2 = dynamic_cast(possibilites1->SelectedItem); - } - else - { - s2 = dynamic_cast(listBox1->SelectedItem); - } - s2 = s2->Substring(s2->LastIndexOf(L"\\")+1); - - s3 = L"TZ" + s2->Substring(2); - - String^ toOut; - toOut = castleType->SelectedIndex.ToString() + L"\t" - + buildingTypes->SelectedIndex + (L"\t") - + s + L"\t" - + s2 + L"\t" - + s3; - out->WriteLine(toOut); - out->Flush(); - - if(first) - { - for each(Object^ obj in listBox2->Items) - { - String^ str = dynamic_cast(obj), - ^usw = dynamic_cast(possibilites2->SelectedItem); - if(str==usw) - { - listBox2->Items->Remove(obj); - if(listBox2->Items->Count>0) - listBox2->SelectedIndex = 0; - break; - } - } - listBox1->Items->Remove(listBox1->SelectedItem); - if(listBox1->Items->Count>0) - listBox1->SelectedIndex++; - } - else - { - for each(Object^ obj in listBox1->Items) - { - String^ str = dynamic_cast(obj), - ^usw = dynamic_cast(possibilites1->SelectedItem); - if(str==usw) - { - listBox1->Items->Remove(obj); - if(listBox1->Items->Count>0) - listBox1->SelectedIndex = 0; - break; - } - } - int tempp = listBox2->SelectedIndex; - listBox2->Items->Remove(listBox2->SelectedItem); - if(listBox2->Items->Count>tempp) - listBox2->SelectedIndex=tempp; - } - - possibilites1->Items->Clear(); - possibilites2->Items->Clear(); - } - catch(...) - { - possibilites1->Items->Clear(); - possibilites2->Items->Clear(); - } - } -private: System::Void confirm1_Click(System::Object^ sender, System::EventArgs^ e) { - confirm(true); - } -private: System::Void confirm2_Click(System::Object^ sender, System::EventArgs^ e) { - confirm(false); - } -private: System::Void prev1_Click(System::Object^ sender, System::EventArgs^ e) { - } -private: System::Void next1_Click(System::Object^ sender, System::EventArgs^ e) { - } -private: System::Void prev2_Click(System::Object^ sender, System::EventArgs^ e) { - } -private: System::Void next2_Click(System::Object^ sender, System::EventArgs^ e) { - } -}; -} - diff --git a/tools/Obwodziciel/Form1.resx b/tools/Obwodziciel/Form1.resx deleted file mode 100644 index f28ce5858..000000000 --- a/tools/Obwodziciel/Form1.resx +++ /dev/null @@ -1,126 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - 17, 17 - - - 42 - - \ No newline at end of file diff --git a/tools/Obwodziciel/Obwodziciel.cpp b/tools/Obwodziciel/Obwodziciel.cpp deleted file mode 100644 index d1a5858a6..000000000 --- a/tools/Obwodziciel/Obwodziciel.cpp +++ /dev/null @@ -1,17 +0,0 @@ -// Obwodziciel.cpp : main project file. - -#include "Form1.h" - -using namespace Obwodziciel; - -[STAThreadAttribute] -int main(array ^args) -{ - // Enabling Windows XP visual effects before any controls are created - Application::EnableVisualStyles(); - Application::SetCompatibleTextRenderingDefault(false); - - // Create the main window and run it - Application::Run(gcnew Form1()); - return 0; -} diff --git a/tools/Obwodziciel/Obwodziciel.vcproj b/tools/Obwodziciel/Obwodziciel.vcproj deleted file mode 100644 index 7df6c12e7..000000000 --- a/tools/Obwodziciel/Obwodziciel.vcproj +++ /dev/null @@ -1,236 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - diff --git a/tools/Obwodziciel/TOWNTYPE.TXT b/tools/Obwodziciel/TOWNTYPE.TXT deleted file mode 100644 index f2e154580..000000000 --- a/tools/Obwodziciel/TOWNTYPE.TXT +++ /dev/null @@ -1,9 +0,0 @@ -Castle -Rampart -Tower -Inferno -Necropolis -Dungeon -Stronghold -Fortress -Conflux diff --git a/tools/Obwodziciel/buildings.txt b/tools/Obwodziciel/buildings.txt deleted file mode 100644 index ec31cfc0e..000000000 --- a/tools/Obwodziciel/buildings.txt +++ /dev/null @@ -1,37 +0,0 @@ -0 16 TBCSBLAK.def 213 251 -0 8 TBCSCAS2.def 478 66 -0 9 TBCSCAS3.def 478 37 -0 7 TBCSCSTL.def 595 66 -0 6 TBCSDOCK.def 478 134 -0 30 TBCSDW_0.def 304 92 -0 31 TBCSDW_1.def 360 130 -0 32 TBCSDW_2.def 76 57 -0 33 TBCSDW_3.def 176 101 -0 34 TBCSDW_4.def 563 211 -0 35 TBCSDW_5.def 174 190 -0 36 TBCSDW_6.def 303 0 -0 21 TBCSEXT0.def 384 193 -0 22 TBCSEXT1.def 0 198 -0 11 TBCSHAL2.def 0 176 -0 12 TBCSHAL3.def 0 164 -0 13 TBCSHAL4.def 0 154 -0 10 TBCSHALL.def 0 209 -0 26 TBCSHOLY.def 456 109 -0 18 TBCSHRD1.def 76 53 -0 19 TBCSHRD2.def 76 35 -0 1 TBCSMAG2.def 706 135 -0 2 TBCSMAG3.def 704 107 -0 3 TBCSMAG4.def 704 76 -0 0 TBCSMAGE.def 707 166 -0 14 TBCSMARK.def 413 264 -0 15 TBCSSILO.def 488 228 -0 17 TBCSSPEC.def 533 71 -0 5 TBCSTVRN.def 0 230 -0 37 TBCSUP_0.def 304 65 -0 38 TBCSUP_1.def 360 115 -0 39 TBCSUP_2.def 76 35 -0 40 TBCSUP_3.def 176 85 -0 41 TBCSUP_4.def 563 173 -0 42 TBCSUP_5.def 160 190 -0 43 TBCSUP_6.def 303 0 -0 20 TBCSBOAT.def 478 134 \ No newline at end of file diff --git a/tools/Wpasujbud/AssemblyInfo.cpp b/tools/Wpasujbud/AssemblyInfo.cpp deleted file mode 100644 index a64855d4a..000000000 --- a/tools/Wpasujbud/AssemblyInfo.cpp +++ /dev/null @@ -1,38 +0,0 @@ -using namespace System; -using namespace System::Reflection; -using namespace System::Runtime::CompilerServices; -using namespace System::Runtime::InteropServices; -using namespace System::Security::Permissions; - -// -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. -// -[assembly:AssemblyTitleAttribute("Wpasujbud 1.0")]; -[assembly:AssemblyDescriptionAttribute("Cudowne narzedzie, ktore wpasuje budynki za mnie")]; -[assembly:AssemblyConfigurationAttribute("")]; -[assembly:AssemblyCompanyAttribute("VCMI Team")]; -[assembly:AssemblyProductAttribute("ret")]; -[assembly:AssemblyCopyrightAttribute("Copyright (c) 2008")]; -[assembly:AssemblyTrademarkAttribute("")]; -[assembly:AssemblyCultureAttribute("")]; - -// -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the value or you can default the Revision and Build Numbers -// by using the '*' as shown below: - -[assembly:AssemblyVersionAttribute("1.0.*")]; - -[assembly:ComVisible(false)]; - -[assembly:CLSCompliantAttribute(true)]; - -[assembly:SecurityPermission(SecurityAction::RequestMinimum, UnmanagedCode = true)]; diff --git a/tools/Wpasujbud/Wpasujbud.cpp b/tools/Wpasujbud/Wpasujbud.cpp deleted file mode 100644 index 7fa0e50a9..000000000 --- a/tools/Wpasujbud/Wpasujbud.cpp +++ /dev/null @@ -1,361 +0,0 @@ -// Wpasujbud.cpp : main project file. -//#include -#include "SDL.h" -#include "Wpasujbud.h" -#include "tchar.h" -#include "obrazek.h" -#include "dataEditor.h" -using namespace Wpasuj; - -int Inaccuracy=5; -int zgodnosc(Bitmap^ bg, Bitmap^ st, int x, int y); -int zgodnosc(SDL_Surface * bg, SDL_Surface * st, int x, int y); - -std::string Wpasujbud::ToString(System::String^ src) -{ - std::string dest; - using namespace System::Runtime::InteropServices; - const char* chars = (const char*)(Marshal::StringToHGlobalAnsi(src)).ToPointer(); - dest = chars; - Marshal::FreeHGlobal(IntPtr((void*)chars)); - return dest; -} - -[STAThreadAttribute] -int __stdcall WinMain() -{ - // Enabling Windows XP visual effects before any controls are created - Application::EnableVisualStyles(); - Application::SetCompatibleTextRenderingDefault(false); - - Application::Run(gcnew Wpasujbud()); - exit(0); - return 0; -} - -Wpasujbud::Wpasujbud(void) -{ - InitializeComponent(); - openFileDialog1->InitialDirectory = IO::Directory::GetCurrentDirectory(); - IO::StreamReader ^sr = gcnew IO::StreamReader(L"config/TOWNTYPE.TXT"); - Int32 i=0; - while(!sr->EndOfStream) - { - String ^ n = sr->ReadLine(); - n = (i.ToString()) + L". " + n; - townID->Items->Add(n); - i++; - } - townID->SelectedIndex=0; - sr->Close(); - i++; - - - sr = gcnew IO::StreamReader(L"config/BNAMES.TXT"); - i=0; - while(!sr->EndOfStream) - { - String ^ n = sr->ReadLine(); - //n = (i.ToString()) + L". " + n; - buildingType->Items->Add(n); - i++; - } - buildingType->SelectedIndex=0; - sr->Close(); - i++; - - bitmapsFolder->Text = openFileDialog1->InitialDirectory; - -} - -System::Void Wpasujbud::searchBitmaps_Click(System::Object^ sender, System::EventArgs^ e) -{ - bitmapList->Items->Clear(); - array^ pliki = IO::Directory::GetFiles(bitmapsFolder->Text,bmpPattern->Text); - for each(String ^ plik in pliki) - { - //if(plik->EndsWith(L".bmp") || plik->EndsWith(L".BMP")) - bitmapList->Items->Add(plik->Substring(plik->LastIndexOf('\\')+1)); - } - if(bitmapList->Items->Count>0) - bitmapList->SelectedIndex=0; -} -System::Void Wpasujbud::startLocating_Click(System::Object^ sender, System::EventArgs^ e) -{ - searchPicturePos(); -} -System::Void Wpasujbud::setBackground_Click(System::Object^ sender, System::EventArgs^ e) -{ - if(townBgPath->Text->Length==0) - return; - Bitmap ^ bg = gcnew Bitmap(townBgPath->Text); - townBg->Image = dynamic_cast(bg); - sbg = SDL_LoadBMP(ToString(townBgPath->Text).c_str()); -} -System::Void Wpasujbud::openFileDialog1_FileOk(System::Object^ sender, System::ComponentModel::CancelEventArgs^ e) -{ - townBgPath->Text = (dynamic_cast(sender))->FileName; -} -System::Void Wpasujbud::browseForBg_Click(System::Object^ sender, System::EventArgs^ e) -{ - openFileDialog1->ShowDialog(); -} -System::Void Wpasujbud::browseForbmpfol_Click(System::Object^ sender, System::EventArgs^ e) -{ - folderBrowserDialog1->ShowDialog(); - bitmapsFolder->Text = folderBrowserDialog1->SelectedPath; -} -System::Void Wpasujbud::bitmapList_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e) -{ - int nsel = bitmapList->SelectedIndex; - if (nsel<0) - return; - String ^ bmpname = bitmapsFolder->Text + "\\" + dynamic_cast(bitmapList->SelectedItem); - Bitmap ^building = gcnew Bitmap(bmpname); - buildingImg->Image = dynamic_cast(building); -} -System::Void Wpasujbud::townBg_Click(System::Object^ sender, System::EventArgs^ e) -{ - //Int32 tx, ty, ux, uy; - //tx = townBg->Location.X; - //ty = townBg->Location.Y; - //ux = Location.X; - //uy = Location.Y; - mx = MousePosition.X - townBg->Location.X - Location.X - 4; - my = MousePosition.Y - townBg->Location.Y - Location.Y - 30; - koordy->Text = mx.ToString() + L", " + my.ToString(); -} -System::Void Wpasujbud::button1_Click(System::Object^ sender, System::EventArgs^ e) //skip -{ - nextPicture(); -} - -Uint32 SDL_GetPixel(SDL_Surface *surface, int x, int y) -{ - Uint8 *p = (Uint8 *)surface->pixels + y * surface->pitch + x * surface->format->BytesPerPixel; - - switch(surface->format->BytesPerPixel) - { - case 1: - { - SDL_Color * color = surface->format->palette->colors+(*p); - return color->r<<16 | color->g<<8 | color->b; - } - case 3: - return p[0] | p[1] << 8 | p[2] << 16; - } -} -int zgodnosc(SDL_Surface * bg, SDL_Surface * st, int x, int y) -{ - int ret=0; - for(int i=0;iw;i+=Inaccuracy) - { - for(int j=0;jh;j+=Inaccuracy) - { - int c1 = SDL_GetPixel(bg,i+x,j+y); - int c2 = SDL_GetPixel(st,i,j); - if((i+x)>=bg->w) - break; - if((j+y)>=bg->h) - break; - if(SDL_GetPixel(bg,i+x,j+y) == SDL_GetPixel(st,i,j)) - { - ret++; - } - } - } - return ret*(Inaccuracy*Inaccuracy); -} -int zgodnosc(Bitmap^ bg, Bitmap^ st, int x, int y) -{ - int ret=0; - for(int i=0;iWidth;i++) - { - for(int j=0;jHeight;j++) - { - //Color c1 = bg->GetPixel(i+x,j+y); - //Color c2 = st->GetPixel(i,j); - if((i+x)>=bg->Width) - break; - if((j+y)>=bg->Height) - break; - if(bg->GetPixel(i+x,j+y) == st->GetPixel(i,j)) - { - ret++; - } - } - } - return ret; -} -void Wpasujbud::searchPicturePos() -{ - //Bitmap^ b = gcnew Bitmap((townBg->Image)->Width,(townBg->Image)->Height,Imaging::PixelFormat::Format24bppRgb); - //Bitmap^ s = dynamic_cast(buildingImg->Image); - //Graphics ^ g = Graphics::FromImage(b); - //g->DrawImage(townBg->Image,0,0); - //townBg->Image = b; - String^ sss = bitmapsFolder->Text; - if(!(sss->EndsWith(L"/")||sss->EndsWith(L"\\"))) - sss+=L"\\"; - sss+=dynamic_cast(bitmapList->SelectedItem); - SDL_Surface *str = SDL_LoadBMP(ToString(sss).c_str()); - Int32 colorPxs = 0; - - int aq = 0x00ffff; - for (int x=0;xw;x++) - { - for(int y=0;yh;y++) - { - if(SDL_GetPixel(str,x,y) != aq) - colorPxs++; - } - } - int zgoda=0, retx, rety; - int px=mx, py=my, maxr = Convert::ToInt32(radious->Text); - if (radioButton2->Checked) - { - px-=str->w/2; - py-=str->h/2; - } - else if (radioButton3->Checked) - { - px-=str->w; - py-=str->h; - } - px-=maxr/2; - py-=maxr/2; - for(int i=0;izgoda) - { - zgoda = pom; - retx = px+i; - rety = py+j; - } - } - } - //for(int r=0;rzgoda) - // { - // zgoda = pom; - // retx = px+i; - // rety = py; - // } - // pom = zgodnosc(sbg,str,px+i,py+r); - // if (pom>zgoda) - // { - // zgoda = pom; - // retx = px+i; - // rety = py+r; - // } - // pom = zgodnosc(sbg,str,px,py+i); - // if (pom>zgoda) - // { - // zgoda = pom; - // retx = px; - // rety = py+i; - // } - // pom = zgodnosc(sbg,str,px+r,py+i); - // if (pom>zgoda) - // { - // zgoda = pom; - // retx = px+r; - // rety = py+i; - // } - // float per = zgoda/colorPxs; - // - // } - // px--; - // py--; - //} - accordanceBox->Text = zgoda.ToString() + L"/" + colorPxs.ToString(); - curx = retx; - cury = rety; - foundedCoords->Text = retx.ToString() + L", " + rety.ToString(); - //townBg->Refresh(); -} - -System::Void Wpasujbud::inaccuracy_TextChanged(System::Object^ sender, System::EventArgs^ e) -{ - int ni = Convert::ToUInt32(inaccuracy->Text); - if(ni==0) - { - inaccuracy->Text == L"1"; - Inaccuracy = 1; - } - else - { - Inaccuracy = ni; - } -} - -void Wpasujbud::nextPicture() -{ - if(bitmapList->SelectedIndex<(bitmapList->Items->Count-1)) - bitmapList->SelectedIndex++; -} -void Wpasujbud::previousPicture() -{ - if(bitmapList->SelectedIndex>0) - bitmapList->SelectedIndex--; -} - -System::Void Wpasujbud::confirm_Click(System::Object^ sender, System::EventArgs^ e) -{ - CBuildingData ^cbd = gcnew CBuildingData(); - //cbd->defname = bitmapsFolder->Text; - //if(!(cbd->defname->EndsWith(L"/")||cbd->defname->EndsWith(L"\\"))) - // cbd->defname+=L"\\"; - cbd->defname+=dynamic_cast(bitmapList->SelectedItem); - cbd->defname = (cbd->defname)->Substring(0,cbd->defname->Length-7)+".def"; - cbd->ID = buildingType->SelectedIndex; - cbd->townID = townID->SelectedIndex; - cbd->x = curx; - cbd->y = cury; - - //int curind = bitmapList->SelectedIndex; - bitmapList->Items->RemoveAt(bitmapList->SelectedIndex); - - nextPicture(); - nextPicture(); - data.push_back(cbd); - -} - //System::String^ defname; - //System::Int32 ID, x, y; - //System::Int32 townID; -System::Void Wpasujbud::save_Click(System::Object^ sender, System::EventArgs^ e) -{ - String ^n = DateTime::Now.ToString()+".txt"; - n = n->Replace(L" ",L"___")->Replace(':','_'); - IO::StreamWriter sr(IO::Directory::GetCurrentDirectory() + L"\\" + n); - for each (CBuildingData ^Data in data) - { - String ^temp = Data->ToString(); - sr.Write(temp); - } - sr.Close(); -} - -System::Void Wpasujbud::buildingImg_Click(System::Object^ sender, System::EventArgs^ e) -{ - if (!buildingImg->Image) - return; - obrazek ^ob = gcnew obrazek(buildingImg->Image); - ob->Show(); -} -System::Void Wpasujbud::dataview_Click(System::Object^ sender, System::EventArgs^ e) -{ - if (data.size()<=0) - return; - dataEditor ^ de = gcnew dataEditor(%data); - de->Show(); -} \ No newline at end of file diff --git a/tools/Wpasujbud/Wpasujbud.h b/tools/Wpasujbud/Wpasujbud.h deleted file mode 100644 index 0ab671c47..000000000 --- a/tools/Wpasujbud/Wpasujbud.h +++ /dev/null @@ -1,649 +0,0 @@ -#pragma once -#include -#include "data.h" -#include "obrazek.h" -#include "dataEditor.h" -#include -namespace Wpasuj { - - using namespace System; - using namespace System::ComponentModel; - using namespace System::Collections; - using namespace System::Windows::Forms; - using namespace System::Data; - using namespace System::Drawing; - - - /// - /// Summary for Wpasujbud - /// - /// WARNING: If you change the name of this class, you will need to change the - /// 'Resource File Name' property for the managed resource compiler tool - /// associated with all .resx files this class depends on. Otherwise, - /// the designers will not be able to interact properly with localized - /// resources associated with this form. - /// - public ref class Wpasujbud : public System::Windows::Forms::Form - { - public: - cliext::vector data; - - Int32 mx, my, curx, cury; - SDL_Surface * sbg; - private: System::Windows::Forms::TextBox^ foundedCoords; - public: - - public: - - public: - - public: - private: System::Windows::Forms::Label^ label11; - private: System::Windows::Forms::Button^ confirm; - - private: System::Windows::Forms::Label^ label12; - private: System::Windows::Forms::Button^ button3; - private: System::Windows::Forms::TextBox^ accordanceBox; - private: System::Windows::Forms::Button^ button4; - private: System::Windows::Forms::TextBox^ inaccuracy; - private: System::Windows::Forms::Label^ label13; - private: System::Windows::Forms::Button^ save; - - private: System::Windows::Forms::RadioButton^ radioButton3; - private: System::Windows::Forms::Button^ dataview; - private: System::Windows::Forms::Label^ label9; - private: System::Windows::Forms::Label^ label14; - - private: System::Windows::Forms::Button^ button1; - public: - - void searchPicturePos(); - void nextPicture(); - void previousPicture(); - std::string ToString(System::String^ src); - - - obrazek ^curob; - dataEditor ^cured; - - Wpasujbud(void); - - protected: - /// - /// Clean up any resources being used. - /// - ~Wpasujbud() - { - if (components) - { - delete components; - } - } - private: System::Windows::Forms::PictureBox^ townBg; - private: System::Windows::Forms::PictureBox^ buildingImg; - - private: System::Windows::Forms::Label^ label1; - private: System::Windows::Forms::RadioButton^ radioButton1; - private: System::Windows::Forms::RadioButton^ radioButton2; - private: System::Windows::Forms::TextBox^ koordy; - private: System::Windows::Forms::Label^ label2; - private: System::Windows::Forms::ComboBox^ buildingType; - - private: System::Windows::Forms::Label^ label3; - private: System::Windows::Forms::Label^ label4; - private: System::Windows::Forms::ComboBox^ townID; - private: System::Windows::Forms::TextBox^ bmpPattern; - private: System::Windows::Forms::Label^ label5; - private: System::Windows::Forms::ListBox^ bitmapList; - private: System::Windows::Forms::Label^ label6; - private: System::Windows::Forms::Button^ searchBitmaps; - private: System::Windows::Forms::Button^ startLocating; - - private: System::Windows::Forms::TextBox^ townBgPath; - private: System::Windows::Forms::Label^ label7; - private: System::Windows::Forms::Button^ setBackground; - - private: System::Windows::Forms::TextBox^ radious; - private: System::Windows::Forms::Label^ label8; - - - private: System::Windows::Forms::OpenFileDialog^ openFileDialog1; - private: System::Windows::Forms::Button^ browseForBg; - private: System::Windows::Forms::TextBox^ bitmapsFolder; - private: System::Windows::Forms::Label^ label10; - private: System::Windows::Forms::Button^ browseForbmpfol; - - private: System::Windows::Forms::FolderBrowserDialog^ folderBrowserDialog1; - - - protected: - - protected: - - private: - /// - /// Required designer variable. - /// - System::ComponentModel::Container ^components; - -#pragma region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - void InitializeComponent(void) - { - this->townBg = (gcnew System::Windows::Forms::PictureBox()); - this->buildingImg = (gcnew System::Windows::Forms::PictureBox()); - this->label1 = (gcnew System::Windows::Forms::Label()); - this->radioButton1 = (gcnew System::Windows::Forms::RadioButton()); - this->radioButton2 = (gcnew System::Windows::Forms::RadioButton()); - this->koordy = (gcnew System::Windows::Forms::TextBox()); - this->label2 = (gcnew System::Windows::Forms::Label()); - this->buildingType = (gcnew System::Windows::Forms::ComboBox()); - this->label3 = (gcnew System::Windows::Forms::Label()); - this->label4 = (gcnew System::Windows::Forms::Label()); - this->townID = (gcnew System::Windows::Forms::ComboBox()); - this->bmpPattern = (gcnew System::Windows::Forms::TextBox()); - this->label5 = (gcnew System::Windows::Forms::Label()); - this->bitmapList = (gcnew System::Windows::Forms::ListBox()); - this->label6 = (gcnew System::Windows::Forms::Label()); - this->searchBitmaps = (gcnew System::Windows::Forms::Button()); - this->startLocating = (gcnew System::Windows::Forms::Button()); - this->townBgPath = (gcnew System::Windows::Forms::TextBox()); - this->label7 = (gcnew System::Windows::Forms::Label()); - this->setBackground = (gcnew System::Windows::Forms::Button()); - this->radious = (gcnew System::Windows::Forms::TextBox()); - this->label8 = (gcnew System::Windows::Forms::Label()); - this->openFileDialog1 = (gcnew System::Windows::Forms::OpenFileDialog()); - this->browseForBg = (gcnew System::Windows::Forms::Button()); - this->bitmapsFolder = (gcnew System::Windows::Forms::TextBox()); - this->label10 = (gcnew System::Windows::Forms::Label()); - this->browseForbmpfol = (gcnew System::Windows::Forms::Button()); - this->folderBrowserDialog1 = (gcnew System::Windows::Forms::FolderBrowserDialog()); - this->button1 = (gcnew System::Windows::Forms::Button()); - this->foundedCoords = (gcnew System::Windows::Forms::TextBox()); - this->label11 = (gcnew System::Windows::Forms::Label()); - this->confirm = (gcnew System::Windows::Forms::Button()); - this->label12 = (gcnew System::Windows::Forms::Label()); - this->button3 = (gcnew System::Windows::Forms::Button()); - this->accordanceBox = (gcnew System::Windows::Forms::TextBox()); - this->button4 = (gcnew System::Windows::Forms::Button()); - this->inaccuracy = (gcnew System::Windows::Forms::TextBox()); - this->label13 = (gcnew System::Windows::Forms::Label()); - this->save = (gcnew System::Windows::Forms::Button()); - this->radioButton3 = (gcnew System::Windows::Forms::RadioButton()); - this->dataview = (gcnew System::Windows::Forms::Button()); - this->label9 = (gcnew System::Windows::Forms::Label()); - this->label14 = (gcnew System::Windows::Forms::Label()); - (cli::safe_cast(this->townBg))->BeginInit(); - (cli::safe_cast(this->buildingImg))->BeginInit(); - this->SuspendLayout(); - // - // townBg - // - this->townBg->Location = System::Drawing::Point(12, 6); - this->townBg->Name = L"townBg"; - this->townBg->Size = System::Drawing::Size(800, 374); - this->townBg->TabIndex = 0; - this->townBg->TabStop = false; - this->townBg->Click += gcnew System::EventHandler(this, &Wpasujbud::townBg_Click); - // - // buildingImg - // - this->buildingImg->Location = System::Drawing::Point(12, 401); - this->buildingImg->Name = L"buildingImg"; - this->buildingImg->Size = System::Drawing::Size(163, 137); - this->buildingImg->TabIndex = 1; - this->buildingImg->TabStop = false; - this->buildingImg->Click += gcnew System::EventHandler(this, &Wpasujbud::buildingImg_Click); - // - // label1 - // - this->label1->AutoSize = true; - this->label1->Location = System::Drawing::Point(12, 385); - this->label1->Name = L"label1"; - this->label1->Size = System::Drawing::Size(166, 13); - this->label1->TabIndex = 2; - this->label1->Text = L"Current building (click for full size):"; - // - // radioButton1 - // - this->radioButton1->AutoSize = true; - this->radioButton1->Checked = true; - this->radioButton1->Location = System::Drawing::Point(185, 491); - this->radioButton1->Name = L"radioButton1"; - this->radioButton1->Size = System::Drawing::Size(94, 17); - this->radioButton1->TabIndex = 3; - this->radioButton1->TabStop = true; - this->radioButton1->Text = L"Top left corner"; - this->radioButton1->UseVisualStyleBackColor = true; - // - // radioButton2 - // - this->radioButton2->AutoSize = true; - this->radioButton2->Location = System::Drawing::Point(185, 512); - this->radioButton2->Name = L"radioButton2"; - this->radioButton2->Size = System::Drawing::Size(85, 17); - this->radioButton2->TabIndex = 3; - this->radioButton2->Text = L"Middle of pic"; - this->radioButton2->UseVisualStyleBackColor = true; - // - // koordy - // - this->koordy->Location = System::Drawing::Point(185, 470); - this->koordy->Name = L"koordy"; - this->koordy->Size = System::Drawing::Size(121, 20); - this->koordy->TabIndex = 4; - // - // label2 - // - this->label2->AutoSize = true; - this->label2->Location = System::Drawing::Point(214, 456); - this->label2->Name = L"label2"; - this->label2->Size = System::Drawing::Size(67, 13); - this->label2->TabIndex = 5; - this->label2->Text = L"Your coords:"; - // - // buildingType - // - this->buildingType->FormattingEnabled = true; - this->buildingType->Location = System::Drawing::Point(185, 400); - this->buildingType->Name = L"buildingType"; - this->buildingType->Size = System::Drawing::Size(121, 21); - this->buildingType->TabIndex = 6; - // - // label3 - // - this->label3->AutoSize = true; - this->label3->Location = System::Drawing::Point(214, 385); - this->label3->Name = L"label3"; - this->label3->Size = System::Drawing::Size(67, 13); - this->label3->TabIndex = 7; - this->label3->Text = L"Building type"; - // - // label4 - // - this->label4->AutoSize = true; - this->label4->Location = System::Drawing::Point(224, 422); - this->label4->Name = L"label4"; - this->label4->Size = System::Drawing::Size(48, 13); - this->label4->TabIndex = 7; - this->label4->Text = L"Town ID"; - // - // townID - // - this->townID->FormattingEnabled = true; - this->townID->Location = System::Drawing::Point(185, 435); - this->townID->Name = L"townID"; - this->townID->Size = System::Drawing::Size(121, 21); - this->townID->TabIndex = 6; - // - // bmpPattern - // - this->bmpPattern->Location = System::Drawing::Point(317, 467); - this->bmpPattern->Name = L"bmpPattern"; - this->bmpPattern->Size = System::Drawing::Size(121, 20); - this->bmpPattern->TabIndex = 4; - this->bmpPattern->Text = L"*.bmp"; - // - // label5 - // - this->label5->AutoSize = true; - this->label5->Location = System::Drawing::Point(332, 452); - this->label5->Name = L"label5"; - this->label5->Size = System::Drawing::Size(103, 13); - this->label5->TabIndex = 5; - this->label5->Text = L"Search bmp pattern:"; - // - // bitmapList - // - this->bitmapList->Enabled = false; - this->bitmapList->FormattingEnabled = true; - this->bitmapList->Location = System::Drawing::Point(449, 400); - this->bitmapList->Name = L"bitmapList"; - this->bitmapList->Size = System::Drawing::Size(133, 95); - this->bitmapList->TabIndex = 8; - this->bitmapList->SelectedIndexChanged += gcnew System::EventHandler(this, &Wpasujbud::bitmapList_SelectedIndexChanged); - // - // label6 - // - this->label6->AutoSize = true; - this->label6->Location = System::Drawing::Point(485, 384); - this->label6->Name = L"label6"; - this->label6->Size = System::Drawing::Size(57, 13); - this->label6->TabIndex = 9; - this->label6->Text = L"Bitmap list:"; - // - // searchBitmaps - // - this->searchBitmaps->Location = System::Drawing::Point(449, 501); - this->searchBitmaps->Name = L"searchBitmaps"; - this->searchBitmaps->Size = System::Drawing::Size(133, 23); - this->searchBitmaps->TabIndex = 10; - this->searchBitmaps->Text = L"Search bitmaps"; - this->searchBitmaps->UseVisualStyleBackColor = true; - this->searchBitmaps->Click += gcnew System::EventHandler(this, &Wpasujbud::searchBitmaps_Click); - // - // startLocating - // - this->startLocating->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 10, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, - static_cast(238))); - this->startLocating->Location = System::Drawing::Point(696, 464); - this->startLocating->Name = L"startLocating"; - this->startLocating->Size = System::Drawing::Size(120, 29); - this->startLocating->TabIndex = 11; - this->startLocating->Text = L"Search pos!"; - this->startLocating->UseVisualStyleBackColor = true; - this->startLocating->Click += gcnew System::EventHandler(this, &Wpasujbud::startLocating_Click); - // - // townBgPath - // - this->townBgPath->Location = System::Drawing::Point(317, 403); - this->townBgPath->Name = L"townBgPath"; - this->townBgPath->Size = System::Drawing::Size(121, 20); - this->townBgPath->TabIndex = 4; - // - // label7 - // - this->label7->AutoSize = true; - this->label7->Location = System::Drawing::Point(332, 386); - this->label7->Name = L"label7"; - this->label7->Size = System::Drawing::Size(94, 13); - this->label7->TabIndex = 5; - this->label7->Text = L"Town background"; - // - // setBackground - // - this->setBackground->Location = System::Drawing::Point(317, 427); - this->setBackground->Name = L"setBackground"; - this->setBackground->Size = System::Drawing::Size(52, 23); - this->setBackground->TabIndex = 12; - this->setBackground->Text = L"Set bg"; - this->setBackground->UseVisualStyleBackColor = true; - this->setBackground->Click += gcnew System::EventHandler(this, &Wpasujbud::setBackground_Click); - // - // radious - // - this->radious->Location = System::Drawing::Point(591, 441); - this->radious->Name = L"radious"; - this->radious->Size = System::Drawing::Size(98, 20); - this->radious->TabIndex = 13; - this->radious->Text = L"100"; - // - // label8 - // - this->label8->AutoSize = true; - this->label8->Location = System::Drawing::Point(597, 426); - this->label8->Name = L"label8"; - this->label8->Size = System::Drawing::Size(62, 13); - this->label8->TabIndex = 5; - this->label8->Text = L"Search rad:"; - // - // openFileDialog1 - // - this->openFileDialog1->FileName = L"openFileDialog1"; - this->openFileDialog1->Filter = L"BMP Files (*.bmp)|*.bmp|All files (*.*)|*.*"; - this->openFileDialog1->FileOk += gcnew System::ComponentModel::CancelEventHandler(this, &Wpasujbud::openFileDialog1_FileOk); - // - // browseForBg - // - this->browseForBg->Location = System::Drawing::Point(373, 427); - this->browseForBg->Name = L"browseForBg"; - this->browseForBg->Size = System::Drawing::Size(65, 23); - this->browseForBg->TabIndex = 14; - this->browseForBg->Text = L"Browse"; - this->browseForBg->UseVisualStyleBackColor = true; - this->browseForBg->Click += gcnew System::EventHandler(this, &Wpasujbud::browseForBg_Click); - // - // bitmapsFolder - // - this->bitmapsFolder->Location = System::Drawing::Point(317, 505); - this->bitmapsFolder->Name = L"bitmapsFolder"; - this->bitmapsFolder->Size = System::Drawing::Size(121, 20); - this->bitmapsFolder->TabIndex = 4; - // - // label10 - // - this->label10->AutoSize = true; - this->label10->Location = System::Drawing::Point(334, 490); - this->label10->Name = L"label10"; - this->label10->Size = System::Drawing::Size(97, 13); - this->label10->TabIndex = 5; - this->label10->Text = L"Folder with bitmaps"; - // - // browseForbmpfol - // - this->browseForbmpfol->Location = System::Drawing::Point(321, 528); - this->browseForbmpfol->Name = L"browseForbmpfol"; - this->browseForbmpfol->Size = System::Drawing::Size(111, 19); - this->browseForbmpfol->TabIndex = 15; - this->browseForbmpfol->Text = L"Browse"; - this->browseForbmpfol->UseVisualStyleBackColor = true; - this->browseForbmpfol->Click += gcnew System::EventHandler(this, &Wpasujbud::browseForbmpfol_Click); - // - // button1 - // - this->button1->Location = System::Drawing::Point(592, 466); - this->button1->Name = L"button1"; - this->button1->Size = System::Drawing::Size(97, 23); - this->button1->TabIndex = 16; - this->button1->Text = L"Next pic"; - this->button1->UseVisualStyleBackColor = true; - this->button1->Click += gcnew System::EventHandler(this, &Wpasujbud::button1_Click); - // - // foundedCoords - // - this->foundedCoords->Location = System::Drawing::Point(696, 441); - this->foundedCoords->Name = L"foundedCoords"; - this->foundedCoords->Size = System::Drawing::Size(120, 20); - this->foundedCoords->TabIndex = 17; - this->foundedCoords->Text = L"0, 0"; - // - // label11 - // - this->label11->AutoSize = true; - this->label11->Location = System::Drawing::Point(722, 425); - this->label11->Name = L"label11"; - this->label11->Size = System::Drawing::Size(87, 13); - this->label11->TabIndex = 18; - this->label11->Text = L"Founded coords:"; - // - // confirm - // - this->confirm->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 8.25F, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, - static_cast(238))); - this->confirm->Location = System::Drawing::Point(590, 525); - this->confirm->Name = L"confirm"; - this->confirm->Size = System::Drawing::Size(120, 23); - this->confirm->TabIndex = 19; - this->confirm->Text = L"Confirm"; - this->confirm->UseVisualStyleBackColor = true; - this->confirm->Click += gcnew System::EventHandler(this, &Wpasujbud::confirm_Click); - // - // label12 - // - this->label12->AutoSize = true; - this->label12->Location = System::Drawing::Point(722, 385); - this->label12->Name = L"label12"; - this->label12->Size = System::Drawing::Size(68, 13); - this->label12->TabIndex = 21; - this->label12->Text = L"Accordance:"; - // - // button3 - // - this->button3->Location = System::Drawing::Point(736, 496); - this->button3->Name = L"button3"; - this->button3->Size = System::Drawing::Size(83, 23); - this->button3->TabIndex = 22; - this->button3->Text = L"Check pos"; - this->button3->UseVisualStyleBackColor = true; - // - // accordanceBox - // - this->accordanceBox->Enabled = false; - this->accordanceBox->Location = System::Drawing::Point(696, 401); - this->accordanceBox->Name = L"accordanceBox"; - this->accordanceBox->Size = System::Drawing::Size(115, 20); - this->accordanceBox->TabIndex = 20; - this->accordanceBox->Text = L"0/0"; - // - // button4 - // - this->button4->Location = System::Drawing::Point(592, 496); - this->button4->Name = L"button4"; - this->button4->Size = System::Drawing::Size(83, 23); - this->button4->TabIndex = 23; - this->button4->Text = L"Previous pic"; - this->button4->UseVisualStyleBackColor = true; - this->button4->Click += gcnew System::EventHandler(this, &Wpasujbud::button4_Click); - // - // inaccuracy - // - this->inaccuracy->Location = System::Drawing::Point(592, 401); - this->inaccuracy->Name = L"inaccuracy"; - this->inaccuracy->Size = System::Drawing::Size(98, 20); - this->inaccuracy->TabIndex = 20; - this->inaccuracy->Text = L"5"; - this->inaccuracy->TextChanged += gcnew System::EventHandler(this, &Wpasujbud::inaccuracy_TextChanged); - // - // label13 - // - this->label13->AutoSize = true; - this->label13->Location = System::Drawing::Point(587, 385); - this->label13->Name = L"label13"; - this->label13->Size = System::Drawing::Size(88, 13); - this->label13->TabIndex = 21; - this->label13->Text = L"Inaccuracy level:"; - // - // save - // - this->save->Location = System::Drawing::Point(681, 497); - this->save->Name = L"save"; - this->save->Size = System::Drawing::Size(48, 23); - this->save->TabIndex = 24; - this->save->Text = L"Save"; - this->save->UseVisualStyleBackColor = true; - this->save->Click += gcnew System::EventHandler(this, &Wpasujbud::save_Click); - // - // radioButton3 - // - this->radioButton3->AutoSize = true; - this->radioButton3->Location = System::Drawing::Point(185, 531); - this->radioButton3->Name = L"radioButton3"; - this->radioButton3->Size = System::Drawing::Size(114, 17); - this->radioButton3->TabIndex = 3; - this->radioButton3->Text = L"Bottom right corner"; - this->radioButton3->UseVisualStyleBackColor = true; - // - // dataview - // - this->dataview->Location = System::Drawing::Point(449, 528); - this->dataview->Name = L"dataview"; - this->dataview->Size = System::Drawing::Size(135, 21); - this->dataview->TabIndex = 25; - this->dataview->Text = L"Data view/edition"; - this->dataview->UseVisualStyleBackColor = true; - this->dataview->Click += gcnew System::EventHandler(this, &Wpasujbud::dataview_Click); - // - // label9 - // - this->label9->AutoSize = true; - this->label9->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 9, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, - static_cast(238))); - this->label9->Location = System::Drawing::Point(722, 523); - this->label9->Name = L"label9"; - this->label9->Size = System::Drawing::Size(99, 15); - this->label9->TabIndex = 26; - this->label9->Text = L"By VCMI Team"; - // - // label14 - // - this->label14->AutoSize = true; - this->label14->Font = (gcnew System::Drawing::Font(L"Microsoft Sans Serif", 9, System::Drawing::FontStyle::Bold, System::Drawing::GraphicsUnit::Point, - static_cast(238))); - this->label14->Location = System::Drawing::Point(742, 538); - this->label14->Name = L"label14"; - this->label14->Size = System::Drawing::Size(53, 15); - this->label14->TabIndex = 27; - this->label14->Text = L"© 2008"; - // - // Wpasujbud - // - this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); - this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; - this->ClientSize = System::Drawing::Size(823, 554); - this->Controls->Add(this->label14); - this->Controls->Add(this->label9); - this->Controls->Add(this->dataview); - this->Controls->Add(this->save); - this->Controls->Add(this->button4); - this->Controls->Add(this->button3); - this->Controls->Add(this->label13); - this->Controls->Add(this->label12); - this->Controls->Add(this->inaccuracy); - this->Controls->Add(this->accordanceBox); - this->Controls->Add(this->confirm); - this->Controls->Add(this->label11); - this->Controls->Add(this->foundedCoords); - this->Controls->Add(this->button1); - this->Controls->Add(this->browseForbmpfol); - this->Controls->Add(this->browseForBg); - this->Controls->Add(this->radious); - this->Controls->Add(this->setBackground); - this->Controls->Add(this->startLocating); - this->Controls->Add(this->searchBitmaps); - this->Controls->Add(this->label6); - this->Controls->Add(this->bitmapList); - this->Controls->Add(this->label4); - this->Controls->Add(this->label3); - this->Controls->Add(this->townID); - this->Controls->Add(this->buildingType); - this->Controls->Add(this->label8); - this->Controls->Add(this->label7); - this->Controls->Add(this->label10); - this->Controls->Add(this->label5); - this->Controls->Add(this->label2); - this->Controls->Add(this->bitmapsFolder); - this->Controls->Add(this->townBgPath); - this->Controls->Add(this->bmpPattern); - this->Controls->Add(this->koordy); - this->Controls->Add(this->radioButton3); - this->Controls->Add(this->radioButton2); - this->Controls->Add(this->radioButton1); - this->Controls->Add(this->label1); - this->Controls->Add(this->buildingImg); - this->Controls->Add(this->townBg); - this->MaximizeBox = false; - this->Name = L"Wpasujbud"; - this->Text = L"Cudowny wpasowywacz 1.00"; - (cli::safe_cast(this->townBg))->EndInit(); - (cli::safe_cast(this->buildingImg))->EndInit(); - this->ResumeLayout(false); - this->PerformLayout(); - - } -#pragma endregion - private: - System::Void searchBitmaps_Click(System::Object^ sender, System::EventArgs^ e); - System::Void startLocating_Click(System::Object^ sender, System::EventArgs^ e); - System::Void setBackground_Click(System::Object^ sender, System::EventArgs^ e); - System::Void openFileDialog1_FileOk(System::Object^ sender, System::ComponentModel::CancelEventArgs^ e) ; - System::Void browseForBg_Click(System::Object^ sender, System::EventArgs^ e); - System::Void browseForbmpfol_Click(System::Object^ sender, System::EventArgs^ e); - System::Void bitmapList_SelectedIndexChanged(System::Object^ sender, System::EventArgs^ e); - System::Void townBg_Click(System::Object^ sender, System::EventArgs^ e); - System::Void button1_Click(System::Object^ sender, System::EventArgs^ e); - System::Void inaccuracy_TextChanged(System::Object^ sender, System::EventArgs^ e); - System::Void confirm_Click(System::Object^ sender, System::EventArgs^ e); - System::Void button4_Click(System::Object^ sender, System::EventArgs^ e) { - previousPicture(); - } - System::Void save_Click(System::Object^ sender, System::EventArgs^ e); - System::Void buildingImg_Click(System::Object^ sender, System::EventArgs^ e); - System::Void dataview_Click(System::Object^ sender, System::EventArgs^ e); - -}; - -} - diff --git a/tools/Wpasujbud/config/BNAMES.txt b/tools/Wpasujbud/config/BNAMES.txt deleted file mode 100644 index 82caf4c15..000000000 --- a/tools/Wpasujbud/config/BNAMES.txt +++ /dev/null @@ -1,44 +0,0 @@ -0 Mage guild 1 -1 Mage guild 2 -2 Mage guild 3 -3 Mage guild 4 -4 Mage guild 5 -5 tavern -6 shipyard when it's present:)) -7 fort -8 citadel -9 castle -10 village hall -11 town hall -12 city hall -13 capitol -14 marketplace -15 resource silo -16 blacksmith -17 lighthouse(0) mystic pond(1) artifact merchants(2,5,8) veil of darkness(4) escape tunnel(6) cage of warlords(7) -18 horde buildings for non-upgraded creatures: Griffins, dwarves, stone gargoyles, imps, skeletons, troglodytes, goblins, gnolls, pixies. -19 horde buildings for upgraded creatures Royal griffins, battle dwarves, obsidian gargoyles, familiars, skeleton warriors, infernal troglodytes, hobgoblins, gnoll marauders, sprites -20 Ship at the Shipyard -21 stables(0) fountain of fortune(1) lookout tower(2) brimstone clouds(3) necromancy amplifier(4) mana vortex(5) freelancer's guild(6) glyphs of fear(7) magic university(8) -22 brotherhood of sword(0) dwarven treasury(1) library(2) castle gates(3) skeleton transformer(4) portal of summoning(5) ballista yard(6) blood obelisk(7) -23 wall of Knowledge.(2) order of fire(3) academy of battle scholars(5) hall of valhalla(6) -24 horde buildings for non-upgraded creatures: dendroid guards, hell hounds -25 horde buildings for upgraded creatures: Dendroid soldiers, Cerberi -26 Grail -27 Houses near city hall -28 Houses near municipal -29 Houses near Capitol -30 dwelling 1 -31 dwelling 2 -32 dwelling 3 -33 dwelling 4 -34 dwelling 5 -35 dwelling 6 -36 dwelling 7 -37 upgraded dwelling 1 -38 upgraded dwelling 2 -39 upgraded dwelling 3 -40 upgraded dwelling 4 -41 upgraded dwelling 5 -42 upgraded dwelling 6 -43 upgraded dwelling 7 diff --git a/tools/Wpasujbud/config/TOWNTYPE.TXT b/tools/Wpasujbud/config/TOWNTYPE.TXT deleted file mode 100644 index f2e154580..000000000 --- a/tools/Wpasujbud/config/TOWNTYPE.TXT +++ /dev/null @@ -1,9 +0,0 @@ -Castle -Rampart -Tower -Inferno -Necropolis -Dungeon -Stronghold -Fortress -Conflux diff --git a/tools/Wpasujbud/data.h b/tools/Wpasujbud/data.h deleted file mode 100644 index 6ec54ad59..000000000 --- a/tools/Wpasujbud/data.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once -public ref class CBuildingData -{ -public: - System::String^ defname; - System::Int32 ID, x, y; - System::Int32 townID; - virtual System::String^ ToString()override - { - return townID.ToString() + L" " + ID.ToString() + L" " + defname + L" " + x.ToString() + L" " + y.ToString() + L"\n"; - } -}; \ No newline at end of file diff --git a/tools/Wpasujbud/dataEditor.cpp b/tools/Wpasujbud/dataEditor.cpp deleted file mode 100644 index 5bd79ee72..000000000 --- a/tools/Wpasujbud/dataEditor.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#include "dataEditor.h" - diff --git a/tools/Wpasujbud/dataEditor.h b/tools/Wpasujbud/dataEditor.h deleted file mode 100644 index 1ff83d23c..000000000 --- a/tools/Wpasujbud/dataEditor.h +++ /dev/null @@ -1,209 +0,0 @@ -#pragma once -#include "data.h" -#include -using namespace System; -using namespace System::ComponentModel; -using namespace System::Collections; -using namespace System::Windows::Forms; -using namespace System::Data; -using namespace System::Drawing; - - -namespace Wpasuj { - - /// - /// Summary for dataEditor - /// - /// WARNING: If you change the name of this class, you will need to change the - /// 'Resource File Name' property for the managed resource compiler tool - /// associated with all .resx files this class depends on. Otherwise, - /// the designers will not be able to interact properly with localized - /// resources associated with this form. - /// - public ref class dataEditor : public System::Windows::Forms::Form - { - public: - dataEditor(cliext::vector ^Data) - { - data = Data; - InitializeComponent(); - dataGridView1->Rows->Add(data->size()); - for (int i=0;isize();i++) - { - dataGridView1->Rows[i]->Cells[0]->Value = data->at(i)->townID; - dataGridView1->Rows[i]->Cells[1]->Value = data->at(i)->ID; - dataGridView1->Rows[i]->Cells[2]->Value = data->at(i)->defname; - dataGridView1->Rows[i]->Cells[3]->Value = data->at(i)->x; - dataGridView1->Rows[i]->Cells[4]->Value = data->at(i)->y; - } - } - private: System::Windows::Forms::DataGridViewTextBoxColumn^ townid; - public: - private: System::Windows::Forms::DataGridViewTextBoxColumn^ buildingID; - private: System::Windows::Forms::DataGridViewTextBoxColumn^ defname; - private: System::Windows::Forms::DataGridViewTextBoxColumn^ x; - private: System::Windows::Forms::DataGridViewTextBoxColumn^ y; - private: System::Windows::Forms::Button^ save; - private: System::Windows::Forms::Button^ clear; - private: System::Windows::Forms::Button^ close; - private: - - cliext::vector ^data; - protected: - /// - /// Clean up any resources being used. - /// - ~dataEditor() - { - if (components) - { - delete components; - } - } - private: System::Windows::Forms::DataGridView^ dataGridView1; - - - - - - protected: - - protected: - - private: - /// - /// Required designer variable. - /// - System::ComponentModel::Container ^components; - -#pragma region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - void InitializeComponent(void) - { - this->dataGridView1 = (gcnew System::Windows::Forms::DataGridView()); - this->townid = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); - this->buildingID = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); - this->defname = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); - this->x = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); - this->y = (gcnew System::Windows::Forms::DataGridViewTextBoxColumn()); - this->save = (gcnew System::Windows::Forms::Button()); - this->clear = (gcnew System::Windows::Forms::Button()); - this->close = (gcnew System::Windows::Forms::Button()); - (cli::safe_cast(this->dataGridView1))->BeginInit(); - this->SuspendLayout(); - // - // dataGridView1 - // - this->dataGridView1->ColumnHeadersHeightSizeMode = System::Windows::Forms::DataGridViewColumnHeadersHeightSizeMode::AutoSize; - this->dataGridView1->Columns->AddRange(gcnew cli::array< System::Windows::Forms::DataGridViewColumn^ >(5) {this->townid, - this->buildingID, this->defname, this->x, this->y}); - this->dataGridView1->Location = System::Drawing::Point(12, 12); - this->dataGridView1->Name = L"dataGridView1"; - this->dataGridView1->Size = System::Drawing::Size(334, 276); - this->dataGridView1->TabIndex = 0; - // - // townid - // - this->townid->HeaderText = L"Town ID"; - this->townid->Name = L"townid"; - this->townid->Width = 50; - // - // buildingID - // - this->buildingID->HeaderText = L"Building ID"; - this->buildingID->Name = L"buildingID"; - this->buildingID->Width = 60; - // - // defname - // - this->defname->HeaderText = L"Def name"; - this->defname->Name = L"defname"; - this->defname->Width = 120; - // - // x - // - this->x->HeaderText = L"X"; - this->x->Name = L"x"; - this->x->Width = 30; - // - // y - // - this->y->HeaderText = L"Y"; - this->y->Name = L"y"; - this->y->Width = 30; - // - // save - // - this->save->Location = System::Drawing::Point(12, 294); - this->save->Name = L"save"; - this->save->Size = System::Drawing::Size(105, 23); - this->save->TabIndex = 1; - this->save->Text = L"Save changes"; - this->save->UseVisualStyleBackColor = true; - this->save->Click += gcnew System::EventHandler(this, &dataEditor::save_Click); - // - // clear - // - this->clear->Location = System::Drawing::Point(248, 294); - this->clear->Name = L"clear"; - this->clear->Size = System::Drawing::Size(96, 23); - this->clear->TabIndex = 2; - this->clear->Text = L"Clear changes"; - this->clear->UseVisualStyleBackColor = true; - this->clear->Click += gcnew System::EventHandler(this, &dataEditor::clear_Click); - // - // close - // - this->close->Location = System::Drawing::Point(123, 294); - this->close->Name = L"close"; - this->close->Size = System::Drawing::Size(119, 23); - this->close->TabIndex = 3; - this->close->Text = L"Close"; - this->close->UseVisualStyleBackColor = true; - this->close->Click += gcnew System::EventHandler(this, &dataEditor::close_Click); - // - // dataEditor - // - this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); - this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; - this->ClientSize = System::Drawing::Size(356, 328); - this->Controls->Add(this->close); - this->Controls->Add(this->clear); - this->Controls->Add(this->save); - this->Controls->Add(this->dataGridView1); - this->Name = L"dataEditor"; - this->Text = L"dataEditor"; - (cli::safe_cast(this->dataGridView1))->EndInit(); - this->ResumeLayout(false); - - } -#pragma endregion - - private: System::Void clear_Click(System::Object^ sender, System::EventArgs^ e) { - for (int i=0;isize();i++) - { - dataGridView1->Rows[i]->Cells[0]->Value = data->at(i)->townID; - dataGridView1->Rows[i]->Cells[1]->Value = data->at(i)->ID; - dataGridView1->Rows[i]->Cells[2]->Value = data->at(i)->defname; - dataGridView1->Rows[i]->Cells[3]->Value = data->at(i)->x; - dataGridView1->Rows[i]->Cells[4]->Value = data->at(i)->y; - } - } -private: System::Void close_Click(System::Object^ sender, System::EventArgs^ e) { - Close(); - } -private: System::Void save_Click(System::Object^ sender, System::EventArgs^ e) { - for (int i=0;isize();i++) - { - data->at(i)->townID = Convert::ToInt32( static_cast(dataGridView1->Rows[i]->Cells[0]->Value)); - data->at(i)->ID = Convert::ToInt32( static_cast(dataGridView1->Rows[i]->Cells[1]->Value)); - data->at(i)->defname = static_cast(dataGridView1->Rows[i]->Cells[2]->Value); - data->at(i)->x = Convert::ToInt32( static_cast(dataGridView1->Rows[i]->Cells[3]->Value)); - data->at(i)->y = Convert::ToInt32( static_cast(dataGridView1->Rows[i]->Cells[4]->Value)); - } - } -}; -} diff --git a/tools/Wpasujbud/obrazek.cpp b/tools/Wpasujbud/obrazek.cpp deleted file mode 100644 index f4a63a41b..000000000 --- a/tools/Wpasujbud/obrazek.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#include "obrazek.h" - diff --git a/tools/Wpasujbud/obrazek.h b/tools/Wpasujbud/obrazek.h deleted file mode 100644 index c5b7c50d9..000000000 --- a/tools/Wpasujbud/obrazek.h +++ /dev/null @@ -1,121 +0,0 @@ -#pragma once - -using namespace System; -using namespace System::ComponentModel; -using namespace System::Collections; -using namespace System::Windows::Forms; -using namespace System::Data; -using namespace System::Drawing; - - -namespace Wpasuj { - - /// - /// Summary for obrazek - /// - /// WARNING: If you change the name of this class, you will need to change the - /// 'Resource File Name' property for the managed resource compiler tool - /// associated with all .resx files this class depends on. Otherwise, - /// the designers will not be able to interact properly with localized - /// resources associated with this form. - /// - public ref class obrazek : public System::Windows::Forms::Form - { - public: - obrazek(System::Drawing::Image^ img) - { - InitializeComponent(img); - } - - protected: - /// - /// Clean up any resources being used. - /// - ~obrazek() - { - if (components) - { - delete components; - } - } - private: System::Windows::Forms::PictureBox^ pictureBox1; - private: System::Windows::Forms::TrackBar^ trackBar1; - private: System::Windows::Forms::Label^ Transparency; - protected: - - private: - /// - /// Required designer variable. - /// - System::ComponentModel::Container ^components; - -#pragma region Windows Form Designer generated code - /// - /// Required method for Designer support - do not modify - /// the contents of this method with the code editor. - /// - void InitializeComponent(System::Drawing::Image^ img) - { - this->pictureBox1 = (gcnew System::Windows::Forms::PictureBox()); - (cli::safe_cast(this->pictureBox1))->BeginInit(); - this->SuspendLayout(); - // - // pictureBox1 - // - this->pictureBox1->Location = System::Drawing::Point(12, 12); - this->pictureBox1->Name = L"pictureBox1"; - this->pictureBox1->Size = System::Drawing::Size(img->Width,img->Height);//(268, 242); - this->pictureBox1->TabIndex = 0; - this->pictureBox1->TabStop = false; - this->pictureBox1->Image = img; - this->pictureBox1->Click += gcnew System::EventHandler(this,&obrazek::obrazek_Click); - - - - this->Transparency = (gcnew System::Windows::Forms::Label()); - this->Transparency->AutoSize = true; - this->Transparency->Location = System::Drawing::Point(12, img->Height+70); - this->Transparency->Name = L"label13"; - this->Transparency->Size = System::Drawing::Size(110, 13); - this->Transparency->TabIndex = 21; - this->Transparency->Text = L"Window transparency"; - - - this->trackBar1 = (gcnew System::Windows::Forms::TrackBar()); - this->trackBar1->Location = System::Drawing::Point(12, img->Height+24); - this->trackBar1->Name = L"trackBar1"; - this->trackBar1->Size = System::Drawing::Size(img->Width, 45); - this->trackBar1->TabIndex = 26; - this->trackBar1->Minimum = 0; - this->trackBar1->Maximum = 255; - this->trackBar1->Value = 255; - this->trackBar1->TickFrequency=1; - this->trackBar1->ValueChanged += gcnew System::EventHandler(this,&obrazek::suwakiemRuszono); - - // - // obrazek - // - this->AutoScaleDimensions = System::Drawing::SizeF(6, 13); - this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font; - this->ClientSize = System::Drawing::Size(img->Width+24,img->Height+94);//(292, 266); - this->Controls->Add(this->pictureBox1); - this->Controls->Add(this->trackBar1); - this->Controls->Add(this->Transparency); - this->Click += gcnew System::EventHandler(this,&obrazek::obrazek_Click); - this->Name = L"obrazek"; - this->Text = L"Picture window"; - (cli::safe_cast(this->pictureBox1))->EndInit(); - this->ResumeLayout(false); - - - } -#pragma endregion - - private: System::Void obrazek_Click(System::Object^ sender, System::EventArgs^ e) { - Close(); - } - private: System::Void suwakiemRuszono(System::Object^ sender, System::EventArgs^ e) { - Opacity = trackBar1->Value/((double)255); - } - }; -}