BlobStorage::Blob BlobStorage::add(const String& path, const Data& data) { ASSERT(!RunLoop::isMain()); auto hash = computeSHA1(data); if (data.isEmpty()) return { data, hash }; auto blobPath = WebCore::fileSystemRepresentation(blobPathForHash(hash)); auto linkPath = WebCore::fileSystemRepresentation(path); unlink(linkPath.data()); bool blobExists = access(blobPath.data(), F_OK) != -1; if (blobExists) { auto existingData = mapFile(blobPath.data()); if (bytesEqual(existingData, data)) { link(blobPath.data(), linkPath.data()); return { existingData, hash }; } unlink(blobPath.data()); } auto mappedData = data.mapToFile(blobPath.data()); if (mappedData.isNull()) return { }; link(blobPath.data(), linkPath.data()); m_approximateSize += mappedData.size(); return { mappedData, hash }; }
bool ReadSessionCacheFileMap(const QString& sessionDir, CacheFileMap& cache) { QString mapPath; mapPath = sessionDir + CACHE_FILE_MAP; QFile mapFile(mapPath); QTextStream stream(&mapFile); QString line; if (!mapFile.open(QIODevice::ReadWrite | QIODevice::Text)) { return false; } stream.setCodec("UTF-16"); while (!stream.atEnd()) { QString originalPath; QString cachedPath; // read the next line, which contains originalPath:= src.java line = stream.readLine(); originalPath = line.section(QObject::tr(":="), 0, 0); cachedPath = line.section(QObject::tr(":="), 1, 1); cache.insert(originalPath, cachedPath); } mapFile.close(); return true; }
bool WriteSessionCacheFileMap(const QString& sessionDir, CacheFileMap& cache) { QString mapPath; mapPath = sessionDir + CACHE_FILE_MAP; QFile mapFile(mapPath); QTextStream stream(&mapFile); if (!mapFile.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) { return false; } stream.setCodec("UTF-16"); CacheFileMap::Iterator it; for (it = cache.begin(); it != cache.end(); ++it) { stream << it.key() << ":=" << it.value() << endl; } mapFile.close(); return true; }
// saves the currently loaded map to a file void EditableMap::save(char *filename) { std::ofstream mapFile(getResourcePath(filename)); std::cout << "Saving the map index \"" << filename << "\" ... "; // verify that the file was opened correctly before reading if(mapFile.bad()) { std::cout << "FAILED!\n"; return; } // sets the width and height of the map mapFile << w << "\n"; mapFile << h << "\n"; // write the information about every tile on the map for(int i=0;i<w;i++) { for(int j=0;j<h;j++) { mapFile << ts[i][j].b << " " << ts[i][j].f << " " << ((ts[i][j].isWalkable)?"Y":"N") << "\n"; } } mapFile.close(); std::cout << "Successful!\n"; }
////////////////////////////////////////////////////////////////////////// // 读取操作 inline HRESULT KAppFile::Load(LPCWSTR strFile) { kis::KFileRead mapFile( strFile ); if (!mapFile.Ok()) return E_APP_FILE_OPEN_FAILED; INT nSize = mapFile.GetSize(); BYTE* pFileData = mapFile; AppFileHeader* pHeader = (AppFileHeader*)pFileData; if (pHeader->nMagic != APP_FILE_MAGIC) return E_APP_FILE_UNKNOWN_FMT; KRecord appRule(pFileData + pHeader->nAppRuleOffset); if (!appRule.Ok()) return E_APP_FILE_UNKNOWN_FMT; try { return ReadAppRules(&appRule); } catch (...) { } return E_FAIL; }
void GameEngine::readMapFromFile() { QFile mapFile(":/maps/map"); if (!mapFile.open(QIODevice::ReadOnly | QIODevice::Text)) return; QTextStream text(&mapFile); while (!text.atEnd()) { QString buf = text.readLine(); if (buf == "[VERTEX]") { readVertexes(text); } if (buf == "[HEXAGONS]") { readHexagons(text); } if (buf == "[HARBOR]") { readHarbors(text); } } mapFile.close(); }
inline HRESULT KAreaFile::Save(LPCWSTR strFile) { KMemWriteProxy proxy; // 保存数据到内存中 KRecordWriter root(&proxy, TRUE, 0, AreaInfo_Root); SaveAreaList(&root); root.EndRecord(); INT nSize = proxy.GetCurPos(); INT nFileSize = nSize + sizeof(AreaFileHeader); kis::KFileWrite mapFile(strFile, nFileSize); if (!mapFile.Ok()) return E_AREA_FILE_SAVE_FAILED; BYTE* pBuf = mapFile; AreaFileHeader* pHeader = (AreaFileHeader*)pBuf; pHeader->cbSize = sizeof(AreaFileHeader); pHeader->nMagic = AREA_FILE_MAGIC; pHeader->nVer = 0; pHeader->DataOffset = sizeof(AreaFileHeader); memcpy(pBuf + pHeader->DataOffset, proxy.GetBuf(0), nSize); return S_OK; }
BlobStorage::Blob BlobStorage::get(const String& path) { ASSERT(!RunLoop::isMain()); auto linkPath = WebCore::fileSystemRepresentation(path); auto data = mapFile(linkPath.data()); return { data, computeSHA1(data) }; }
/* Constructor function open(options: Object = null): File NOTE: options can be an options hash or as mode string */ static EjsObj *openFile(Ejs *ejs, EjsFile *fp, int argc, EjsObj **argv) { EjsObj *options; cchar *mode; int perms, omode; if (argc < 0 || argc > 1) { ejsThrowArgError(ejs, "Bad args"); return 0; } options = argv[0]; if (argc == 0 || !ejsIsDefined(ejs, options)) { omode = O_RDONLY | O_BINARY; perms = EJS_FILE_PERMS; fp->mode = EJS_FILE_READ; mode = "r"; } else { if (ejsIs(ejs, options, String)) { mode = ejsToMulti(ejs, options); perms = EJS_FILE_PERMS; } else { perms = ejsGetNumOption(ejs, options, "permissions", EJS_FILE_PERMS, 1); mode = getStrOption(ejs, options, "mode", "r", 1); if (ejs->exception) { return 0; } } omode = mapMode(mode); if (!(omode & O_WRONLY)) { fp->mode |= EJS_FILE_READ; } if (omode & (O_WRONLY | O_RDWR)) { fp->mode |= EJS_FILE_WRITE; } } fp->modeString = sclone(mode); fp->perms = perms; if (fp->file) { mprCloseFile(fp->file); } fp->file = mprOpenFile(fp->path, omode, perms); if (fp->file == 0) { ejsThrowIOError(ejs, "Cannot open %s", fp->path); return 0; } if (options) { ejsSetPathAttributes(ejs, fp->path, options); } #if ME_CC_MMU && FUTURE mprGetPathInfo(&fp->info); fp->mapped = mapFile(fp, fp->info.size, MPR_MAP_READ | MPR_MAP_WRITE); #endif fp->mode |= EJS_FILE_OPEN; return (EjsObj*) fp; }
void Map::parseIndex(char *filename) { int mapW, mapH, newF, newB; char newW; std::ifstream mapFile(getResourcePath(filename)); std::cout << "Opening map index \"" << filename << "\" ... "; // verify that the file was opened correctly before reading if(mapFile.bad()) { std::cout << "FAILED!\n"; return; } std::cout << "Successful!\n"; // get the width and height of the map (according to its index) mapFile >> mapW; mapFile >> mapH; w = mapW; h = mapH; // check if the bounding window is larger than the map if(limitWTiles > w) limitWTiles = w; if(limitHTiles > h) limitHTiles = h; // initialize 2D array of tiles which will represent the map ts = new Tile*[mapW]; for (int k = 0; k < mapW; k++) ts[k] = new Tile[mapH]; std::cout << "Initializing map, W: "<<mapW<<" tiles, H: "<< mapH <<" tiles ... "; // read the input index file, initializing the tiles for(int i=0;i<w;i++) { for(int j=0;j<h;j++) { mapFile >> newB; mapFile >> newF; mapFile >> newW; ts[i][j].b = newB; ts[i][j].f = newF; ts[i][j].isWalkable = (newW=='Y')?true:false; } } mapFile.close(); std::cout << "Successful!\n"; }
bool MagicTowerLoader::saveGame(const QString& directoryName, const QString& saveName) { QFile mapFile(directoryName + "/" + saveName + ".mtsavedmap.ini"); QFile extraFile(directoryName + "/" + saveName + ".mtsavedextra.ini"); if(!mapFile.open(QIODevice::WriteOnly)) { return false; } if(!extraFile.open(QIODevice::WriteOnly)) { mapFile.close(); return false; } QTextStream mapOutputStream(&mapFile); QTextStream extraOutputStream(&extraFile); QStringList maps = scene->allMaps(); for(int i=0;i<maps.size();i++) { QString title = QString("[map/")+maps[i]+"]"; mapOutputStream << title << "\r\n"; for(int j=1;j<12;j++) { QString line; for(int k=1;k<12;k++) { if(scene->getObjectAt(maps[i],"main",k,j)!=NULL) line.append(scene->getObjectAt(maps[i],"main",k,j)->presetName); else line.append("null"); if(k!=12) { line.append("|"); } MagicTowerCharacter* character = dynamic_cast<MagicTowerCharacter*>(scene->getObjectAt(maps[i],"character",k,j)); if(character!=NULL) { extraOutputStream << "[Character]" << "\r\n"; extraOutputStream << "map = " << maps[i] << "\r\n"; extraOutputStream << "x = " << k << "\r\n"; extraOutputStream << "y = " << j << "\r\n"; QMap<QString,int> properties = character->getAllIntGameProperties(); QMap<QString, int>::const_iterator i = properties.begin(); while(i != properties.end()) { extraOutputStream << i.key() << " = " << i.value() << "\r\n"; i++; } } } mapOutputStream << line << "\r\n"; } } mapFile.close(); extraOutputStream << "\r\n"; extraFile.close(); }
BlobStorage::Blob BlobStorage::add(const String& path, const Data& data) { ASSERT(!RunLoop::isMain()); auto hash = computeSHA1(data); if (data.isEmpty()) return { data, hash }; auto blobPath = WebCore::fileSystemRepresentation(blobPathForHash(hash)); auto linkPath = WebCore::fileSystemRepresentation(path); unlink(linkPath.data()); bool blobExists = access(blobPath.data(), F_OK) != -1; if (blobExists) { auto existingData = mapFile(blobPath.data()); if (bytesEqual(existingData, data)) { link(blobPath.data(), linkPath.data()); return { existingData, hash }; } unlink(blobPath.data()); } int fd = open(blobPath.data(), O_CREAT | O_EXCL | O_RDWR , S_IRUSR | S_IWUSR); if (fd < 0) return { }; size_t size = data.size(); if (ftruncate(fd, size) < 0) { close(fd); return { }; } void* map = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); close(fd); if (map == MAP_FAILED) return { }; uint8_t* mapData = static_cast<uint8_t*>(map); data.apply([&mapData](const uint8_t* bytes, size_t bytesSize) { memcpy(mapData, bytes, bytesSize); mapData += bytesSize; return true; }); // Drop the write permission. mprotect(map, size, PROT_READ); auto mappedData = Data::adoptMap(map, size); link(blobPath.data(), linkPath.data()); m_approximateSize += size; return { mappedData, hash }; }
int main( int argc, char* argv[] ) { //get_settings read_settings; //create a settings reading object. int screenDataW = 1920; //put screen data into a temp var int screenDataH = 1080; SDL_Init( SDL_INIT_EVERYTHING ); //start SDL SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2); //set GL version of the window SDL_Window* window = SDL_CreateWindow( "RainbowRPG - SDL2.0 - OpenGL2.1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, screenDataW, screenDataH, SDL_WINDOW_FULLSCREEN_DESKTOP | SDL_WINDOW_OPENGL | SDL_WINDOW_INPUT_GRABBED); //create OpenGL window SDL_GLContext glcontext = SDL_GL_CreateContext(window); //set context as OpenGL // SDL_SetWindowFullscreen(window, SDL_WINDOW_FULLSCREEN); initGL(screenDataW, screenDataH); //init GL. //command_thread.detach(); // SDL_Delay(1000); std::string mapFile ("a.map"); std::cout << "Initialising map!\n\n"; map* ptrmap; //create a pointer of type map. map currentMap (screenDataW, screenDataH, mapFile); ptrmap = ¤tMap; //make pointer point to instance of map. std::cout << "checking for inputted commands...."; command* ptrCommand; //create a pointer of type command. command commandline; //create command line object. std::cout << "creating command line thread...\n"; boost::thread command_thread ( boost::bind (&command::start_command, &commandline) ); //create a thread of the command line. std::cout << "Command thread started\n\n"; ptrCommand = & commandline; //make pointer point to command object. //boost::thread logic_loop (boost::bind(&entity_logic_loop, ptrmap)); //create logic loop thread. std::cout << "Running game loop func\n\n"; game_loop(ptrCommand, ptrmap, window); //game_loop( ptrmap, window); currentMap.destroy_map(); //destroy the map! SDL_GL_DeleteContext(glcontext); //clean up SDL_Quit(); //quit SDL std::cout << "\nQuited nicely, press any letter/number key then tap return to terminate \n(This is a problem with using threads and std::cin together, must find a better way of doing this safely\n\n"; // - Remember killing the thread causes recursive terminate >.<.)\n\n"; command_thread.join(); //detach both out threads. //logic_loop.join(); return 0; }
void Environment::loadMap(const fs::path &path) { appLog(describeComponentLoading(Component::Map), LogOrigin::Engine); std::ifstream mapFile(path.string()); if (auto map = Map::load(mapFile)) { this->map.emplace(std::move(map.get())); } else { appLog(describeComponentMalformed(Component::Map), LogOrigin::Error); loadError = true; } appLog(describeComponentDone(Component::Map), LogOrigin::Engine); }
QString findMapInDir( const QString& path ) { QString mapPath = path.left( path.lastIndexOf( '/' ) + 1 ) + "MoNav.ini"; if( !QFile::exists( mapPath ) ) return ""; QSettings mapFile( mapPath, QSettings::IniFormat ); return mapFile.value( "name", "" ).toString(); }
void InputProcessing::ReadMap(std::string mapFileName, int *Nrow, double *M, int *it, int Norder, int &jmaxOrd){ std::string mapFilePath = paths["input"] + mapFileName; std::ifstream mapFile(mapFilePath.c_str()); if (!mapFile.is_open()){ std::string msg = "Cannot open file " + mapFileName; Abort(msg.c_str()); } std::string line; int iTmp = 0, iOrder, iTmp_prev = 0; double Mtmp1; int ittmp[6]; int j = 0, i = 1; while(!mapFile.eof()){ mapFile >> iTmp >> Mtmp1 >> iOrder >> ittmp[0] >> ittmp[1] >> ittmp[2] >> ittmp[3] >> ittmp[4] >> ittmp[5]; if(!mapFile) { Nrow[i - 1] = j; break; } if (iTmp > iTmp_prev){ j = j + 1; iTmp_prev = iTmp; }else{ Nrow[i - 1] = j; i = i + 1; j = 1; iTmp_prev = 1; } M[(j - 1) * 6 + i - 1] = Mtmp1; for(int k = 1; k <= 6; ++k){ it[(j - 1) * 6 * 6 + (i - 1) * 6 + k - 1] = ittmp[k - 1]; } //std::cout << iTmp << "\t" << Mtmp1 << "\t" << iOrder << "\t" << ittmp[0] << "\t" << ittmp[1] << "\t" << ittmp[2] << "\t" << ittmp[3] << "\t" << ittmp[4] << "\t" << ittmp[5] << "\n"; } mapFile.close(); //!----------------------------------------------------- //! Truncate the matrix at the prescribed order Norder //!----------------------------------------------------- jmaxOrd = 0; for(i = 1; i <= 6; ++i){ int kl = 0; for(j = 1; j <= Nrow[i - 1]; ++j){ int sum = 0; for(int k = 1; k <= 6; ++k){ sum += it[(j - 1) * 6 * 6 + (i - 1) * 6 + k - 1]; } if(sum <= Norder) kl = kl+1; if(jmaxOrd < sum)jmaxOrd = sum; } Nrow[i - 1] = kl; } }
//-------------------------------------------------------------------------------------------------- TextMap::Ptr TextMap::loadTextMapFromFile( const std::string& filename ) { TextMap::Ptr pTextMap; std::ifstream mapFile( filename ); if ( mapFile.is_open() ) { pTextMap = TextMap::Ptr( new TextMap() ); std::string curLine; // First read out the object filename if ( mapFile.good() ) { std::getline( mapFile, curLine ); boost::trim( curLine ); if ( curLine != NO_MODEL_FILENAME ) { pTextMap->mModelFilename = Utilities::decodeRelativeFilename( filename, curLine ); printf( "Got a model filename of %s\n", pTextMap->mModelFilename.c_str() ); } // Now read in the number of letters uint32_t numLetters; mapFile >> numLetters; pTextMap->mLetters.reserve( numLetters ); // Read in the letters for ( uint32_t letterIdx = 0; letterIdx < numLetters; letterIdx++ ) { Letter letter; Eigen::Vector3f pos; Eigen::Vector3f eulerAnglesDegrees; mapFile >> letter.mCharacter; mapFile >> pos[ 0 ] >> pos[ 1 ] >> pos[ 2 ]; mapFile >> eulerAnglesDegrees[ 0 ] >> eulerAnglesDegrees[ 1 ] >> eulerAnglesDegrees[ 2 ]; mapFile >> letter.mWidth >> letter.mHeight; letter.mMtx = Eigen::Matrix4f::Identity(); letter.mMtx.block<3,3>( 0, 0 ) = ( Eigen::AngleAxisf( Utilities::degToRad( eulerAnglesDegrees[ 0 ] ), Eigen::Vector3f::UnitX() ) * Eigen::AngleAxisf( Utilities::degToRad( eulerAnglesDegrees[ 1 ] ), Eigen::Vector3f::UnitY() ) * Eigen::AngleAxisf( Utilities::degToRad( eulerAnglesDegrees[ 2 ] ), Eigen::Vector3f::UnitZ() ) ).toRotationMatrix(); letter.mMtx.block<3,1>( 0, 3 ) = pos; pTextMap->mLetters.push_back( letter ); } }
Map* MapLoader::loadMap(const string& mapFileName, const string& constrFileName) { ifstream mapFile(mapFileName); LoadableLocationSet locations; LoadableReaderSet readers; NameIdMap locationsMap; string line; if (mapFile.is_open()) { unsigned int lId = 0, rId = 0; while (getline(mapFile, line)) { Util::trim(line); // Jump if blank line or comment (starts with '#') if (line.length() == 0 || line[0] == '#') continue; vector<string> v = Util::split(line, SEP); if (v.size() == 5) { // Location line string name = v[0]; double x = stod(v[1]), y = stod(v[2]), w = stod(v[3]), h = stod(v[4]); locationsMap.insert(NameIdPair(name, lId)); locations.push_back(Location(lId++, name, x, y, w, h)); } else if (v.size() == 3) { // Reader line string name = v[0]; double x = stod(v[1]), y = stod(v[2]); readers.push_back(Reader(rId++, name, x, y)); } else throw BadInput(); } } else throw BadInput(); Map* map = Map::createMap<LoadableLocationSet,LoadableReaderSet>(locations, readers); ifstream constrFile(constrFileName); if (constrFile.is_open()) { while (getline(constrFile, line)) { Util::trim(line); // Jump if blank line or comment (starts with '#') if (line.length() == 0 || line[0] == '#') continue; vector<string> v = Util::split(line, CSEP); if (v[0] == "DR") { // Direct Reachability Constraint unsigned int id1 = locationsMap.at(v[1]), id2 = locationsMap.at(v[2]); map->setDR(id1, id2); } else if (v[0] == "DU") { // Direct Unreachability Constraint unsigned int id1 = locationsMap.at(v[1]), id2 = locationsMap.at(v[2]); map->setDU(id1, id2); } else if (v[0] == "LT") { // Latency Constraint unsigned int id = locationsMap.at(v[1]), latency = stoi(v[2]); map->setLT(id, latency); } else if (v[0] == "TT") { // Traveling Time Constraint unsigned int id1 = locationsMap.at(v[1]), id2 = locationsMap.at(v[2]), travelingTime = stoi(v[3]); map->setTT(id1, id2, travelingTime); } else throw BadInput(); } } return map; }
/** * Loads a series of map polar coordinates in X-Com format, * converts them and stores them in a set of polygons. * @param filename Filename of the DAT file. * @sa http://www.ufopaedia.org/index.php?title=WORLD.DAT */ void RuleGlobe::loadDat(const std::string &filename) { // Load file std::ifstream mapFile (filename.c_str(), std::ios::in | std::ios::binary); if (!mapFile) { throw Exception(filename + " not found"); } short value[10]; while (mapFile.read((char*)&value, sizeof(value))) { Polygon* poly; int points; for (int i = 0; i < 10; ++i) { value[i] = SDL_SwapLE16(value[i]); } if (value[6] != -1) { points = 4; } else { points = 3; } poly = new Polygon(points); for (int i = 0, j = 0; i < points; ++i) { // Correct X-Com degrees and convert to radians double lonRad = value[j++] * 0.125 * M_PI / 180; double latRad = value[j++] * 0.125 * M_PI / 180; poly->setLongitude(i, lonRad); poly->setLatitude(i, latRad); } poly->setTexture(value[8]); _polygons.push_back(poly); } if (!mapFile.eof()) { throw Exception("Invalid globe map"); } mapFile.close(); }
void MapWidget::readMap() //读取地图信息 { QString mapName; QFile mapFile("maps.txt"); int ok = mapFile.open(QIODevice::ReadOnly); if(ok) { QTextStream ts(&mapFile); if(!ts.atEnd()) { ts>>mapName; ts>>x1>>y1>>x2>>y2; } }
void FieldTest::testConstructorRightResults() { HTMLLogger Logger; Logger.Init("log.html","MainLog"); SetLogger(&Logger); // Простая маленькая корректно сформированная карта, содержащая все типы символов. const char* pathToMap = "tests/res/testmaps/OrdinaryCorrectMap"; Field field(pathToMap); /* * Сравнение того, * как карта считалась в объект с теми символами, * которые мы сами считываем из файла. */ // Проверяем, что совпадают размеры int curLen; // Длина считываемой строки int maxLen = 0; int numOfLines = 0; std::ifstream mapFile(pathToMap); std::string line; while(std::getline(mapFile, line)) { // Нахождение размера по X // Поиск максимальной длины curLen = line.length(); if(curLen > maxLen) { maxLen = curLen; } // Поэлементное сравнение считанной карты и файла std::string::iterator itr = line.begin(); std::string::iterator endItr = line.end(); int i = 0; for(; itr != endItr; itr++) { CPPUNIT_ASSERT( *itr == field.getXY(i++, numOfLines) ); } // Нахождение размера по Y numOfLines++; } std::pair<int, int> fieldSize = field.getSize(); CPPUNIT_ASSERT(fieldSize.first == maxLen); CPPUNIT_ASSERT(fieldSize.second == numOfLines); }
TEST(MapTests, TestCreate) { char** options = nullptr; options = ngsListAddNameValue(options, "DEBUG_MODE", "ON"); options = ngsListAddNameValue(options, "SETTINGS_DIR", ngsFormFileName(ngsGetCurrentDirectory(), "tmp", nullptr)); EXPECT_EQ(ngsInit(options), COD_SUCCESS); ngsListFree(options); ngs::MapStore mapStore; char mapId = mapStore.createMap(DEFAULT_MAP_NAME, "unit test", DEFAULT_EPSG, ngs::DEFAULT_BOUNDS); EXPECT_GE(mapId, 0); ngs::MapViewPtr defMap = mapStore.getMap(mapId); ASSERT_NE(defMap, nullptr); ngsRGBA color = defMap->backgroundColor(); EXPECT_EQ(color.R, DEFAULT_MAP_BK.R); EXPECT_EQ(color.G, DEFAULT_MAP_BK.G); EXPECT_EQ(color.B, DEFAULT_MAP_BK.B); // ngmd - NextGIS map document ngs::CatalogPtr catalog = ngs::Catalog::instance(); CPLString tmpDir = CPLFormFilename(CPLGetCurrentDir(), "tmp", nullptr); ngs::Folder::mkDir(tmpDir); ngs::ObjectPtr tmpDirObj = catalog->getObjectBySystemPath(tmpDir); ASSERT_NE(tmpDirObj, nullptr); ngs::ObjectContainer* tmpDirContainer = ngsDynamicCast(ngs::ObjectContainer, tmpDirObj); CPLString mapPath = CPLFormFilename(tmpDirObj->path().c_str(), "default", "ngmd"); CPLString iconsPath = CPLFormFilename(CPLGetCurrentDir(), "data", nullptr); CPLString iconSet = CPLFormFilename(iconsPath, "tex", "png"); defMap->addIconSet("simple", iconSet, true); ngs::MapFile mapFile(tmpDirContainer, "default.ngmd", mapPath); EXPECT_EQ(defMap->save(&mapFile), true); mapId = mapStore.openMap(&mapFile); defMap = mapStore.getMap(mapId); defMap->setBackgroundColor({1,2,3,4}); EXPECT_EQ(defMap->save(&mapFile), true); ngs::Catalog::setInstance(nullptr); ngsUnInit(); }
// If bufferMax is zero, then the file is accessed using memory // mapped I/O. Otherwise, a small buffer is used. // readBuffer::readBuffer(const char *filename, u64bit bufferMax) { _filename = 0L; _file = 0; _filePos = 0; _mmap = false; _stdin = false; _eof = false; _bufferPos = 0; _bufferLen = 0; _bufferMax = 0; _buffer = 0L; if (((filename == 0L) && (isatty(fileno(stdin)) == 0)) || ((filename != 0L) && (filename[0] == '-') && (filename[1] == 0))) { _filename = new char [32]; strcpy(_filename, "(stdin)"); _stdin = true; if (bufferMax == 0) bufferMax = 32 * 1024; } else if (filename == 0L) { fprintf(stderr, "readBuffer()-- no filename supplied, and I will not use the terminal for input.\n"), exit(1); } else { _filename = new char [strlen(filename) + 1]; strcpy(_filename, filename); } if (bufferMax == 0) { _mmap = true; _buffer = (char *)mapFile(_filename, &_bufferLen, 'r'); } else { errno = 0; _file = (_stdin) ? fileno(stdin) : open(_filename, O_RDONLY | O_LARGEFILE); if (errno) fprintf(stderr, "readBuffer()-- couldn't open the file '%s': %s\n", _filename, strerror(errno)), exit(1); _bufferMax = bufferMax; _buffer = new char [_bufferMax]; } fillBuffer(); if (_bufferLen == 0) _eof = true; }
// ------------------------------------------------------------------------------------------------ void Map :: LoadMap(std::string fileName) { std::ifstream mapFile (fileName.c_str()); assert(mapFile.is_open()); int data; for(Tile y = 0; y < MAP_NUM_TILES_Y; y++) { for(Tile x = 0; x < MAP_NUM_TILES_X; x++) { mapFile >> data; if( (TileType)data < TILE_TYPE_BULLET_PICKUP) { tileTypes[x][y] = (TileType)data; } else { tileTypes[x][y] = TILE_TYPE_SPACE; if((TileType)data == TILE_TYPE_BULLET_PICKUP) { game->CreatePickUp(Vector2df(x * MAP_TILE_SIZE + MAP_TILE_SIZE / 2, y * MAP_TILE_SIZE + MAP_TILE_SIZE / 2), PICK_UP_TYPE_BULLETS); } else if((TileType)data == TILE_TYPE_MINE_PICKUP) { game->CreatePickUp(Vector2df(x * MAP_TILE_SIZE + MAP_TILE_SIZE / 2, y * MAP_TILE_SIZE + MAP_TILE_SIZE / 2), PICK_UP_TYPE_MINES); } else if((TileType)data == TILE_TYPE_MISSILE_PICKUP) { game->CreatePickUp(Vector2df(x * MAP_TILE_SIZE + MAP_TILE_SIZE / 2, y * MAP_TILE_SIZE + MAP_TILE_SIZE / 2), PICK_UP_TYPE_MISSILES); } else if((TileType)data == TILE_TYPE_REPAIR_PICKUP) { game->CreatePickUp(Vector2df(x * MAP_TILE_SIZE + MAP_TILE_SIZE / 2, y * MAP_TILE_SIZE + MAP_TILE_SIZE / 2), PICK_UP_TYPE_REPAIR); } else if((TileType)data == TILE_TYPE_SPAWN) { CreateSpawnPoint(Vector2df(x * MAP_TILE_SIZE + MAP_TILE_SIZE / 2, y * MAP_TILE_SIZE + MAP_TILE_SIZE / 2)); } } } } mapFile.close(); CalculateGravityVectors(); } // ----------------------------------------------------------------------------------------------
// 读取描述地图信息的文件 void MapWidget::readMap( void ) { QFile mapFile( "./interface/images/map/map.info" ); QString mapName; int ok = mapFile.open( QIODevice::ReadOnly ); if ( ok ) { QTextStream text( &mapFile ); if ( !text.atEnd() ) { text >> mapName; text >> x1 >> y1 >> x2 >> y2; } }
inline HRESULT KAdvFltFile::Save(LPCWSTR strFile, KPackTemplate* pTemplate, INT nBufSize, INT nCnt) { ADVFLTFileHeader header = {0}; header.cbSize = sizeof(header) + nBufSize; header.nAdvFltCnt = nCnt; header.nIpRuleOffset = sizeof(header); header.nMagic = ADVIP_FILE_MAGIC; header.nVer = 1; kis::KHashAlg().Md5((BYTE*)pTemplate, nBufSize, header.CheckSum); kis::KFileWrite mapFile(strFile, header.cbSize); BYTE* pBuf = mapFile; memcpy(pBuf, &header, sizeof(header)); pBuf += sizeof(header); memcpy(pBuf, (BYTE*)pTemplate, nBufSize); return S_OK; }
static bool HasSequenceKeys(const std::string& mapPath) { std::ifstream mapFile(mapPath); if (!mapFile) RuntimeError("Could not open '%s' for reading.", mapPath.c_str()); string line; if (!std::getline(mapFile, line)) RuntimeError("Could not read the file '%s'.", mapPath.c_str()); // Try to parse sequence id, file path and label. std::string image, classId, sequenceKey; std::stringstream ss(line); if (!std::getline(ss, sequenceKey, '\t') || !std::getline(ss, classId, '\t') || !std::getline(ss, image, '\t')) { return false; } return true; }
void ImageDataDeserializer::CreateSequenceDescriptions(std::string mapPath, size_t labelDimension) { UNREFERENCED_PARAMETER(labelDimension); std::ifstream mapFile(mapPath); if (!mapFile) { RuntimeError("Could not open %s for reading.", mapPath.c_str()); } std::string line; ImageSequenceDescription description; description.m_numberOfSamples = 1; description.m_isValid = true; for (size_t lineIndex = 0; std::getline(mapFile, line); ++lineIndex) { std::stringstream ss(line); std::string imagePath; std::string classId; if (!std::getline(ss, imagePath, '\t') || !std::getline(ss, classId, '\t')) { RuntimeError("Invalid map file format, must contain 2 tab-delimited columns: %s, line: %d.", mapPath.c_str(), static_cast<int>(lineIndex)); } description.m_id = lineIndex; description.m_chunkId = lineIndex; description.m_path = imagePath; description.m_classId = std::stoi(classId); if (description.m_classId >= labelDimension) { RuntimeError( "Image '%s' has invalid class id '%d'. Expected label dimension is '%d'.", mapPath.c_str(), static_cast<int>(description.m_classId), static_cast<int>(labelDimension)); } m_imageSequences.push_back(description); } }
void leaky::open() { LoadMap(); setupSymbols(progFile); // open up the log file mappedLogFile = ::open(logFile, O_RDONLY); if (mappedLogFile < 0) { perror("open"); exit(-1); } off_t size; firstLogEntry = (malloc_log_entry*) mapFile(mappedLogFile, PROT_READ, &size); lastLogEntry = (malloc_log_entry*)((char*)firstLogEntry + size); analyze(); exit(0); }
void WorldMap::Load(const std::string& fileName) { std::ifstream mapFile(fileName); std::string row; if (mapFile.is_open()) { int i=0; //read in a whole line while(mapFile >> row) { int j=0; //iterate through individual numbers in the line, reading them as chars then converting to ints, then to enum type for(auto digit : row) { mapGrid[i][j].second.ChangeType(static_cast<MapObject::ObjectType>(atoi(&digit))); ++j; } ++i; } }