void Map_Snapshot() { CString strMsg; // we need to do the following // 1. make sure the snapshot directory exists (create it if it doesn't) // 2. find out what the lastest save is based on number // 3. inc that and save the map CString strOrgPath, strOrgFile; ExtractPath_and_Filename(currentmap, strOrgPath, strOrgFile); AddSlash(strOrgPath); strOrgPath += "snapshots"; bool bGo = true; struct _stat Stat; if (_stat(strOrgPath, &Stat) == -1) { bGo = (_mkdir(strOrgPath) != -1); } AddSlash(strOrgPath); if (bGo) { int nCount = 0; long lSize = 0; CString strNewPath = strOrgPath; strNewPath += strOrgFile; CString strFile; while (bGo) { strFile.Format("%s.%i", strNewPath, nCount); bGo = DoesFileExist(strFile, lSize); nCount++; } // strFile has the next available slot Map_SaveFile(strFile.GetBuffer(0), false); Sys_SetTitle (currentmap); if (lSize > 120 * 1024 * 1024) // total size of saves > 4 mb // Jonathan: bumped to 120mb { Sys_Printf("The snapshot files in the [%s] directory total more than 40 megabytes. You might consider cleaning the directory up.", strOrgPath); } } else { strMsg.Format("Snapshot save failed.. unabled to create directory\n%s", strOrgPath); g_pParentWnd->MessageBox(strMsg); } }
void BeginnerHelper::AddPlayer( PlayerNumber pn, NoteData *pSteps ) { ASSERT(!m_bInitialized); ASSERT(pSteps != NULL); ASSERT((pn >= 0) && (pn < NUM_PLAYERS)); ASSERT(GAMESTATE->IsHumanPlayer(pn)); if(!CanUse()) return; const Character *Character = GAMESTATE->m_pCurCharacters[pn]; ASSERT( Character != NULL ); if(!DoesFileExist(Character->GetModelPath())) return; m_NoteData[pn].CopyAll(*pSteps); m_bPlayerEnabled[pn] = true; }
bool Character::Has2DElems() { if( DoesFileExist(m_sCharDir + "2DFail/BGAnimation.ini") ) // check 2D Idle BGAnim exists return true; if( DoesFileExist(m_sCharDir + "2DFever/BGAnimation.ini") ) // check 2D Idle BGAnim exists return true; if( DoesFileExist(m_sCharDir + "2DGood/BGAnimation.ini") ) // check 2D Idle BGAnim exists return true; if( DoesFileExist(m_sCharDir + "2DMiss/BGAnimation.ini") ) // check 2D Idle BGAnim exists return true; if( DoesFileExist(m_sCharDir + "2DWin/BGAnimation.ini") ) // check 2D Idle BGAnim exists return true; if( DoesFileExist(m_sCharDir + "2DWinFever/BGAnimation.ini") ) // check 2D Idle BGAnim exists return true; if( DoesFileExist(m_sCharDir + "2DGreat/BGAnimation.ini") ) // check 2D Idle BGAnim exists return true; if( DoesFileExist(m_sCharDir + "2DIdle/BGAnimation.ini") ) // check 2D Idle BGAnim exists return true; return false; }
//----------------------------------------------------------------------------- // Purpose: Helper utility, Write buffer to file //----------------------------------------------------------------------------- bool CScriptLib::WriteBufferToFile( const char *pTargetName, CUtlBuffer &buffer, DiskWriteMode_t writeMode ) { char* ptr; char dirPath[MAX_PATH]; bool bSuccess = true; // create path // prime and skip to first seperator strcpy( dirPath, pTargetName ); ptr = strchr( dirPath, '\\' ); while ( ptr ) { ptr = strchr( ptr+1, '\\' ); if ( ptr ) { *ptr = '\0'; _mkdir( dirPath ); *ptr = '\\'; } } bool bDoWrite = false; if ( writeMode == WRITE_TO_DISK_ALWAYS ) { bDoWrite = true; } else if ( writeMode == WRITE_TO_DISK_UPDATE ) { if ( DoesFileExist( pTargetName ) ) { bDoWrite = true; } } if ( bDoWrite ) { bSuccess = g_pFullFileSystem->WriteFile( pTargetName, NULL, buffer ); } return bSuccess; }
bool RemoveDirectory(const std::string &dir_name) { // Don't do anything if the directory doesn't exist if (!DoesFileExist(dir_name)) { return true; } // Remove any files that still reside in the directory CleanDirectory(dir_name); // Finally, remove the folder itself with rmdir() int32_t success = rmdir(dir_name.c_str()); if(success == -1) { std::cerr << "UTILS ERROR: could not delete directory: " << dir_name << std::endl; return false; } return true; }
void CProfileSettings::Init(const wchar_t* pszFileName) { // Load m_bModified=true; // Load settings if (!CProfileFile::Load(pszFileName)) { // Save immediately to attach file name with CProfileFile CProfileFile::Reset(false); CProfileFile::SetFileName(pszFileName); if (DoesFileExist(pszFileName)) { SlxMessageBox(Format(L"Failed to load settings file '%s', resetting everything to default (%s)", pszFileName, CProfileFile::GetParseError()), MB_OK|MB_ICONWARNING); CProfileFile::Reset(false); } } m_bModified=false; }
void DumpSyncLogs( char *syncId ) { static float s_lastDump = 0.0f; if( GetHighResTime() > s_lastDump + 10.0f ) { s_lastDump = GetHighResTime(); char filename[256]; sprintf( filename, "synclog %s c%d.txt", syncId, g_app->GetClientToServer()->m_clientId ); if( !DoesFileExist( filename ) ) { DumpSyncRandLog( filename ); DumpWorldToSyncLog( filename ); AppDebugOut( "SYNCERROR log dumped to '%s'\n", filename ); } } }
BOOL CppOutPickModeCallback::Pick(IObjParam *ip,ViewExp *vpt) { INode *node = vpt->GetClosestHit(); if (node) { static TCHAR fname[256] = {'\0'}; OPENFILENAME ofn; memset(&ofn,0,sizeof(ofn)); FilterList fl; fl.Append( GetString(IDS_RB_CPPFILES)); fl.Append( _T("*.cpp")); TSTR title = GetString(IDS_RB_SAVEOBJECT); ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = theCppOut.hPanel; ofn.lpstrFilter = fl; ofn.lpstrFile = fname; ofn.nMaxFile = 256; ofn.lpstrInitialDir = ip->GetDir(APP_EXPORT_DIR); ofn.Flags = OFN_HIDEREADONLY|OFN_FILEMUSTEXIST|OFN_PATHMUSTEXIST; ofn.lpstrDefExt = _T("asc"); ofn.lpstrTitle = title; tryAgain: if (GetSaveFileName(&ofn)) { if (DoesFileExist(fname)) { TSTR buf1; TSTR buf2 = GetString(IDS_RB_SAVEOBJECT); buf1.printf(GetString(IDS_RB_FILEEXISTS),fname); if (IDYES!=MessageBox( theCppOut.hPanel, buf1,buf2,MB_YESNO|MB_ICONQUESTION)) { goto tryAgain; } } theCppOut.OutputObject(node,fname); } } return TRUE; }
bool ReadScriptDescriptor::OpenFile(const std::string &filename) { // check for file existence if(!DoesFileExist(filename)) { PRINT_ERROR << "Attempted to open unavailable file: " << filename << std::endl; return false; } if(ScriptManager->IsFileOpen(filename)) { PRINT_ERROR << "Attempted to open file that is already opened: " << filename << std::endl; return false; } // Check that the thread stack is in sync with open files. assert(ScriptManager->_CheckForPreviousLuaState(filename) == NULL); // Increases the global stack size by 1 element. That is needed because the new thread will be pushed in the // stack and we have to be sure there is enough space there. lua_checkstack(ScriptManager->GetGlobalState(), 1); _lstack = lua_newthread(ScriptManager->GetGlobalState()); // Attempt to load and execute the Lua file if(luaL_loadfile(_lstack, filename.c_str()) != 0 || lua_pcall(_lstack, 0, 0, 0)) { PRINT_ERROR << "could not open script file: " << filename << ", error message:" << std::endl << lua_tostring(_lstack, private_script::STACK_TOP) << std::endl; _access_mode = SCRIPT_CLOSED; return false; } _filename = filename; _access_mode = SCRIPT_READ; // If the file is already open, we don't add it twice. ScriptManager->_AddOpenFile(this); return true; } // bool ReadScriptDescriptor::OpenFile(string file_name, bool force_reload)
bool MakeDirectory(const std::string &dir_name) { // Don't do anything if the directory already exists. if (DoesFileExist(dir_name)) { return true; } // Create the directory with mkdir(). Note that Windows does not require file permissions to be set, but // all other operating systems do. #ifdef _WIN32 int32_t success = mkdir(dir_name.c_str()); #else int32_t success = mkdir(dir_name.c_str(), S_IRWXG | S_IRWXO | S_IRWXU); #endif if(success == -1) { std::cerr << "UTILS ERROR: could not create directory: " << dir_name.c_str() << std::endl; return false; } return true; }
/** * Function name CInsertResource::Execute * Description * @return void * @exception * @see */ BOOL CInsertResource::Execute() { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); Init(); SetFileName(); BOOL bRes = !DoesFileExist(m_sFileName, TRUE); if(bRes) { GenResource(m_ResourceText); COperation::WriteFile(m_ResourceText); ParseConfig(); GenImportText(m_ImportText); InsertResourceImport(); CString ConfigText = m_ConfigText.c_str(); WriteFile(ConfigText); InformProjectManager(); } m_ConfigText.empty(); m_ResourceText.Empty(); m_ImportText.Empty(); m_aVarList.RemoveAll(); return bRes; }
bool VerifyScript(int i) { std::wstring file_name = SCRIPTS_DIRECTORY + PYTHON_FILE_NAMES[i]; if (!DoesFileExist(file_name)) { // file doesn't exist, copy the file over return ReAquireScript(i); } else { unsigned long long verify_last = GetLastUpdatedValue(i); if (verify_last == 0) return false; if (LAST_UPDATED != verify_last) { std::cerr << "Reaquiring script " << wToS(PYTHON_FILE_NAMES[i]) << std::endl; // file exists, but is out of date. Overwrite it. return ReAquireScript(i); } return true; } }
uint32_t GetFileModTime(const std::string& filename) { if (!DoesFileExist(filename)) return 0; #ifdef _WIN32 GET_FILEEX_INFO_LEVELS info_level_id = GetFileExInfoStandard; WIN32_FILE_ATTRIBUTE_DATA file_information; if (GetFileAttributesEx(filename.c_str(), info_level_id, &file_information) == 0) return 0; // Only return the lower part of the mod time, as we don't need 64-bit precision to compare file times // for our needs. return static_cast<uint32_t>(file_information.ftLastWriteTime.dwLowDateTime); #else // create a file attribute structure struct stat attrib; if (stat(filename.c_str(), &attrib) != 0) return 0; // Returns the latest system modification time. return static_cast<uint32_t>(attrib.st_mtime); #endif }
/** * Function name CInsertFunctionBlock::Execute * Description * @return BOOL * @exception * @see */ BOOL CInsertFunctionBlock::Execute() { AFX_MANAGE_STATE(AfxGetStaticModuleState( )); Init(); SetFileName(); BOOL bRes = !DoesFileExist(m_sName, FALSE); if(bRes) { GenFunctionBlock(m_FunctionBlockText); InsertVarList(m_FunctionBlockText, m_FunctionBlock); if (m_FileType == FILETYPE_ST || m_FileType == FILETYPE_IL) { WriteFile(m_FunctionBlockText); } else { Write4grFile(); } InformProjectManager(); } m_FunctionBlockText.Empty(); m_aVarList.RemoveAll(); return bRes; }
void JukeBox::LoadMusicXML() { if (!m_init) // the sound device has not be initialized (was busy?) return; // is xml_file already loaded ? std::set<std::string>::iterator it_profile = m_profiles_loaded.find("music") ; if (it_profile != m_profiles_loaded.end()) { MSG_DEBUG("jukebox", "Music is already loaded !"); return; } std::cout << _("o Loading music") << std::endl; XmlReader doc; // Load the XML std::string folder = Config::GetInstance()->GetDataDir() + "music" PATH_SEPARATOR; std::string xml_filename = folder + "profile.xml"; if (!DoesFileExist(xml_filename)) { std::cerr << "[Music] Error : file " << xml_filename << " not found" << std::endl; return; } if (!doc.Load(xml_filename)) return; xmlNodeArray nodes = XmlReader::GetNamedChildren(doc.GetRoot(), "music"); xmlNodeArray::const_iterator it = nodes.begin(), end = nodes.end(); for (; it != end; ++it) { // loading XML ... std::string sample="no_sample"; std::string file="no_file"; XmlReader::ReadStringAttr(*it, "type", sample); XmlReader::ReadStringAttr(*it, "playlist", file); MSG_DEBUG("jukebox", "Load music sample %s", sample.c_str()); // Load sound std::string filename = folder + file; if (!DoesFileExist(filename)) { std::cerr << "Music error: File " << filename.c_str() << " does not exist !" << std::endl; continue; } std::ifstream fp(filename.c_str()); if (fp.bad()) { std::cerr << "Music error: File " << filename.c_str() << " couldn't be read !" << std::endl; continue; } std::string line; while (std::getline(fp, line)) { if (line[0] == '#') continue; if (!DoesFileExist(line)) { // This line comes from an XML file, thus path separator here is "/" line = filename.substr(0, filename.find_last_of("/")) + PATH_SEPARATOR + line; if (!DoesFileExist(line)) { std::cerr << "[Music] Unable to find " << line << " music file." << std::endl; continue; } } playlist[sample].push_back(line); } } // The profile is loaded m_profiles_loaded.insert("music"); playing_pl = playlist.end(); }
bool BootMode::_SaveSettingsFile(const std::string &filename) { // No need to save the settings if we haven't edited anything! if(!_has_modified_settings) return false; std::string file; std::string fileTemp; // Load the settings file for reading in the original data fileTemp = GetUserDataPath(false) + "/settings.lua"; if(filename.empty()) file = fileTemp; else file = GetUserDataPath(false) + "/" + filename; //copy the default file so we have an already set up lua file and then we can modify its settings if(!DoesFileExist(file)) CopyFile(std::string("dat/config/settings.lua"), file); WriteScriptDescriptor settings_lua; if(!settings_lua.OpenFile(file)) { PRINT_ERROR << "Failed to open settings file: " << file << std::endl; return false; } settings_lua.WriteComment("--General settings--"); settings_lua.BeginTable("settings"); // Write the current settings into the .lua file settings_lua.WriteComment("Show the first time help window"); settings_lua.WriteInt("first_start", 0); //Save language settings settings_lua.WriteComment("The GUI and in game dialogues language used"); settings_lua.WriteString("language", SystemManager->GetLanguage()); // video settings_lua.InsertNewLine(); settings_lua.WriteComment("--Video settings--"); settings_lua.BeginTable("video_settings"); settings_lua.WriteComment("Screen resolution"); settings_lua.WriteInt("screen_resx", VideoManager->GetScreenWidth()); settings_lua.WriteInt("screen_resy", VideoManager->GetScreenHeight()); settings_lua.WriteComment("Run the screen fullscreen/in a window"); settings_lua.WriteBool("full_screen", VideoManager->IsFullscreen()); settings_lua.WriteComment("Used smoothed tile sprites when playing"); settings_lua.WriteBool("smooth_graphics", VideoManager->ShouldSmoothPixelArt()); settings_lua.EndTable(); // video_settings // audio settings_lua.InsertNewLine(); settings_lua.WriteComment("--Audio settings--"); settings_lua.BeginTable("audio_settings"); settings_lua.WriteComment("Music and sounds volumes: [0.0 - 1.0]"); settings_lua.WriteFloat("music_vol", AudioManager->GetMusicVolume()); settings_lua.WriteFloat("sound_vol", AudioManager->GetSoundVolume()); settings_lua.EndTable(); // audio_settings // input settings_lua.InsertNewLine(); settings_lua.WriteComment("--Keyboard settings--"); settings_lua.BeginTable("key_settings"); settings_lua.WriteComment("Keyboard key SDL values."); settings_lua.WriteInt("up", InputManager->GetUpKey()); settings_lua.WriteInt("down", InputManager->GetDownKey()); settings_lua.WriteInt("left", InputManager->GetLeftKey()); settings_lua.WriteInt("right", InputManager->GetRightKey()); settings_lua.WriteInt("confirm", InputManager->GetConfirmKey()); settings_lua.WriteInt("cancel", InputManager->GetCancelKey()); settings_lua.WriteInt("menu", InputManager->GetMenuKey()); settings_lua.WriteInt("pause", InputManager->GetPauseKey()); settings_lua.EndTable(); // key_settings settings_lua.InsertNewLine(); settings_lua.WriteComment("--Joystick settings--"); settings_lua.BeginTable("joystick_settings"); settings_lua.WriteComment("Tells whether joysticks input should be taken in account"); settings_lua.WriteBool("input_disabled", (!InputManager->GetJoysticksEnabled())); settings_lua.WriteComment("The axis index number to be used as x/y axis"); settings_lua.WriteInt("x_axis", InputManager->GetXAxisJoy()); settings_lua.WriteInt("y_axis", InputManager->GetYAxisJoy()); settings_lua.WriteComment("The joystick x/y axis dead zone [0-N] (Default: 8192)"); settings_lua.WriteInt("threshold", InputManager->GetThresholdJoy()); settings_lua.WriteComment("Joystick keys index number [0-N] (0 is the first button)"); settings_lua.WriteInt("confirm", InputManager->GetConfirmJoy()); settings_lua.WriteInt("cancel", InputManager->GetCancelJoy()); settings_lua.WriteInt("menu", InputManager->GetMenuJoy()); settings_lua.WriteInt("pause", InputManager->GetPauseJoy()); settings_lua.WriteInt("quit", InputManager->GetQuitJoy()); settings_lua.EndTable(); // joystick_settings settings_lua.EndTable(); // settings // and save it! settings_lua.SaveFile(); settings_lua.CloseFile(); _has_modified_settings = false; return true; } // bool BootMode::_SaveSettingsFile(const std::string& filename)
int SetInput (AsnInfo *asn) { /* Arguments: ** asn io: Association info structure */ extern int status; /* Local Variables */ char filename[SZ_FNAME+1]; int exist; /* EXISTS_YES or EXISTS_NO */ int in_dot; char linput[SZ_FNAME+1]; /* Lower case version of input */ int incase; /* What kind of input do we have? */ int DoesFileExist (char *); char *lowcase (char *, char *); int GetAsnName (char *, char *); void FindAsnRoot (char *, char *); /* Initialize internal variables here... */ filename[0] = '\0'; /* convert input to lowercase for use only in looking for extensions */ lowcase (linput, asn->input); /* Determine what kind of input: root only, ** root + suffix, or ** root + suffix + extension ** We will look for '.fit' or '.fits' extensions. */ /* First, let's complete the input filename with a FITS extension.*/ if (strstr(linput, ".fit") == NULL) { strcpy (filename, asn->input); strcat (filename, ".fits"); } else { strcpy (filename, asn->input); strcat (filename, "\0"); } /* Initialize local variable */ incase = 0; /* Now, we find out what kind of input name was provided... */ if (strstr(linput, "_asn") != NULL){ incase = 0; } else if (strstr(linput, "_raw") != NULL ) { incase = 1; } else if (!IsProduct (linput)) { /* Not a sub-product/intermediate product... */ incase = 2; } else { /* treat as if it was only a rootname (plus '.fits') */ incase = 3; } if (asn->debug) { sprintf (MsgText, "GetAsnTable: incase = %d",incase); trlmessage (MsgText); } /* Given this full filename for a file which exists, ** copy out just the rootname. */ FindAsnRoot(filename, asn->rootname); /* Can we find the file as it is input? */ exist = DoesFileExist(filename); /* Treat filename according to what was input... */ switch (incase) { case 0: /* We have an ASN file explicitly specified */ if (exist == EXISTS_YES) { /* Found an ASN file: Set values in ASN structure */ asn->process = FULL; strcpy(asn->asn_table, filename); strcpy(asn->filename, filename); if (asn->verbose) { trlmessage ("Processing FULL ASN table..."); } } else { /* Couldn't find specified ASN file... */ sprintf (MsgText, "File %s not found for processing", filename); trlerror (MsgText); return (status = OPEN_FAILED); } break; case 1: /* We have a RAW file explicitly specified */ if (exist == EXISTS_YES) { /* Found a RAW file: Set values in ASN structure */ strcpy (asn->filename, filename); strcpy (asn->asn_table, filename); strcat (asn->asn_table, "\0"); if (asn->verbose) { sprintf (MsgText, "Processing SINGLE image %s...", asn->filename); trlmessage (MsgText); } asn->process = SINGLE; } else { /* Couldn't find specified RAW file... */ sprintf (MsgText,"File %s not found for processing", filename); trlerror (MsgText); return (status = OPEN_FAILED); } break; case 2: /* We have a sub-product/intermediate file specified ** for re-processing. They should really just run the ** stand-alone tasks separately by hand, but... */ if (exist == EXISTS_YES) { strcpy (asn->filename, filename); /* Look for ASN_TAB in file's header, and copy to ** ASN->asn_table if it is found. */ if (!GetAsnName (filename, asn->asn_table) ) { /* No ASN table listed, process as a ** SINGLE exposure */ asn->process = SINGLE; if (asn->verbose) { trlmessage ("Re-Processing a SINGLE image from ASN table..."); } } else { /* ASN table given in file, PARTIALLY process ** table */ asn->process = PARTIAL; if (asn->verbose) { trlmessage ("Re-Processing PART of ASN table..."); } } } else { /* Couldn't find specified file... */ sprintf (MsgText,"File %s not found for re-processing", filename); trlerror (MsgText); return (status = OPEN_FAILED); } break; case 3: /* We only have a rootname (with .fits extension) ** specified */ default: if (exist == EXISTS_YES) { strcpy (asn->filename, filename); /* Look for ASN_TAB in file's header, and copy to ** ASN->asn_table if it is found. */ if (!GetAsnName (filename, asn->asn_table)) { /* No ASN table listed, process as a SINGLE ** exposure */ asn->process = SINGLE; if (asn->verbose) { trlmessage ("Processing a SINGLE image from ASN table..."); } } else { /* ASN table given in file, PARTIALLY process ** table */ asn->process = PARTIAL; if (asn->verbose) { trlmessage ("Processing PART of ASN table..."); } } } else { /* Let's start fresh, shall we? At this point we only ** have as rootname and (maybe) a .fits extension... in_dot = strcspn (filename, ".fit"); */ in_dot = strlen(filename) - strlen(strstr (filename, ".fit")); if (asn->debug){ sprintf (MsgText, "For file %s, in_dot = %d", filename, in_dot); trlmessage (MsgText); } /* Truncate extension off of filename */ filename[in_dot] = '\0'; /* Create full ASN table name from input rootname */ strcat (filename, "_asn.fits"); exist = DoesFileExist (filename); if (exist == EXISTS_YES) { strcat (filename, "\0"); /* If a name was specified, the file must exist. */ strcpy (asn->asn_table, filename); if (asn->verbose) { trlmessage ("Found and processing FULL ASN table..."); } asn->process = FULL; } else { /* Couldn't find ASN file, so ** trim off suffix previously tested. */ in_dot = strlen (filename) - strlen (strstr(filename, "_asn")) ; filename[in_dot] = '\0'; /* ... and look for RAW file */ strcat (filename, "_raw.fits"); exist = DoesFileExist (filename); if (exist == EXISTS_YES) { /* Found a RAW file; ** Set values in ASN structure */ strcat (filename, "\0"); strcpy (asn->asn_table, filename); if (asn->verbose) { trlmessage ("Processing a SINGLE image from ASN table..."); } asn->process = SINGLE; } else { /* Is INPUT the rootname of a product which ** hasn't been created yet? */ /* Extract just the rootname plus last character ** of rootname (which may be the subproduct ID*/ in_dot = strlen (filename) - strlen (strstr (filename, "_raw")); filename[in_dot -1] = '\0'; /* Replace last character of filename with ** 0_asn.fits */ strcat (filename, "0_asn.fits"); exist = DoesFileExist (filename); if (exist == EXISTS_YES) { strcpy (asn->asn_table, filename); if (asn->verbose) { trlmessage ("PARTIAL processing of ASN table..."); } asn->process = PARTIAL; } else { /* We can't find a matching file or ASN ** table to process */ sprintf (MsgText, "File %s not found for processing", filename); trlerror (MsgText); return (status = OPEN_FAILED); } } } } /* End of Exists ELSE statement for this case */ break; /* End of Case 3 and DEFAULT case */ } /* End of switch statement */ if (asn->debug) { trlmessage ("SetInput: Determined what ASN table to process and how."); } return (status); }
// // TODO: Instead of returning TRUE/FALSE, it would be nice to return // a flag indicating: // - whether the installation is actually valid; // - if it's broken or not (aka. needs for repair, or just upgrading). // static BOOLEAN IsValidNTOSInstallationByHandle( IN HANDLE SystemRootDirectory) { BOOLEAN Success = FALSE; PCWSTR PathName; USHORT i; UNICODE_STRING VendorName; WCHAR VendorNameBuffer[MAX_PATH]; /* Check for the existence of \SystemRoot\System32 */ PathName = L"System32\\"; if (!DoesPathExist(SystemRootDirectory, PathName)) { // DPRINT1("Failed to open directory '%S', Status 0x%08lx\n", PathName, Status); return FALSE; } /* Check for the existence of \SystemRoot\System32\drivers */ PathName = L"System32\\drivers\\"; if (!DoesPathExist(SystemRootDirectory, PathName)) { // DPRINT1("Failed to open directory '%S', Status 0x%08lx\n", PathName, Status); return FALSE; } /* Check for the existence of \SystemRoot\System32\config */ PathName = L"System32\\config\\"; if (!DoesPathExist(SystemRootDirectory, PathName)) { // DPRINT1("Failed to open directory '%S', Status 0x%08lx\n", PathName, Status); return FALSE; } #if 0 /* * Check for the existence of SYSTEM and SOFTWARE hives in \SystemRoot\System32\config * (but we don't check here whether they are actually valid). */ PathName = L"System32\\config\\SYSTEM"; if (!DoesFileExist(SystemRootDirectory, PathName)) { // DPRINT1("Failed to open file '%S', Status 0x%08lx\n", PathName, Status); return FALSE; } PathName = L"System32\\config\\SOFTWARE"; if (!DoesFileExist(SystemRootDirectory, PathName)) { // DPRINT1("Failed to open file '%S', Status 0x%08lx\n", PathName, Status); return FALSE; } #endif RtlInitEmptyUnicodeString(&VendorName, VendorNameBuffer, sizeof(VendorNameBuffer)); /* Check for the existence of \SystemRoot\System32\ntoskrnl.exe and retrieves its vendor name */ PathName = L"System32\\ntoskrnl.exe"; Success = CheckForValidPEAndVendor(SystemRootDirectory, PathName, &VendorName); if (!Success) DPRINT1("Kernel executable '%S' is either not a PE file, or does not have any vendor?\n", PathName); /* The kernel gives the OS its flavour */ if (Success) { for (i = 0; i < ARRAYSIZE(KnownVendors); ++i) { Success = !!FindSubStrI(VendorName.Buffer, KnownVendors[i]); if (Success) { /* We have found a correct vendor combination */ DPRINT1("IsValidNTOSInstallation: We've got an NTOS installation from %S !\n", KnownVendors[i]); break; } } } /* OPTIONAL: Check for the existence of \SystemRoot\System32\ntkrnlpa.exe */ /* Check for the existence of \SystemRoot\System32\ntdll.dll and retrieves its vendor name */ PathName = L"System32\\ntdll.dll"; Success = CheckForValidPEAndVendor(SystemRootDirectory, PathName, &VendorName); if (!Success) DPRINT1("User-mode DLL '%S' is either not a PE file, or does not have any vendor?\n", PathName); if (Success) { for (i = 0; i < ARRAYSIZE(KnownVendors); ++i) { if (!!FindSubStrI(VendorName.Buffer, KnownVendors[i])) { /* We have found a correct vendor combination */ DPRINT1("IsValidNTOSInstallation: The user-mode DLL '%S' is from %S\n", PathName, KnownVendors[i]); break; } } } return Success; }
void DrawMap(void) { char buff[512]; /*------------------------------------------------------------------------------ //Begin Input Ctrl & View Matrix Setup ------------------------------------------------------------------------------*/ static float angle = 0.0f; static float view = -240.0f; //view = -view; D3DXMATRIX matWorld; D3DXMATRIX matWorld2; D3DXMatrixTranslation(&matWorld2,0.0f,0.0f,angle/1500.0f); //D3DXMatrixRotationX(&matWorld, DEGtoRAD(angle/1.0069)); //DXMatrixRotationY(&matWorld, DEGtoRAD(angle)); D3DXMatrixRotationYawPitchRoll(&matWorld,DEGtoRAD(angle/20.0f),DEGtoRAD(angle/15.0f),DEGtoRAD(angle/10.0f)); matWorld*=matWorld2; angle += 1.0f; //g_pD3DDevice->SetTransform(D3DTS_WORLD, &matWorld); D3DXMATRIX matView; static float mawari = 0.0f; float delta; delta = 0.02f; if( GetKeyState(VK_CONTROL)&0x8000 ){ delta = 0.1f; }; if( GetKeyState(VK_RIGHT) & 0x8000 ) mawari-=delta; if( GetKeyState(VK_LEFT) & 0x8000 ) mawari+=delta; static D3DXVECTOR3 pos(0.0f, 0.0f, 0.0f); delta = 2.0f; if( GetKeyState(VK_CONTROL)&0x8000 ){ delta = 5.0f; }; if( GetKeyState(VK_UP) & 0x8000 ){ pos.x+=cos(mawari)*delta; pos.z+=sin(mawari)*delta; } if( GetKeyState(VK_DOWN) & 0x8000 ){ pos.x+=cos(mawari+3.1415926f)*delta; pos.z+=sin(mawari+3.1415926f)*delta; } if( GetKeyState(VK_PRIOR) & 0x8000 ){ pos.y+=delta; } if( GetKeyState(VK_NEXT) & 0x8000 ){ pos.y-=delta; } if( GetKeyState(VK_HOME) & 0x8000 ){ mawari=pos.x=pos.y=pos.z=0.0f; } D3DXVECTOR3 pnt(pos.x+cos(mawari), pos.y+0.0f, pos.z+sin(mawari)); D3DXVECTOR3 up(0.0f, 1.0f, 0.0f); D3DXMatrixLookAtRH(&matView, &pos, &pnt, &up); g_pD3DDevice->SetTransform(D3DTS_VIEW, &matView); D3DXMATRIX matProj; D3DXMatrixPerspectiveFovRH(&matProj, DEGtoRAD(45.0f), 4.0f / 3.0f, 1.0f, 500.0f); g_pD3DDevice->SetTransform(D3DTS_PROJECTION, &matProj); if( GetAsyncKeyState(VK_RETURN) & 0x1 ){ AutoMakeMMB=TRUE;} /*------------------------------------------------------------------------------ //End Input Ctrl & View Matrix Setup ------------------------------------------------------------------------------*/ /*------------------------------------------------------------------------------ //Begin RenderState ------------------------------------------------------------------------------*/ //g_pD3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW/*/D3DCULL_NONE*/ ); g_pD3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW/*/D3DCULL_NONE*/ ); g_pD3DDevice->SetRenderState( D3DRS_ZENABLE, TRUE ); //g_pD3DDevice->SetLight(0,&light); //g_pD3DDevice->LightEnable(0,TRUE); g_pD3DDevice->SetRenderState(D3DRS_LIGHTING,FALSE); //g_pD3DDevice->SetRenderState(D3DRS_AMBIENT, 0xF0F0F0F0); g_pD3DDevice->SetRenderState(D3DRS_SHADEMODE, D3DSHADE_GOURAUD ); g_pD3DDevice->SetRenderState(D3DRS_ALPHABLENDENABLE, TRUE); g_pD3DDevice->SetRenderState( D3DRS_STENCILENABLE, TRUE ); g_pD3DDevice->SetRenderState( D3DRS_ALPHATESTENABLE , TRUE ); g_pD3DDevice->SetRenderState( D3DRS_ALPHAREF , 0x80 ); g_pD3DDevice->SetRenderState( D3DRS_ALPHAFUNC , D3DCMP_GREATER ); //g_pD3DDevice->SetRenderState(D3DRS_EDGEANTIALIAS,TRUE); /*------------------------------------------------------------------------------ //End RenderState ------------------------------------------------------------------------------*/ //地图是在TheDesertWorld.cpp里画的 //g_pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET|D3DCLEAR_ZBUFFER, D3DCOLOR_XRGB(0,0,128), 1.0f, 0L ); if( flgFirst ) logprintf("MZB:%d",noj); pory = 0; for( int i=0; i< noj; i++ ) { //if(i>=50) break; D3DXMATRIX matWorld; D3DXMATRIX matWorld2; D3DXMATRIX matWorld3; D3DXMATRIX matWorld4; D3DXMATRIX matWorldR4; D3DXMATRIX matWorldR5; D3DXMATRIX matWorldR6; ZeroMemory(&matWorld,sizeof(D3DXMATRIX)); D3DXMatrixScaling(&matWorld3,oj[i].fScaleX,oj[i].fScaleY,oj[i].fScaleZ); D3DXMatrixTranslation(&matWorld,oj[i].fTransX,oj[i].fTransY,oj[i].fTransZ); D3DXMatrixRotationX(&matWorldR4,oj[i].fRotX); D3DXMatrixRotationY(&matWorldR5,oj[i].fRotY); D3DXMatrixRotationZ(&matWorldR6,oj[i].fRotZ); matWorld2 = matWorldR4 * matWorldR5 * matWorldR6; matWorld=((matWorld3*matWorld2)/**matWorld4*/)*matWorld; g_pD3DDevice->SetTransform(D3DTS_WORLD, &matWorld); if( oj[i].fScaleX*oj[i].fScaleY*oj[i].fScaleZ < 0.0f ) { g_pD3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW ); } else { g_pD3DDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CCW ); } if(0) { float pp[]={-20,0,0,20,0,0, 0,-20,0,0,20,0, 0,0,-20,0,0,20}; //float pp[]={-10,0,0,10,0,0, 0,-10,0,0,10,0, 0,0,-10,0,0,10}; g_pD3DDevice->SetFVF(D3DFVF_XYZ); g_pD3DDevice->DrawPrimitiveUP(D3DPT_LINELIST,3,pp,12); } //Draw MzbLists Hint { RECT rc={5,91,600,128}; //自动输出 i = haha; //这个会打乱文件名和文件内容的正确配对吗? if (AutoMakeMMB == TRUE) {haha+=1;}; if (haha == (noj -1)) {haha = 0;AutoMakeMMB == false;}; sprintf(buff,"-----MZBList:%d/%d",i,noj); pDxFont->DrawTextA(NULL,buff,lstrlen(buff),&rc, DT_LEFT, D3DCOLOR_XRGB(0,0,255)); } for( int j=0; j< NumMMB; j++ ) { if( memcmp(MMBlist[j]+16,oj[i].id,16) ) continue; //Draw Mmb Hint { RECT rc={5,134,600,160}; sprintf(buff,"------- Draw MMB:%s",sstr(oj[i].id,16)); pDxFont->DrawTextA(NULL,buff,lstrlen(buff),&rc, DT_LEFT, D3DCOLOR_XRGB(0,0,255)); } /*------------------------------------------------------------------------------ //Begin MapObj Files Output ------------------------------------------------------------------------------*/ char opname[16]; //要输出的文件名 CopyMemory(opname,MMBlist[j]+16,16); ChangeSpaceToNull(opname); lstrcat(opname,".MapObj"); if (DoesFileExist(opname)) { logprintf("发现有文件重复将自动复盖,这些文件是%s",opname);} HANDLE hFile = CreateFile(opname,GENERIC_WRITE,FILE_SHARE_READ,NULL,OPEN_ALWAYS,FILE_ATTRIBUTE_NORMAL,NULL ); //ReadFile(hFile,pdat,dwSize,&dmy,NULL); if( hFile!=INVALID_HANDLE_VALUE && hFile!=NULL ) { DWORD dmy; //SetFilePointer(hFile,0,NULL,FILE_END); LPSTR ReadLocate = MMBlist[j+1]-16; int size = (int)(((*(DWORD*)&ReadLocate[4])>>3)&0x007ffff0); WriteFile(hFile,&ReadLocate[0],size,&dmy,NULL); CloseHandle(hFile); } /*------------------------------------------------------------------------------ //End MapObj Files Output ------------------------------------------------------------------------------*/ DrawMMB(MMBlist[j]); //信息输出1 { RECT rc={5,5,600,64}; sprintf(buff,"正在绘制Index数=%d\nLookAt:X=%02.2f Y=%02.2f Z=%02.2f",pory,pos.x,pos.y,pos.z); pDxFont->DrawTextA(NULL,buff,lstrlen(buff),&rc, DT_LEFT, D3DCOLOR_XRGB(196,196,0)); } //信息输出2 { RECT rc={5,48,600,96}; sprintf(buff,"%sMZB=%d MMB=%d\n当前第%d个MMB",oj?"总共":"第",noj,NumMMB,j); pDxFont->DrawTextA(NULL,buff,lstrlen(buff),&rc, DT_LEFT, D3DCOLOR_XRGB(196,196,0)); } break; }//End For MumMMB break; }//End For Noj
/* Resolves actor paths a la LoadActor("..."), with autowildcarding and .redir * files. Returns a path *within* the Rage filesystem, unlike the FILEMAN * function of the same name. */ bool ActorUtil::ResolvePath( RString &sPath, const RString &sName, bool optional ) { CollapsePath( sPath ); // If we know this is an exact match, don't bother with the GetDirListing, // so "foo" doesn't partial match "foobar" if "foo" exists. RageFileManager::FileType ft = FILEMAN->GetFileType( sPath ); if( ft != RageFileManager::TYPE_FILE && ft != RageFileManager::TYPE_DIR ) { vector<RString> asPaths; GetDirListing( sPath + "*", asPaths, false, true ); // return path too if( asPaths.empty() ) { if(optional) { return false; } RString sError = ssprintf( "%s: references a file \"%s\" which doesn't exist", sName.c_str(), sPath.c_str() ); switch(LuaHelpers::ReportScriptError(sError, "BROKEN_FILE_REFERENCE", true)) { case Dialog::abort: RageException::Throw( "%s", sError.c_str() ); break; case Dialog::retry: FILEMAN->FlushDirCache(); return ResolvePath( sPath, sName ); case Dialog::ignore: return false; default: FAIL_M("Invalid response to Abort/Retry/Ignore dialog"); } } THEME->FilterFileLanguages( asPaths ); if( asPaths.size() > 1 ) { RString sError = ssprintf( "%s: references a file \"%s\" which has multiple matches", sName.c_str(), sPath.c_str() ); sError += "\n" + join( "\n", asPaths ); switch(LuaHelpers::ReportScriptError(sError, "BROKEN_FILE_REFERENCE", true)) { case Dialog::abort: RageException::Throw( "%s", sError.c_str() ); break; case Dialog::retry: FILEMAN->FlushDirCache(); return ResolvePath( sPath, sName ); case Dialog::ignore: asPaths.erase( asPaths.begin()+1, asPaths.end() ); break; default: FAIL_M("Invalid response to Abort/Retry/Ignore dialog"); } } sPath = asPaths[0]; } if( ft == RageFileManager::TYPE_DIR ) { RString sLuaPath = sPath + "/default.lua"; if( DoesFileExist(sLuaPath) ) { sPath = sLuaPath; return true; } } sPath = DerefRedir( sPath ); return true; }
// // TODO: Instead of returning TRUE/FALSE, it would be nice to return // a flag indicating: // - whether the installation is actually valid; // - if it's broken or not (aka. needs for repair, or just upgrading). // static BOOLEAN IsValidNTOSInstallationByHandle( IN HANDLE SystemRootDirectory, OUT PUSHORT Machine OPTIONAL, OUT PUNICODE_STRING VendorName OPTIONAL) { BOOLEAN Success = FALSE; PCWSTR PathName; USHORT i; USHORT LocalMachine; UNICODE_STRING LocalVendorName; WCHAR VendorNameBuffer[MAX_PATH]; /* Check for VendorName validity */ if (VendorName->MaximumLength < sizeof(UNICODE_NULL)) { /* Don't use it, invalidate the pointer */ VendorName = NULL; } else { /* Zero it out */ *VendorName->Buffer = UNICODE_NULL; VendorName->Length = 0; } /* Check for the existence of \SystemRoot\System32 */ PathName = L"System32\\"; if (!DoesDirExist(SystemRootDirectory, PathName)) { // DPRINT1("Failed to open directory '%S', Status 0x%08lx\n", PathName, Status); return FALSE; } /* Check for the existence of \SystemRoot\System32\drivers */ PathName = L"System32\\drivers\\"; if (!DoesDirExist(SystemRootDirectory, PathName)) { // DPRINT1("Failed to open directory '%S', Status 0x%08lx\n", PathName, Status); return FALSE; } /* Check for the existence of \SystemRoot\System32\config */ PathName = L"System32\\config\\"; if (!DoesDirExist(SystemRootDirectory, PathName)) { // DPRINT1("Failed to open directory '%S', Status 0x%08lx\n", PathName, Status); return FALSE; } #if 0 /* * Check for the existence of SYSTEM and SOFTWARE hives in \SystemRoot\System32\config * (but we don't check here whether they are actually valid). */ PathName = L"System32\\config\\SYSTEM"; if (!DoesFileExist(SystemRootDirectory, PathName)) { // DPRINT1("Failed to open file '%S', Status 0x%08lx\n", PathName, Status); return FALSE; } PathName = L"System32\\config\\SOFTWARE"; if (!DoesFileExist(SystemRootDirectory, PathName)) { // DPRINT1("Failed to open file '%S', Status 0x%08lx\n", PathName, Status); return FALSE; } #endif RtlInitEmptyUnicodeString(&LocalVendorName, VendorNameBuffer, sizeof(VendorNameBuffer)); /* Check for the existence of \SystemRoot\System32\ntoskrnl.exe and retrieves its vendor name */ PathName = L"System32\\ntoskrnl.exe"; Success = CheckForValidPEAndVendor(SystemRootDirectory, PathName, &LocalMachine, &LocalVendorName); if (!Success) DPRINT1("Kernel executable '%S' is either not a PE file, or does not have any vendor?\n", PathName); /* * The kernel gives the OS its flavour. If we failed due to the absence of * ntoskrnl.exe this might be due to the fact this particular installation * uses a custom kernel that has a different name, overridden in the boot * parameters. We then rely on the existence of ntdll.dll, which cannot be * renamed on a valid NT system. */ if (Success) { for (i = 0; i < ARRAYSIZE(KnownVendors); ++i) { Success = !!FindSubStrI(LocalVendorName.Buffer, KnownVendors[i]); if (Success) { /* We have found a correct vendor combination */ DPRINT("IsValidNTOSInstallation: We've got an NTOS installation from %S !\n", KnownVendors[i]); break; } } /* Return the target architecture */ if (Machine) { /* Copy the value and invalidate the pointer */ *Machine = LocalMachine; Machine = NULL; } /* Return the vendor name */ if (VendorName) { /* Copy the string and invalidate the pointer */ RtlCopyUnicodeString(VendorName, &LocalVendorName); VendorName = NULL; } } /* OPTIONAL: Check for the existence of \SystemRoot\System32\ntkrnlpa.exe */ /* Check for the existence of \SystemRoot\System32\ntdll.dll and retrieves its vendor name */ PathName = L"System32\\ntdll.dll"; Success = CheckForValidPEAndVendor(SystemRootDirectory, PathName, &LocalMachine, &LocalVendorName); if (!Success) DPRINT1("User-mode DLL '%S' is either not a PE file, or does not have any vendor?\n", PathName); if (Success) { for (i = 0; i < ARRAYSIZE(KnownVendors); ++i) { if (!!FindSubStrI(LocalVendorName.Buffer, KnownVendors[i])) { /* We have found a correct vendor combination */ DPRINT("IsValidNTOSInstallation: The user-mode DLL '%S' is from %S\n", PathName, KnownVendors[i]); break; } } /* Return the target architecture if not already obtained */ if (Machine) { /* Copy the value and invalidate the pointer */ *Machine = LocalMachine; Machine = NULL; } /* Return the vendor name if not already obtained */ if (VendorName) { /* Copy the string and invalidate the pointer */ RtlCopyUnicodeString(VendorName, &LocalVendorName); VendorName = NULL; } } return Success; }
std::vector<std::string> ListDirectory(const std::string &dir_name, const std::string &filter) { //create our vector std::vector<std::string> directoryList; // Don't try to list files if the directory does not exist. if (!DoesFileExist(dir_name)) { return directoryList; } //directory exists so lets list #if defined _WIN32 //--- WINDOWS -------------------------------------------------------------- WIN32_FIND_DATAA info = { 0 }; HANDLE handle = nullptr; std::string file_name = "*.*"; std::string first_file = dir_name + "/" + file_name; handle = FindFirstFileA(first_file.c_str(), &info); if (handle != INVALID_HANDLE_VALUE) { // List each file from the directory. do { file_name = info.cFileName; if (filter == "") { directoryList.push_back(file_name); } else if (file_name.find(filter) != std::string::npos) { directoryList.push_back(file_name); } } while (FindNextFileA(handle, &info)); } if (handle != nullptr && handle != INVALID_HANDLE_VALUE) { FindClose(handle); } #else //Not Windows DIR *dir; struct dirent *dir_file; dir = opendir(dir_name.c_str()); //open the directory for listing if(!dir) { std::cerr << "UTILS ERROR: Failed to list directory: " << dir_name << std::endl; return directoryList; } //List each file found in the directory as long as it end with .lua while((dir_file = readdir(dir))) { std::string fileName = dir_file->d_name; //contains a .lua ending so put it in the directory if(filter == "") directoryList.push_back(dir_file->d_name); else if(fileName.find(filter) != std::string::npos) directoryList.push_back(dir_file->d_name); } closedir(dir); #endif return directoryList; }
// Open a file result_t CFile::Open(const CAnyString& pszFileName, uint32_t flags) { Close(); // If create or open mode specified, select depending on file existance if ((flags & ffCreate) && (flags & ffOpen)) { if (DoesFileExist(pszFileName)) flags &= ~ffCreate; else flags &= ~ffOpen; } // Work out fopen flags const wchar_t* pszFlags=NULL; switch (flags & 0x000F) { case ffWrite|ffCreate: pszFlags=L"wb"; break; case ffRead|ffOpen: pszFlags=L"rb"; break; case ffRead|ffWrite|ffCreate: pszFlags=L"wb+"; break; case ffRead|ffWrite|ffOpen: pszFlags=L"rb+"; break; default: return e_invalidarg; } #ifdef _MSC_VER // Work out sharing flags int shareflag=_SH_DENYRW; switch (flags & (ffShareRead|ffShareWrite)) { case ffShareRead|ffShareWrite: shareflag=_SH_DENYNO; break; case ffShareRead: shareflag=_SH_DENYWR; break; case ffShareWrite: shareflag=_SH_DENYRD; break; } // Open file m_pFile=_wfsopen(pszFileName, pszFlags, shareflag); if (!m_pFile) return ResultFromErrno(errno); #else m_pFile=fopen64(pszFileName, w2a(pszFlags)); if (!m_pFile) return ResultFromErrno(errno); #endif // Append? if ((flags & ffAppend) && (flags & ffOpen)) { fseek(m_pFile, 0, SEEK_END); } // Done return s_ok; }
void Map_Snapshot(){ CString strMsg; // I hope the modified flag is kept correctly up to date if ( !modified ) { return; } // we need to do the following // 1. make sure the snapshot directory exists (create it if it doesn't) // 2. find out what the lastest save is based on number // 3. inc that and save the map CString strOrgPath, strOrgFile; ExtractPath_and_Filename( currentmap, strOrgPath, strOrgFile ); AddSlash( strOrgPath ); strOrgPath += "snapshots"; bool bGo = true; struct stat Stat; if ( stat( strOrgPath, &Stat ) == -1 ) { #ifdef _WIN32 bGo = ( _mkdir( strOrgPath ) != -1 ); #endif #if defined ( __linux__ ) || defined ( __APPLE__ ) bGo = ( mkdir( strOrgPath,0755 ) != -1 ); #endif } AddSlash( strOrgPath ); if ( bGo ) { int nCount = 0; long lSize = 0; CString strNewPath; strNewPath = strOrgPath; strNewPath += strOrgFile; // QB - snapshots now follow the format: <mapname>.<snapnum>.<ext> // **NOTE** atm snapshots must end with a .map (or .xmap) ext (this is why they were broken) CString strOldEXT = "map"; //default to .map const char* type = strrchr( strOrgFile.GetBuffer(),'.' ); if ( type != NULL ) { strOldEXT = ++type; }; // get the ext for later. StripExtension(strNewPath); // then strip it from the new path // CString strFile; while ( bGo ) { char buf[PATH_MAX]; //sprintf( buf, "%s.%i", strNewPath.GetBuffer(), nCount ); // snapshot will now end with a known ext. sprintf( buf, "%s.%i.%s", strNewPath.GetBuffer(), nCount, strOldEXT.GetBuffer() ); strFile = buf; bGo = DoesFileExist( strFile, lSize ); nCount++; } // strFile has the next available slot Map_SaveFile( strFile, false ); // it is still a modified map (we enter this only if this is a modified map) Sys_SetTitle( currentmap ); Sys_MarkMapModified(); if ( lSize > 12 * 1024 * 1024 ) { // total size of saves > 4 mb Sys_Printf( "The snapshot files in %s total more than 4 megabytes. You might consider cleaning up.", strOrgPath.GetBuffer() ); } } else { strMsg.Format( "Snapshot save failed.. unabled to create directory\n%s", strOrgPath.GetBuffer() ); gtk_MessageBox( g_pParentWnd->m_pWidget, strMsg ); } strOrgPath = ""; strOrgFile = ""; }
//! \brief Finds the OS specific directory path to save and retrieve user data static const std::string _SetupUserDataPath() { #if defined _WIN32 char path[MAX_PATH]; // %APPDATA% (%USERPROFILE%\Application Data) if(SUCCEEDED(SHGetFolderPathA(nullptr, CSIDL_APPDATA, nullptr, 0, path))) { std::string user_path = std::string(path) + "/" APPUPCASEDIRNAME "/"; if(!DoesFileExist(user_path)) MakeDirectory(user_path); _CopyOldSaveFiles(user_path); return user_path; } #elif defined __APPLE__ passwd *pw = getpwuid(getuid()); if(pw) { std::string path = std::string(pw->pw_dir) + "/Library/Application Support/" APPUPCASEDIRNAME "/"; if(!DoesFileExist(path)) MakeDirectory(path); return path; } #else // Linux, BSD, other POSIX systems // Implementation of the freedesktop specs (at least partially) // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html // $XDG_DATA_HOME/valyriatear/ // equals to: ~/.local/share/valyriatear/ most of the time if (getenv("XDG_DATA_HOME")) { std::string path = std::string(getenv("XDG_DATA_HOME")) + "/" APPSHORTNAME "/"; if(!DoesFileExist(path)) MakeDirectory(path); _CopyOldSaveFiles(path); return path; } // We create a sane default: ~/.local/share/valyriatear passwd *pw = getpwuid(getuid()); if(pw) { std::string path = std::string(pw->pw_dir) + "/.local/"; if(!DoesFileExist(path)) MakeDirectory(path); path += "/share/"; if(!DoesFileExist(path)) MakeDirectory(path); path += "/" APPSHORTNAME "/"; if(!DoesFileExist(path)) MakeDirectory(path); _CopyOldSaveFiles(path); return path; } #endif // Default path if a specific solution could not be found. Note that this path may // not be writable by the user since it could be installed in administrator/root space PRINT_WARNING << "could not idenfity user path, defaulting to system path" << std::endl; return "data/"; }
void JukeBox::LoadXML(const std::string& profile) { if (!m_init) // the sound device has not be initialized (was busy?) return; // is xml_file already loaded ? std::set<std::string>::iterator it_profile = m_profiles_loaded.find(profile); if (it_profile != m_profiles_loaded.end()) { MSG_DEBUG("jukebox", "Profile %s is already loaded !", profile.c_str()); return; } std::cout << Format(_("o Loading sound profile: %s"), profile.c_str()) << std::endl; XmlReader doc; // Load the XML std::string folder = Config::GetInstance()->GetDataDir() + "sound" PATH_SEPARATOR + profile + PATH_SEPARATOR; std::string xml_filename = folder + "profile.xml"; if (!DoesFileExist(xml_filename)) { std::cerr << "[Sound] Error : file " << xml_filename << " not found" << std::endl; return; } if (!doc.Load(xml_filename)) return; xmlNodeArray nodes = XmlReader::GetNamedChildren(doc.GetRoot(), "sound"); xmlNodeArray::const_iterator it = nodes.begin(), end = nodes.end(); for (; it != end; ++it) { // reads XML std::string sample = "no_sample"; std::string file = "no_file"; float level = 1.0f; XmlReader::ReadStringAttr(*it, "sample", sample); XmlReader::ReadStringAttr(*it, "file", file); XmlReader::ReadfloatAttr(*it, "level", level); MSG_DEBUG("jukebox", "Load sound sample %s/%s: %s (%.3f)", profile.c_str(), sample.c_str(), file.c_str(), level); // Load sound std::string sample_filename = folder + file; if (!DoesFileExist(sample_filename)) { std::cerr << "Sound warning: File " << sample_filename.c_str() << " does not exist! (probably not yet recorded)" << std::endl; continue; } // Inserting sound sample in list sample_info inf = { sample_filename, level }; m_soundsamples.insert(sound_sample(profile+"/"+sample, inf)); // Precache m_cache.Precache(sample_filename.c_str()); } // The profile is loaded m_profiles_loaded.insert(profile); }
bool MoveFile(const std::string &source_name, const std::string &destination_name) { if(DoesFileExist(destination_name)) remove(destination_name.c_str()); return (rename(source_name.c_str(), destination_name.c_str()) == 0); }
void Alsa9Buf::GetSoundCardDebugInfo() { static bool done = false; if( done ) return; done = true; if( DoesFileExist("/rootfs/proc/asound/version") ) { RString sVersion; GetFileContents( "/rootfs/proc/asound/version", sVersion, true ); LOG->Info( "ALSA: %s", sVersion.c_str() ); } InitializeErrorHandler(); int card = -1; while( dsnd_card_next( &card ) >= 0 && card >= 0 ) { const RString id = ssprintf( "hw:%d", card ); snd_ctl_t *handle; int err; err = dsnd_ctl_open( &handle, id, 0 ); if ( err < 0 ) { LOG->Info( "Couldn't open card #%i (\"%s\") to probe: %s", card, id.c_str(), dsnd_strerror(err) ); continue; } snd_ctl_card_info_t *info; dsnd_ctl_card_info_alloca(&info); err = dsnd_ctl_card_info( handle, info ); if ( err < 0 ) { LOG->Info( "Couldn't get card info for card #%i (\"%s\"): %s", card, id.c_str(), dsnd_strerror(err) ); dsnd_ctl_close( handle ); continue; } int dev = -1; while ( dsnd_ctl_pcm_next_device( handle, &dev ) >= 0 && dev >= 0 ) { snd_pcm_info_t *pcminfo; dsnd_pcm_info_alloca(&pcminfo); dsnd_pcm_info_set_device(pcminfo, dev); dsnd_pcm_info_set_stream(pcminfo, SND_PCM_STREAM_PLAYBACK); err = dsnd_ctl_pcm_info(handle, pcminfo); if ( err < 0 ) { if (err != -ENOENT) LOG->Info("dsnd_ctl_pcm_info(%i) (%s) failed: %s", card, id.c_str(), dsnd_strerror(err)); continue; } LOG->Info( "ALSA Driver: %i: %s [%s], device %i: %s [%s], %i/%i subdevices avail", card, dsnd_ctl_card_info_get_name(info), dsnd_ctl_card_info_get_id(info), dev, dsnd_pcm_info_get_id(pcminfo), dsnd_pcm_info_get_name(pcminfo), dsnd_pcm_info_get_subdevices_avail(pcminfo), dsnd_pcm_info_get_subdevices_count(pcminfo) ); } dsnd_ctl_close(handle); } if( card == 0 ) LOG->Info( "No ALSA sound cards were found."); if( !PREFSMAN->m_iSoundDevice.Get().empty() ) LOG->Info( "ALSA device overridden to \"%s\"", PREFSMAN->m_iSoundDevice.Get().c_str() ); }
void CWorldsDlg::OnWorldDecompress() { //first off, we need to get the filename of the selected item CString sInFileName = GetSelectedItemFileName(); int nDotPos = sInFileName.ReverseFind('.'); if(nDotPos == -1) return; CString sExt = sInFileName.Mid(nDotPos + 1); if(sExt.CompareNoCase("ltc") != 0) return; //make sure it is compressed if(CLTAUtil::IsFileCompressed(sInFileName) == false) { //this shouldn't ever happen. The wrong menu item managed to come up ASSERT(false); return; } //make sure that the region we are compressing is not open for editing for(uint32 nCurrRegion = 0; nCurrRegion < GetProjectBar()->m_RegionDocs.GetSize(); nCurrRegion++) { if(sInFileName.CompareNoCase(GetProjectBar()->m_RegionDocs[nCurrRegion]->m_FileName) == 0) { //they are trying to compress a file that is open, we can't allow this, otherwise //when they save, it will save to the wrong filename. Another approach //would be to update the region's filename, but I don't think I'll have enough //time to thoroughly test this to my satisfaction, so I'll go with the error MessageBox( sInFileName + " is currently open for editing.\nYou must close this file before you decompress it", "Cannot Decompress Open File", MB_ICONEXCLAMATION | MB_OK); return; } } CString sOutFileName = ConvertExtension(sInFileName, ".ltc", ".lta"); //see if the file already exists if(DoesFileExist(sOutFileName) == TRUE) { //prompt the user with an overwrite prompt if(MessageBox("The file " + sOutFileName + " already exists.\nWould you like to overwrite this file?", "File already exists", MB_ICONQUESTION | MB_YESNO) == IDNO) { //the user didn't want to overwrite the file return; } } //now we open up the input file, and compress it BeginWaitCursor(); CLTAFile InFile(sInFileName, true, true); //make sure the files opened okay if(InFile.IsValid() == false) { MessageBox( "Unable to open " + sInFileName + " for reading\nDecompression not performed", "Error", MB_ICONEXCLAMATION | MB_OK); return; } CLTAFile OutFile(sOutFileName, false, false); //make sure the files opened okay if(OutFile.IsValid() == false) { MessageBox( "Unable to open " + sOutFileName + " for writing\nDecompression not performed", "Error", MB_ICONEXCLAMATION | MB_OK); return; } //now we just decompress uint8 nByte; while(InFile.ReadByte(nByte)) { if(OutFile.WriteByte(nByte) == false) { MessageBox( "Error while saving to " + sOutFileName + "\nDecompression not performed", "Error", MB_ICONEXCLAMATION | MB_OK); return; } } //close out the files InFile.Close(); OutFile.Close(); //now we need to delete the input file // Delete the world if (!DeleteFile(sInFileName)) { MessageBox("Error deleting world" + sInFileName, "Error", MB_OK | MB_ICONEXCLAMATION); return; } // Refresh the display list PopulateList(); EndWaitCursor(); }
// NOTE: This function can return NULL if the actor should not be displayed. // Callers should be aware of this and handle it appropriately. Actor* ActorUtil::MakeActor( const RString &sPath_, Actor *pParentActor ) { RString sPath( sPath_ ); FileType ft = GetFileType( sPath ); switch( ft ) { case FT_Lua: { auto_ptr<XNode> pNode( LoadXNodeFromLuaShowErrors(sPath) ); if( pNode.get() == NULL ) { // XNode will warn about the error return new Actor; } Actor *pRet = ActorUtil::LoadFromNode( pNode.get(), pParentActor ); return pRet; } case FT_Xml: { // Legacy actors; only supported in quirks mode if ( !PREFSMAN->m_bQuirksMode ) return new Actor; XNode xml; if ( !XmlFileUtil::LoadFromFileShowErrors(xml, sPath) ) return new Actor; XmlFileUtil::CompileXNodeTree( &xml, sPath ); XmlFileUtil::AnnotateXNodeTree( &xml, sPath ); return LoadFromNode( &xml, pParentActor ); } case FT_Directory: { if( sPath.Right(1) != "/" ) sPath += '/'; RString sXml = sPath + "default.xml"; if (DoesFileExist(sXml)) return MakeActor(sXml, pParentActor); XNode xml; xml.AppendAttr( "Class", "BGAnimation" ); xml.AppendAttr( "AniDir", sPath ); return ActorUtil::LoadFromNode( &xml, pParentActor ); } case FT_Bitmap: case FT_Movie: { XNode xml; xml.AppendAttr( "Class", "Sprite" ); xml.AppendAttr( "Texture", sPath ); return ActorUtil::LoadFromNode( &xml, pParentActor ); } case FT_Sprite: { // Legacy actor; only supported in quirks mode if( !PREFSMAN->m_bQuirksMode ) return new Actor; IniFile ini; ini.ReadFile( sPath ); XmlFileUtil::AnnotateXNodeTree( &ini, sPath ); return ActorUtil::LoadFromNode( ini.GetChild("Sprite"), pParentActor ); } case FT_Model: { XNode xml; xml.AppendAttr( "Class", "Model" ); xml.AppendAttr( "Meshes", sPath ); xml.AppendAttr( "Materials", sPath ); xml.AppendAttr( "Bones", sPath ); return ActorUtil::LoadFromNode( &xml, pParentActor ); } default: { LOG->Warn( "File \"%s\" has unknown type, \"%s\".", sPath.c_str(), FileTypeToString(ft).c_str() ); XNode xml; xml.AppendAttr( "Class", "Actor" ); return ActorUtil::LoadFromNode( &xml, pParentActor ); } } }