/** Called by the map-selecting CglList. */ void CPreGame::SelectMap(std::string s) { if (s == "Random map") { s = pregame->showList->items[1 + gu->usRandInt() % (pregame->showList->items.size() - 1)]; } stupidGlobalMapname = pregame->mapName = s; delete pregame->showList; pregame->showList = 0; logOutput << "Map: " << s.c_str() << "\n"; // Determine if the map is inside an archive, and possibly map needed archives CFileHandler* f = SAFE_NEW CFileHandler("maps/" + s); if (!f->FileExists()) { vector<string> ars = archiveScanner->GetArchivesForMap(s); if (ars.empty()) throw content_error("Couldn't find any archives for map '" + s + "'."); for (vector<string>::iterator i = ars.begin(); i != ars.end(); ++i) { if (!hpiHandler->AddArchive(*i, false)) throw content_error("Couldn't load archive '" + *i + "' for map '" + s + "'."); } } delete f; if (net && net->GetDemoRecorder()) net->GetDemoRecorder()->SetName(s); }
bool CMouseCursor::BuildFromFileNames(const string& name, int lastFrame) { // find the image file type to use const char* ext = ""; const char* exts[] = { "png", "tga", "bmp" }; const int extCount = sizeof(exts) / sizeof(exts[0]); for (int e = 0; e < extCount; e++) { ext = exts[e]; std::ostringstream namebuf; namebuf << "anims/" << name << "_0." << ext; CFileHandler* f = new CFileHandler(namebuf.str()); if (f->FileExists()) { delete f; break; } delete f; } while (int(frames.size()) < lastFrame) { std::ostringstream namebuf; namebuf << "anims/" << name << "_" << frames.size() << "." << ext; ImageData image; if (!LoadCursorImage(namebuf.str(), image)) break; images.push_back(image); FrameData frame(image, defFrameLength); frames.push_back(frame); } hwCursor->Finish(); return true; }
int CAICallback::GetFileSize (const char *filename, const char* modes) { CFileHandler fh (filename, modes); if (!fh.FileExists ()) return -1; return fh.FileSize(); }
int CAICallback::GetFileSize (const char *name) { CFileHandler fh (name); if (!fh.FileExists ()) return -1; return fh.FileSize(); }
bool CAICallback::ReadFile (const char *name, void *buffer, int bufferLength) { CFileHandler fh (name); int fs; if (!fh.FileExists() || bufferLength < (fs = fh.FileSize())) return false; fh.Read (buffer, fs); return true; }
int CArchiveDir::OpenFile(const std::string& fileName) { CFileHandler* f = SAFE_NEW CFileHandler(archiveName + lcNameToOrigName[StringToLower(fileName)]); if (!f || !f->FileExists()) return 0; ++curFileHandle; fileHandles[curFileHandle] = f; return curFileHandle; }
// returns next line (without newlines) string SimpleParser::GetLine(CFileHandler& fh) { lineNumber++; char a; string s = ""; while (!fh.Eof()) { fh.Read(&a, 1); if (a == '\n') { break; } if (a != '\r') { s += a; } } return s; }
string CUnit3DLoader::GetLine(CFileHandler& fh) { string s=""; char a; fh.Read(&a,1); while(a!='\xd' && a!='\xa'){ s+=a; fh.Read(&a,1); if(fh.Eof()) break; } return s; }
static std::string GetLine(CFileHandler& fh) { std::string s = ""; char a; fh.Read(&a, 1); while (a!='\n' && a!='\r') { s += a; fh.Read(&a, 1); if (fh.Eof()) break; } return s; }
// returns next line (without newlines) static string GetLine(CFileHandler& fh) { lineNumber++; char a; string s = ""; while (true) { a = fh.Peek(); if (a == EOF) { break; } fh.Read(&a, 1); if (a == '\n') { break; } if (a != '\r') { s += a; } } return s; }
// returns next non-blank line (without newlines or comments) static string GetCleanLine(CFileHandler& fh) { string::size_type pos; while (true) { if (fh.Eof()) { return ""; // end of file } string line = GetLine(fh); pos = line.find_first_not_of(" \t"); if (pos == string::npos) { continue; // blank line } pos = line.find("//"); if (pos != string::npos) { line.erase(pos); pos = line.find_first_not_of(" \t"); if (pos == string::npos) { continue; // blank line (after removing comments) } } return line; } }
/// Read TileFileHeader head from file src void CSMFMapFile::ReadMapTileFileHeader(TileFileHeader& head, CFileHandler& file) { file.Read(&head.magic,sizeof(head.magic)); head.version = ReadInt(file); head.numTiles = ReadInt(file); head.tileSize = ReadInt(file); head.compressionType = ReadInt(file); }
int VorbisStreamSeek(void* datasource, ogg_int64_t offset, int whence) { CFileHandler* buffer = static_cast<CFileHandler*>(datasource); if (whence == SEEK_SET) { buffer->Seek(offset, std::ios_base::beg); } else if (whence == SEEK_CUR) { buffer->Seek(offset, std::ios_base::cur); } else if (whence == SEEK_END) { buffer->Seek(offset, std::ios_base::end); } return 0; }
void CTAPalette::Init(CFileHandler& paletteFile) { for (unsigned c = 0; c < NUM_PALETTE_ENTRIES; ++c) { for (unsigned c2 = 0; c2 < 4; ++c2) { paletteFile.Read(&p[c][c2], 1); } p[c][3] = 255; } }
std::string CSpawnScript::LoadToken(CFileHandler& file) { std::string s; char c; while (!file.Eof()) { file.Read(&c,1); if(c>='0' && c<='z') break; } s += c; while (!file.Eof()) { file.Read(&c,1); if(c<'0' || c>'z') return s; s+=c; } return s; }
void CPreGame::LoadMap(const std::string& mapName, const bool forceReload) { static bool alreadyLoaded = false; if (!alreadyLoaded || forceReload) { CFileHandler* f = new CFileHandler("maps/" + mapName); if (!f->FileExists()) { vector<string> ars = archiveScanner->GetArchivesForMap(mapName); if (ars.empty()) { throw content_error("Couldn't find any archives for map '" + mapName + "'."); } for (vector<string>::iterator i = ars.begin(); i != ars.end(); ++i) { if (!vfsHandler->AddArchive(*i, false)) { throw content_error("Couldn't load archive '" + *i + "' for map '" + mapName + "'."); } } } delete f; alreadyLoaded = true; } }
bool CMouseCursor::LoadCursorImage(const string& name, ImageData& image) { CFileHandler* f = new CFileHandler(name); if (!f->FileExists()) { return false; } CBitmap b; if (!b.Load(name)) { logOutput.Print("CMouseCursor: Bad image file: %s", name.c_str()); return false; } b.ReverseYAxis(); CBitmap* final = getAlignedBitmap(b); // coded bmp transparency mask if ((name.size() >= 3) && (StringToLower(name.substr(name.size() - 3)) == "bmp")) { setBitmapTransparency(*final, 84, 84, 252); }
void CTileHandler::ProcessTiles2(void) { unsigned char* data=new unsigned char[1024*1024*4]; bigTex=CBitmap(data,1,1); /// /free big tex memory int tilex=xsize/4; int tiley=ysize/4; for(int a=0;a<(tilex*tiley)/1024;++a){ int startTile=a*1024; char name[100]; DDSURFACEDESC2 ddsheader; int ddssignature; CFileHandler file; if (prog == "nvdxt.exe " || prog == "nvcompress.exe " || prog == "texconv.exe " || prog == "old_nvdxt.exe "){ sprintf(name,"Temp%03i.dds",a); file.Open(name); file.Read(&ddssignature, sizeof(int)); file.Read(&ddsheader, sizeof(DDSURFACEDESC2)); } if (prog == "texcompress.exe "){ sprintf(name, "temp\\Temp%03i.png.raw", a); file.Open(name); } char bigtile[696320]; // /1024x1024 and 4 mipmaps file.Read(bigtile, 696320); for(int b=0;b<1024;++b){ int x=b%32; int y=b/32; int xb=(startTile+b)%tilex; int yb=(startTile+b)/tilex; char* ctile=new char[SMALL_TILE_SIZE]; ReadTile(x*32,y*32,ctile,bigtile); CBitmap* bm=new CBitmap(); bm->CreateFromDXT1((unsigned char*)ctile,32,32); int t1=tileUse[max(0,(yb-1)*tilex+xb)]; int t2=tileUse[max(0,yb*tilex+xb-1)]; int ct=FindCloseTile(bm,t1==t2?t1:-1); if(ct==-1){ tileUse[yb*tilex+xb]=usedTiles; tiles[usedTiles++]=bm; newTiles.push_back(ctile); } else { tileUse[yb*tilex+xb]=ct; delete bm; delete[] ctile; } } printf("Creating tiles %i/%i %i%%\n", usedTiles-numExternalTile,(a+1)*1024,(((a+1)*1024)*100)/(tilex*tiley)); } delete[] data; }
bool CMouseCursor::BuildFromFileNames(const string& name, int lastFrame) { char namebuf[128]; if (name.size() > (sizeof(namebuf) - 20)) { logOutput.Print("CMouseCursor: Long name %s", name.c_str()); return false; } // find the image file type to use const char* ext = ""; const char* exts[] = { "png", "tga", "bmp" }; const int extCount = sizeof(exts) / sizeof(exts[0]); for (int e = 0; e < extCount; e++) { ext = exts[e]; SNPRINTF(namebuf, sizeof(namebuf), "anims/%s_%d.%s", name.c_str(), 0, ext); CFileHandler* f = new CFileHandler(namebuf); if (f->FileExists()) { delete f; break; } delete f; } while (frames.size() < lastFrame) { SNPRINTF(namebuf, sizeof(namebuf), "anims/%s_%d.%s", name.c_str(), frames.size(), ext); ImageData image; if (!LoadCursorImage(namebuf, image)) { break; } images.push_back(image); FrameData frame(image, defFrameLength); frames.push_back(frame); } return true; }
static void GetWord(CFileHandler& fh, std::string &s) { char a = fh.Peek(); while (a == ' ' || a == '\n' || a == '\r') { fh.Read(&a, 1); a = fh.Peek(); if (fh.Eof()) break; } s = ""; fh.Read(&a, 1); while (a != ',' && a != ' ' && a != '\n' && a != '\r') { s += a; fh.Read(&a, 1); if (fh.Eof()) break; } }
string CUnit3DLoader::GetWord(CFileHandler& fh) { char a=fh.Peek(); while(a==' ' || a=='\xd' || a=='\xa'){ fh.Read(&a,1); a=fh.Peek(); if(fh.Eof()) break; } string s=""; fh.Read(&a,1); while(a!=',' && a!=' ' && a!='\xd' && a!='\xa'){ s+=a; fh.Read(&a,1); if(fh.Eof()) break; } return s; }
/// Read SMFHeader head from file void CSMFMapFile::ReadMapHeader(SMFHeader& head, CFileHandler& file) { file.Read(head.magic,sizeof(head.magic)); head.version = ReadInt(file); head.mapid = ReadInt(file); head.mapx = ReadInt(file); head.mapy = ReadInt(file); head.squareSize = ReadInt(file); head.texelPerSquare = ReadInt(file); head.tilesize = ReadInt(file); head.minHeight = ReadFloat(file); head.maxHeight = ReadFloat(file); head.heightmapPtr = ReadInt(file); head.typeMapPtr = ReadInt(file); head.tilesPtr = ReadInt(file); head.minimapPtr = ReadInt(file); head.metalmapPtr = ReadInt(file); head.featurePtr = ReadInt(file); head.numExtraHeaders = ReadInt(file); }
void CParticiple::splitter(const char *szPath, const char *szMark) { int nTmp; int nIndex; int nIndexPhase; CFileHandler fh; set<string> setData; CMysqlHandler mysql; CString strSQL; set<string>::const_iterator iter_set; CString strFileName; CString strFilePath; string strContent; vector<string> vecPhase; fh.readPath(szPath, setData); if(0 >= setData.size()) { _log("[CParticiple] splitter Path: %s no file", szPath); return; } mysql.connect(EDUBOT_HOST, EDUBOT_DB, EDUBOT_ACCOUNT, EDUBOT_PASSWD, "5"); if(!mysql.isValid()) { _log("[CParticiple] splitter MySQL invalid"); return; } for(iter_set = setData.begin(); setData.end() != iter_set; ++iter_set) { nIndex = iter_set->rfind("."); if((int) string::npos != nIndex) { if(!iter_set->substr(nIndex + 1).compare("txt")) { strFileName = trim(iter_set->substr(0, nIndex)); _log("[CParticiple] splitter Start analysis file: %s", iter_set->c_str()); strFilePath.format("%s%s", szPath, iter_set->c_str()); strContent.clear(); if(!fh.readContent(strFilePath.getBuffer(), strContent, true)) continue; strSQL.format("DELETE FROM story_affective WHERE story = '%s'", strFileName.getBuffer()); mysql.sqlExec(strSQL.toString()); //======= 特殊符號替換 =======// strContent = ReplaceAll(strContent, "。”", "”。"); strContent = ReplaceAll(strContent, "。」", "」。"); _log("[CParticiple] splitter Content: %s", strContent.c_str()); //======= 字串分詞 ========// int nIndex = 0; int nLen = 0; int nCount = 0; CString strPart; while(1) { if(nCount) nIndex = nIndex + nLen + strlen(szMark); nLen = strContent.find(szMark, nIndex); if((int) string::npos == nLen) break; nLen = nLen - nIndex; printf("index=%d , size=%d\n", nIndex, nLen); strPart = strContent.substr(nIndex, nLen); printf("part: %s\n", strPart.getBuffer()); strSQL.format("INSERT INTO story_affective (story,numbering,sentence)VALUES('%s',%d,'%s')", strFileName.getBuffer(),nCount,strPart.getBuffer()); mysql.sqlExec(strSQL.toString()); ++nCount; } } } } mysql.close(); }
bool CPreGame::Update() { assert(good_fpu_control_registers("CPreGame::Update")); switch (state) { case UNKNOWN: logOutput.Print("Internal error in CPreGame"); return false; case WAIT_ON_ADDRESS: if (userWriting) break; if (saveAddress) configHandler.SetString("address",userInput); if(net->InitClient(userInput.c_str(),8452,0)==-1){ logOutput.Print("Client couldn't connect"); return false; } // State is never WAIT_ON_ADDRESS if gameSetup was true in our constructor, // so if it's true here, it means net->InitClient() just loaded a demo // with gameSetup. // If so, don't wait indefinitely on a script/map/mod name, but load // everything from gameSetup and switch to ALL_READY state. if(gameSetup) { CScriptHandler::SelectScript("Commanders"); SelectMap(gameSetup->mapname); SelectMod(gameSetup->baseMod); state = ALL_READY; break; } else { state = WAIT_ON_SCRIPT; // fall trough } case WAIT_ON_SCRIPT: if (showList || !server) break; mapName = CScriptHandler::Instance().chosenScript->GetMapName(); if (mapName == "") ShowMapList(); state = WAIT_ON_MAP; // fall through case WAIT_ON_MAP: if (showList || !server) break; modName = CScriptHandler::Instance().chosenScript->GetModName(); if (modName == "") ShowModList(); state = WAIT_ON_MOD; // fall through case WAIT_ON_MOD: if (showList || !server) break; state = ALL_READY; // fall through case ALL_READY: ENTER_MIXED; // Map all required archives depending on selected mod(s) vector<string> ars = archiveScanner->GetArchives(modName); if (ars.empty()) logOutput.Print("Warning: mod archive \"%s\" is missing?\n", modName.c_str()); for (vector<string>::iterator i = ars.begin(); i != ars.end(); ++i) if (!hpiHandler->AddArchive(*i, false)) logOutput.Print("Warning: Couldn't load archive '%s'.", i->c_str()); // Determine if the map is inside an archive, and possibly map needed archives CFileHandler* f = SAFE_NEW CFileHandler("maps/" + mapName); if (!f->FileExists()) { vector<string> ars = archiveScanner->GetArchivesForMap(mapName); if (ars.empty()) logOutput.Print("Warning: map archive \"%s\" is missing?\n", mapName.c_str()); for (vector<string>::iterator i = ars.begin(); i != ars.end(); ++i) { if (!hpiHandler->AddArchive(*i, false)) logOutput.Print("Warning: Couldn't load archive '%s'.", i->c_str()); } } delete f; // always load springcontent.sdz hpiHandler->AddArchive("base/springcontent.sdz", false); LoadStartPicture(); game = SAFE_NEW CGame(server, mapName, modName, infoConsole); infoConsole = 0; ENTER_UNSYNCED; pregame=0; delete this; return true; } if(!server && state != WAIT_ON_ADDRESS){ net->Update(); UpdateClientNet(); } return true; }
CBFGroundTextures::CBFGroundTextures(CSmfReadMap *rm) { CFileHandler *ifs = rm->ifs; map = rm; numBigTexX=gs->mapx/128; numBigTexY=gs->mapy/128; MapHeader* header=&map->header; ifs->Seek(header->tilesPtr); tileSize = header->tilesize; MapTileHeader tileHeader; READPTR_MAPTILEHEADER(tileHeader,ifs); tileMap = SAFE_NEW int[(header->mapx*header->mapy)/16]; tiles = SAFE_NEW char[tileHeader.numTiles*SMALL_TILE_SIZE]; int curTile=0; for(int a=0;a<tileHeader.numTileFiles;++a){ PrintLoadMsg("Loading tile file"); int size; ifs->Read(&size,4); size = swabdword(size); string name; while(true){ char ch; ifs->Read(&ch,1); /* char, no swab */ if(ch==0) break; name+=ch; } name=string("maps/")+name; CFileHandler tileFile(name); if(!tileFile.FileExists()){ logOutput.Print("Couldnt find tile file %s",name.c_str()); memset(&tiles[curTile*SMALL_TILE_SIZE],0xaa,size*SMALL_TILE_SIZE); curTile+=size; continue; } PrintLoadMsg("Reading tiles"); TileFileHeader tfh; READ_TILEFILEHEADER(tfh,tileFile); if(strcmp(tfh.magic,"spring tilefile")!=0 || tfh.version!=1 || tfh.tileSize!=32 || tfh.compressionType!=1){ char t[500]; sprintf(t,"Error couldnt open tile file %s",name.c_str()); handleerror(0,t,"Error when reading tile file",0); exit(0); } for(int b=0;b<size;++b){ tileFile.Read(&tiles[curTile*SMALL_TILE_SIZE],SMALL_TILE_SIZE); curTile++; } } PrintLoadMsg("Reading tile map"); int count = (header->mapx*header->mapy)/16; ifs->Read(tileMap, count*sizeof(int)); for (int i = 0; i < count; i++) { tileMap[i] = swabdword(tileMap[i]); } tileMapXSize = header->mapx/4; tileMapYSize = header->mapy/4; squares=SAFE_NEW GroundSquare[numBigTexX*numBigTexY]; for(int y=0;y<numBigTexY;++y){ for(int x=0;x<numBigTexX;++x){ GroundSquare* square=&squares[y*numBigTexX+x]; square->texLevel=1; square->lastUsed=-100; LoadSquare(x,y,2); } } inRead=false; }
/// read an int from file (endian aware) static int ReadInt(CFileHandler& file) { unsigned int __tmpdw = 0; file.Read(&__tmpdw,sizeof(unsigned int)); return (int)swabDWord(__tmpdw); }
/// read a float from file (endian aware) static float ReadFloat(CFileHandler& file) { float __tmpfloat = 0.0f; file.Read(&__tmpfloat,sizeof(float)); return swabFloat(__tmpfloat); }
bool CGameSetup::Init(char* buf, int size) { for(int a=0;a<MAX_PLAYERS;a++){ gs->players[a]->team=0; //needed in case one tries to spec a game with only one team } gameSetupText=SAFE_NEW char[size]; memcpy(gameSetupText,buf,size); gameSetupTextLength=size; file.LoadBuffer(buf,size); if(!file.SectionExist("GAME")) return false; mapname=file.SGetValueDef("","GAME\\mapname"); scriptName=file.SGetValueDef("Commanders","GAME\\scriptname"); baseMod=archiveScanner->ModArchiveToModName(file.SGetValueDef(MOD_FILE,"GAME\\Gametype")); file.GetDef(hostip,"0","GAME\\HostIP"); file.GetDef(hostport,"0","GAME\\HostPort"); file.GetDef(maxUnits,"500","GAME\\MaxUnits"); file.GetDef(gs->gameMode,"0","GAME\\GameMode"); file.GetDef(sourceport,"0","GAME\\SourcePort"); file.GetDef(limitDgun,"0","GAME\\LimitDgun"); file.GetDef(diminishingMMs,"0","GAME\\DiminishingMMs"); file.GetDef(disableMapDamage,"0","GAME\\DisableMapDamage"); demoName=file.SGetValueDef("","GAME\\Demofile"); if(!demoName.empty()) hostDemo=true; file.GetDef(ghostedBuildings,"1","GAME\\GhostedBuildings"); file.GetDef(maxSpeed, "3", "GAME\\MaxSpeed"); file.GetDef(minSpeed, "0.3", "GAME\\MinSpeed"); // Determine if the map is inside an archive, and possibly map needed archives CFileHandler* f = SAFE_NEW CFileHandler("maps/" + mapname); if (!f->FileExists()) { vector<string> ars = archiveScanner->GetArchivesForMap(mapname); for (vector<string>::iterator i = ars.begin(); i != ars.end(); ++i) { if (!hpiHandler->AddArchive(*i, false)) logOutput.Print("Warning: Couldn't load archive '%s'.", i->c_str()); } } delete f; file.GetDef(myPlayer,"0","GAME\\MyPlayerNum"); gu->myPlayerNum=myPlayer; file.GetDef(numPlayers,"2","GAME\\NumPlayers"); file.GetDef(gs->activeTeams,"2","GAME\\NumTeams"); file.GetDef(gs->activeAllyTeams,"2","GAME\\NumAllyTeams"); file.GetDef(startPosType,"0","GAME\\StartPosType"); if(startPosType==2){ for(int a=0;a<gs->activeTeams;++a) readyTeams[a]=false; for(int a=0;a<gs->activeTeams;++a) teamStartNum[a]=a; SAFE_NEW CStartPosSelecter(); } else { for(int a=0;a<gs->activeTeams;++a) readyTeams[a]=true; if(startPosType==0){ //in order for(int a=0;a<gs->activeTeams;++a) teamStartNum[a]=a; } else { //random order std::multimap<int,int> startNums; for(int a=0;a<gs->activeTeams;++a) startNums.insert(pair<int,int>(gu->usRandInt(),a)); //server syncs these later int b=0; for(std::multimap<int,int>::iterator si=startNums.begin();si!=startNums.end();++si){ teamStartNum[si->second]=b; ++b; } } } for(int a=0;a<numPlayers;++a){ char section[50]; sprintf(section,"GAME\\PLAYER%i\\",a); string s(section); gs->players[a]->team=atoi(file.SGetValueDef("0",s+"team").c_str()); gs->players[a]->spectator=!!atoi(file.SGetValueDef("0",s+"spectator").c_str()); gs->players[a]->playerName=file.SGetValueDef("0",s+"name"); int fromDemo; file.GetDef(fromDemo,"0",s+"IsFromDemo"); if(fromDemo) numDemoPlayers++; } gu->spectating = gs->players[myPlayer]->spectator; gu->spectatingFullView = gu->spectating; TdfParser p2; CReadMap::OpenTDF (mapname, p2); for(int a=0;a<gs->activeTeams;++a){ char section[50]; sprintf(section,"GAME\\TEAM%i\\",a); string s(section); int colorNum=atoi(file.SGetValueDef("0",s+"color").c_str()); colorNum%=palette.NumTeamColors(); float3 defaultCol(palette.teamColor[colorNum][0]/255.0f,palette.teamColor[colorNum][1]/255.0f,palette.teamColor[colorNum][2]/255.0f); float3 color=file.GetFloat3(defaultCol,s+"rgbcolor"); for(int b=0;b<3;++b) gs->Team(a)->color[b]=int(color[b]*255); gs->Team(a)->color[3]=255; gs->Team(a)->handicap=atof(file.SGetValueDef("0",s+"handicap").c_str())/100+1; gs->Team(a)->leader=atoi(file.SGetValueDef("0",s+"teamleader").c_str()); gs->Team(a)->side = StringToLower(file.SGetValueDef("arm",s+"side").c_str()); gs->SetAllyTeam(a, atoi(file.SGetValueDef("0",s+"allyteam").c_str())); if (demoName.empty()) aiDlls[a]=file.SGetValueDef("",s+"aidll"); else aiDlls[a]=""; float x,z; char teamName[50]; sprintf(teamName,"TEAM%i",teamStartNum[a]); p2.GetDef(x,"1000",string("MAP\\")+teamName+"\\StartPosX"); p2.GetDef(z,"1000",string("MAP\\")+teamName+"\\StartPosZ"); gs->Team(a)->startPos=float3(x,100,z); if(startPosType==2) gs->Team(a)->startPos.y=-500; //show that we havent selected start pos yet } gu->myTeam=gs->players[myPlayer]->team; gu->myAllyTeam=gs->AllyTeam(gu->myTeam); for(int a=0;a<gs->activeAllyTeams;++a){ char section[50]; sprintf(section,"GAME\\ALLYTEAM%i\\",a); string s(section); startRectTop[a]=atof(file.SGetValueDef("0",s+"StartRectTop").c_str()); startRectBottom[a]=atof(file.SGetValueDef("1",s+"StartRectBottom").c_str()); startRectLeft[a]=atof(file.SGetValueDef("0",s+"StartRectLeft").c_str()); startRectRight[a]=atof(file.SGetValueDef("1",s+"StartRectRight").c_str()); int numAllies=atoi(file.SGetValueDef("0",s+"NumAllies").c_str()); for(int b=0;b<numAllies;++b){ char key[100]; sprintf(key,"GAME\\ALLYTEAM%i\\Ally%i",a,b); int other=atoi(file.SGetValueDef("0",key).c_str()); gs->SetAlly(a,other, true); } } if(startPosType==2){ for(int a=0;a<gs->activeTeams;++a) gs->Team(a)->startPos=float3(startRectLeft[gs->AllyTeam(a)]*gs->mapx*8,-500,startRectTop[gs->AllyTeam(a)]*gs->mapy*8); } int metal,energy; file.GetDef(metal,"1000","GAME\\StartMetal"); file.GetDef(energy,"1000","GAME\\StartEnergy"); for(int a=0;a<gs->activeTeams;++a){ gs->Team(a)->metal=metal; gs->Team(a)->metalIncome=metal; //for the endgame statistics gs->Team(a)->metalStorage=metal; gs->Team(a)->energy=energy; gs->Team(a)->energyIncome=energy; gs->Team(a)->energyStorage=energy; } // Read the unit restrictions int numRestrictions; file.GetDef(numRestrictions, "0", "GAME\\NumRestrictions"); for (int i = 0; i < numRestrictions; ++i) { char key[100]; sprintf(key, "GAME\\RESTRICT\\Unit%d", i); string resName = file.SGetValueDef("", key); sprintf(key, "GAME\\RESTRICT\\Limit%d", i); int resLimit; file.GetDef(resLimit, "0", key); restrictedUnits[resName] = resLimit; } return true; }
bool CPreGame::Update(void) { if(waitOnAddress && !userWriting){ waitOnAddress=false; if (saveAddress) configHandler.SetString("address",userInput); if(net->InitClient(userInput.c_str(),8452,0)==-1){ info->AddLine("Client couldnt connect"); return false; } userWriting=false; } if(!server && !waitOnAddress){ net->Update(); UpdateClientNet(); } if(waitOnScript && !showList){ waitOnScript=false; mapName=CScriptHandler::Instance().chosenScript->GetMapName(); if(mapName==""){ ShowMapList(); waitOnMap=true; } else { allReady=true; } } if(allReady){ ENTER_MIXED; // Map all required archives depending on selected mod(s) stupidGlobalModName = MOD_FILE; if (gameSetup) stupidGlobalModName = gameSetup->baseMod; vector<string> ars = archiveScanner->GetArchives(stupidGlobalModName); for (vector<string>::iterator i = ars.begin(); i != ars.end(); ++i) { hpiHandler->AddArchive(*i, false); } // Determine if the map is inside an archive, and possibly map needed archives CFileHandler* f = new CFileHandler("maps/" + mapName); if (!f->FileExists()) { vector<string> ars = archiveScanner->GetArchivesForMap(mapName); for (vector<string>::iterator i = ars.begin(); i != ars.end(); ++i) { hpiHandler->AddArchive(*i, false); } } delete f; LoadStartPicture(); game=new CGame(server,mapName); ENTER_UNSYNCED; game->Update(); pregame=0; delete this; return true; } return true; }
int main(int argc, char *argv[]) { #ifdef _WIN32 try { #endif std::cout << "If you find any errors, report them to mantis or the forums." << std::endl << std::endl; ConfigHandler::Instantiate(""); FileSystemHandler::Cleanup(); FileSystemHandler::Initialize(false); CGameServer* server = 0; CGameSetup* gameSetup = 0; if (argc > 1) { const std::string script(argv[1]); std::cout << "Loading script from file: " << script << std::endl; ClientSetup settings; CFileHandler fh(argv[1]); if (!fh.FileExists()) throw content_error("Setupscript doesn't exists in given location: "+script); std::string buf; if (!fh.LoadStringData(buf)) throw content_error("Setupscript cannot be read: "+script); settings.Init(buf); gameSetup = new CGameSetup(); // to store the gamedata inside if (!gameSetup->Init(buf)) // read the script provided by cmdline { std::cout << "Failed to load script" << std::endl; return 1; } std::cout << "Starting server..." << std::endl; // Create the server, it will run in a separate thread GameData* data = new GameData(); UnsyncedRNG rng; rng.Seed(gameSetup->gameSetupText.length()); rng.Seed(script.length()); data->SetRandomSeed(rng.RandInt()); // Use script provided hashes if they exist if (gameSetup->mapHash != 0) { data->SetMapChecksum(gameSetup->mapHash); gameSetup->LoadStartPositions(false); // reduced mode } else { data->SetMapChecksum(archiveScanner->GetMapChecksum(gameSetup->mapName)); CFileHandler* f = new CFileHandler("maps/" + gameSetup->mapName); if (!f->FileExists()) { std::vector<std::string> ars = archiveScanner->GetArchivesForMap(gameSetup->mapName); if (ars.empty()) { throw content_error("Couldn't find any archives for map '" + gameSetup->mapName + "'."); } for (std::vector<std::string>::iterator i = ars.begin(); i != ars.end(); ++i) { if (!vfsHandler->AddArchive(*i, false)) { throw content_error("Couldn't load archive '" + *i + "' for map '" + gameSetup->mapName + "'."); } } } delete f; gameSetup->LoadStartPositions(); // full mode } if (gameSetup->modHash != 0) { data->SetModChecksum(gameSetup->modHash); } else { const std::string modArchive = archiveScanner->ModNameToModArchive(gameSetup->modName); data->SetModChecksum(archiveScanner->GetModChecksum(modArchive)); } data->SetSetup(gameSetup->gameSetupText); server = new CGameServer(&settings, false, data, gameSetup); while (!server->HasFinished()) // check if still running #ifdef _WIN32 Sleep(1000); #else sleep(1); // if so, wait 1 second #endif delete server; // delete the server after usage } else { std::cout << "usage: spring-dedicated <full_path_to_script>" << std::endl; } FileSystemHandler::Cleanup(); #ifdef _WIN32 } catch (const std::exception& err) { std::cout << "Exception raised: " << err.what() << std::endl; return 1; } #endif return 0; }