char* LoadTextFileAsBuffer(const char* fileName) { char* returnedBuffer = NULL; IFile* fileHandle = behaviac::CFileManager::GetInstance()->FileOpen(fileName, CFileSystem::EOpenAccess_Read); if (fileHandle) { uint32_t fileSize = (uint32_t)fileHandle->GetSize(); char* fileBuffer = (char*)BEHAVIAC_MALLOC_WITHTAG(fileSize + 1, "TextFileBuffer"); if (fileHandle->Read(fileBuffer, fileSize) == fileSize) { fileBuffer[fileSize] = '\0'; returnedBuffer = fileBuffer; } else { BEHAVIAC_ASSERT(0, "Fail to read the text file : %s\n", fileName); } behaviac::CFileManager::GetInstance()->FileClose(fileHandle); } else { BEHAVIAC_ASSERT(0, "Fail to open the text file : %s\n", fileName); } return returnedBuffer; }
int main(int argc, char** argv) { _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); IFile::OpenMode mode = IFile::O_ReadOnly; assert(argc>1); IFile *pFile = OpenDiskFile(argv[1], mode); BlockManager* pMgr = new BlockManager(pFile, mode==IFile::O_Truncate, offset_type(1024)); BlockFS *pFS = new BlockFS(pMgr, mode); std::vector<std::string> names; pFS->ExportFileNames(names); for (std::vector<std::string>::iterator it = names.begin(); it != names.end(); ++it) { IFile* pUnpackedFile = pFS->OpenFileInPackage(it->c_str()); IFile* pTemp = OpenDiskFile(it->c_str(), IFile::O_Truncate); offset_type length = pUnpackedFile->GetSize(); char* buff = new char[(size_t)length.offset]; printf("Unpacking %s\n", it->c_str()); pUnpackedFile->Read(buff, length); pTemp->Write(buff, length); delete []buff; delete pTemp; delete pUnpackedFile; } delete pFS; delete pMgr; delete pFile; }
const char* Reader( lua_State* state, void* data, size_t* size ) { IFile* file = reinterpret_cast< IFile* >( data ); *size = file->Read( reinterpret_cast<boost::int8_t*>( dataBuffer ), kBufferSize ); return dataBuffer; }
void KG3DFontTexture::LoadAlphaAdjustTable(LPCSTR szFontName, INT nFontSize) { BOOL bAdjust = FALSE; char szFileName[MAX_PATH]; LPSTR szSep = NULL; int nLen = _countof(szFileName) - 16; strncpy(szFileName, szFontName, nLen); szFileName[nLen - 1] = '\0'; szSep = strrchr(szFileName, '.'); if (szSep) { sprintf(szSep, "%d.prf", nFontSize); if (g_IsFileExist(szFileName)) { IFile* pFile = g_OpenFile(szFileName); if (pFile) { unsigned int nCount = pFile->Read(m_uchAdjustBuffer, sizeof(m_uchAdjustBuffer)); if (nCount == sizeof(m_uchAdjustBuffer)) bAdjust = TRUE; KG_COM_RELEASE(pFile); } } } if (!bAdjust) { for (size_t nIndex = 0; nIndex < _countof(m_uchAdjustBuffer); ++nIndex) { m_uchAdjustBuffer[nIndex] = (UCHAR)nIndex; } } }
bool KLuaWrap::DoScriptFile(const char *ScriptFile, const char *EnvName /*= NULL*/) { bool ret = false; assert(m_L); if (!(ScriptFile && ScriptFile[0])) return false; IFile* pFile = NULL; char* pBuffer = NULL; unsigned int size; if ((pFile = g_OpenFile(ScriptFile)) == NULL) { printf("%s is not exist!\n", ScriptFile); KGLogPrintf(KGLOG_WARNING, "[Lua] %s is not exist!\n", ScriptFile); return false; } size = pFile->Size(); pBuffer = (char*)malloc(size + 1024); if (pBuffer) { char tmp[128]; int pos = 0; int tmpLen = sprintf(tmp, "package.path = \"%s?.lua\"", m_ScriptPackagePath); #ifdef WIN32 for (int i = 0; i < tmpLen; ++i) { pBuffer[pos++] = tmp[i]; if (tmp[i] == '\\') { pBuffer[pos++] = '\\'; } } #endif if (EnvName && EnvName[0]) pos += sprintf(pBuffer + pos, "%s={} setmetatable(%s,{__index=_G,__newindex=function(t,i,v)for _,r in pairs(_RESERVE_G_VAR_)do if i==r then _G[i] = v return end end rawset(t,i,v)end}) setfenv(1,%s)", EnvName, EnvName, EnvName); if (pFile->Read(pBuffer + pos, size) == size) { ret = lua_tinker::dobuffer(m_L, pBuffer, size + pos, ScriptFile); if (ret && EnvName && EnvName[0]) { lua_getglobal(m_L, EnvName); lua_pushstring(m_L, "CURRENT_SCRIPT_FILE"); lua_pushstring(m_L, ScriptFile); lua_settable(m_L, -3); lua_pop(m_L, 1); } } free(pBuffer); pBuffer = NULL; } pFile->Release(); pFile = NULL; return ret; }
char* Workspace::ReadFileToBuffer(const char* file, uint32_t& bufferSize) { IFile* fp = behaviac::CFileManager::GetInstance()->FileOpen(file, CFileSystem::EOpenAccess_Read); if (!fp) { return 0; } //fp->Seek(0, CFileSystem::ESeekMoveMode_End); uint32_t fileSize = (uint32_t)fp->GetSize(); bufferSize = fileSize + 1; char* pBuffer = 0; for (int i = 0; i < kFileBuffers; ++i) { FileBuffer_t& fileBuffer = this->m_fileBuffers[i]; BEHAVIAC_ASSERT(fileBuffer.offset == 0 || fileBuffer.offset < fileBuffer.length); if (fileBuffer.start == 0) { //to allocate extra 10k int fileBufferLength = bufferSize + 10 * 1024; const int kBufferLength = 100 * 1024; if (fileBufferLength < kBufferLength) { fileBufferLength = kBufferLength; } fileBuffer.start = (char*)BEHAVIAC_MALLOC(fileBufferLength); fileBuffer.length = fileBufferLength; BEHAVIAC_ASSERT(fileBuffer.offset == 0); pBuffer = fileBuffer.start; fileBuffer.offset += bufferSize; BEHAVIAC_ASSERT(fileBuffer.offset < fileBuffer.length); break; } else if (bufferSize < fileBuffer.length - fileBuffer.offset) { pBuffer = fileBuffer.start + fileBuffer.offset; fileBuffer.offset += bufferSize; BEHAVIAC_ASSERT(fileBuffer.offset < fileBuffer.length); break; } } BEHAVIAC_ASSERT(pBuffer); fp->Read(pBuffer, sizeof(char) * fileSize); pBuffer[fileSize] = 0; behaviac::CFileManager::GetInstance()->FileClose(fp); return pBuffer; }
int main(int argc, char* argv[]) { _CrtSetDbgFlag ( _CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF ); if(argc < 3) { printf("usage: %s directory package", argv[0]); return 0; } IFile::OpenMode mode = IFile::O_Write; if(!PathFileExistsA(argv[1])) mode = IFile::O_Truncate; IFile *pFile = OpenDiskFile(argv[1], mode); BlockManager* pMgr = new BlockManager(pFile, mode==IFile::O_Truncate, offset_type(1024)); BlockFS *pFS = new BlockFS(pMgr, mode); std::vector<BlockFileEntry> vecEntries = pFS->GetEntries(); std::map<std::string, MD5Index> mapEntries; for(std::vector<BlockFileEntry>::iterator it = vecEntries.begin(); it != vecEntries.end(); ++it) { if(std::string("")!=it->name) { assert(mapEntries.find(it->name)==mapEntries.end()); mapEntries[it->name] = it->index; } } std::vector<std::string> add; ScanFileRecursively(argv[2], pFS, mapEntries, add); for(std::map<std::string, MD5Index>::iterator it = mapEntries.begin(); it != mapEntries.end(); ++it) pFS->RemoveFile(it->first.c_str()); for(std::vector<std::string>::iterator it = add.begin(); it != add.end(); ++it) { IFile* pTemp = OpenDiskFile(it->c_str(), IFile::O_ReadOnly); offset_type length = pTemp->GetSize(); char* buff = new char[(size_t)length.offset]; pTemp->Read(buff, length); printf("adding %s, %d bytes\n", it->c_str(), length); pFS->AddFile(it->c_str(), buff, length, length > pFS->GetBlockDataSize()); delete[]buff; delete pTemp; } delete pFS; delete pMgr; delete pFile; return 0; }
char* Workspace::ReadFileToBuffer(const char* file) { IFile* fp = behaviac::CFileManager::GetInstance()->FileOpen(file, CFileSystem::EOpenAccess_Read); if (!fp) { return 0; } //fp->Seek(0, CFileSystem::ESeekMoveMode_End); uint32_t fileSize = (uint32_t)fp->GetSize(); BEHAVIAC_ASSERT(m_fileBufferTop < kFileBufferDepth - 1, "please increase kFileBufferDepth"); uint32_t offset = m_fileBufferOffset[m_fileBufferTop++]; uint32_t offsetNew = offset + fileSize + 1; BEHAVIAC_ASSERT(m_fileBufferTop < kFileBufferDepth - 1, "please increase kFileBufferDepth"); m_fileBufferOffset[m_fileBufferTop] = offsetNew; if (m_fileBuffer == 0 || offsetNew > m_fileBufferLength) { //to allocate extra 10k m_fileBufferLength = offsetNew + 10 * 1024; if (m_fileBufferLength < 50 * 1024) { m_fileBufferLength = 50 * 1024; } m_fileBuffer = (char*)BEHAVIAC_REALLOC(m_fileBuffer, m_fileBufferLength); } BEHAVIAC_ASSERT(m_fileBuffer); BEHAVIAC_ASSERT(offsetNew < m_fileBufferLength); char* pBuffer = m_fileBuffer + offset; fp->Read(pBuffer, sizeof(char) * fileSize); pBuffer[fileSize] = 0; behaviac::CFileManager::GetInstance()->FileClose(fp); return pBuffer; }
// Read from the File. VFS_BOOL VFS_File_Read( VFS_Handle hFile, VFS_BYTE* pBuffer, VFS_DWORD dwToRead, VFS_DWORD* pRead ) { // Not initialized yet? if( !IsInit() ) { SetLastError( VFS_ERROR_NOT_INITIALIZED_YET ); return VFS_FALSE; } // Invalid Handle Value? if( hFile == VFS_INVALID_HANDLE_VALUE ) { SetLastError( VFS_ERROR_INVALID_PARAMETER ); return VFS_FALSE; } // Get the File Pointer. IFile* pFile = ( IFile* )( VFS_DWORD )hFile; return pFile->Read( pBuffer, dwToRead, pRead ); }
HRESULT KTgaButton::LoadTgaFile(const char* strFileName,BOOL bAddToTerrian) { if (!strFileName) return E_FAIL; bool isload = false; std::string dir = strFileName; std::list<std::string>::iterator its,listend; std::string *psting = NULL; //FILE* fpFile = fopen(strFileName, "rb"); IFile* fpFile = g_OpenFile(strFileName); if (!fpFile)//打开默认的贴图文件 { TCHAR NameDefault[MAX_PATH]; wsprintf(NameDefault,"%s\\Data\\Editor\\Texture\\replace.tga",g_szDefWorkDirectory); fpFile = g_OpenFile(NameDefault);//fpFile = fopen(NameDefault, "rb");// if(!fpFile) return E_FAIL; } fpFile->Read(&m_TgaInfo.Header, sizeof(TGAHeader));//fread(&m_TgaInfo.Header, sizeof(TGAHeader), 1, fpFile);// const int byteperpixel = m_TgaInfo.Header.bitsperpixel / 8; if(byteperpixel != 4) { MessageBox("Tga格式不正确,必须为32位"); SAFE_RELEASE(fpFile);//fclose(fpFile);// return E_FAIL; } m_TextureDir = dir; //TCHAR drive[256]; //TCHAR dirc[256]; //TCHAR fname[256]; //TCHAR ext[256]; std::string filename; if(m_pTerrainEx && m_nButtonType == GROUNDTEXTURE) { int nCoord =0; if(SUCCEEDED(m_pTerrainEx->GetGroundTextureCoordIndex(m_nLayer,m_nTextureIndex,&nCoord))) { SetTexCoordIndex(nCoord); } } size_t Size = m_TgaInfo.Header.height * m_TgaInfo.Header.width * byteperpixel; SAFE_DELETE_ARRAY(m_TgaInfo.pBuffer); m_TgaInfo.pBuffer = new BYTE[Size]; fpFile->Seek(m_TgaInfo.Header.Id + sizeof(TGAHeader), SEEK_SET);//fseek(fpFile, m_TgaInfo.Header.Id + sizeof(TGAHeader), SEEK_SET);// fpFile->Read(m_TgaInfo.pBuffer, (unsigned long)Size);//fread(m_TgaInfo.pBuffer, Size, 1, fpFile);// RECT rect; GetClientRect(&rect); int height = abs(rect.bottom - rect.top); int width = abs(rect.left - rect.right); BYTE *NewData = SacleData(rect,m_TgaInfo.pBuffer,byteperpixel); CDC* pDc = this->GetDC(); m_Bitmap.CreateCompatibleBitmap(pDc, width, height); m_Bitmap.SetBitmapBits(width * height * byteperpixel,NewData); SetBitmap(m_Bitmap); ReleaseDC(pDc); SAFE_DELETE_ARRAY(NewData); //fclose(fpFile); SAFE_RELEASE(fpFile); m_bIsHaveTexture = true; return S_OK; }
int KGTestMapDisuseResource::FindResInSFX(const char cszResourceName[], set<string>& setResList) { //参照KG3DSFX::_LoadFromFile int nResult = false; HRESULT hRetCode = E_FAIL; DWORD dwSize = 0; SFX_FILE_HEADER* pHeader = NULL; DWORD fileLen = 0; BYTE* pBuffer = NULL; DWORD dwCurPos = 0; DWORD i = 0; IFile* pFile = NULL; KG_ASSERT_EXIT(cszResourceName); KGLOG_PROCESS_ERROR(cszResourceName[0] != '\0'); pFile = g_OpenFile(cszResourceName); KG_PROCESS_ERROR(pFile); fileLen = pFile->Size(); ASSERT(fileLen > 0); KG_PROCESS_ERROR(fileLen); pBuffer = new BYTE[fileLen]; KG_PROCESS_ERROR(pBuffer); dwSize = pFile->Read(pBuffer, fileLen); KG_PROCESS_ERROR(dwSize == fileLen); pHeader = reinterpret_cast<SFX_FILE_HEADER*>(pBuffer); KG_PROCESS_ERROR(pHeader->dwID == SFX_ID); KG_PROCESS_ERROR(pHeader->dwFileLength == fileLen); KG_PROCESS_ERROR(LOWORD(pHeader->dwVersion) >= 2); dwCurPos += sizeof(SFX_FILE_HEADER); for (i = 0; i < pHeader->dwElementNum; ++i, dwCurPos += sizeof(SFX_ELEMENT)) { SFX_ELEMENT *pElem = reinterpret_cast<SFX_ELEMENT*>(&pBuffer[dwCurPos]); ASSERT(dwCurPos < fileLen); KG_PROCESS_ERROR( (pElem->dwElementID >= SFX_FEID_GENERAL_INFORMATION) && (pElem->dwElementID < SFX_FEID_SIZE) ); ASSERT(pElem->dwElementOffset <= fileLen); /* pElem->dwElementID对应于 KG3DSFX::ProcessBlockFunction KG3DSFX::ms_pfnProcessBlock[SFX_FEID_SIZE] 中的ReadModelBlock函数指针的索引7,此函数读取mesh,mtl,ani的信息 */ if (pElem->dwElementID == 7) { //参照KG3DSFX::ReadModelBlock SFX_MODEL_BLOCK* pBlock = (SFX_MODEL_BLOCK*)&pBuffer[pElem->dwElementOffset]; FindResource((const char*)pBlock->byMeshFileName, setResList); FindResource((const char*)pBlock->byMaterialFileName, setResList); FindResource((const char*)pBlock->byAnimationFileName, setResList); } } nResult = true; Exit0: return nResult; }
int KGTestMapDisuseResource::FindResInPVS(const char cszResourceName[], set<string>& setResList) { //参照KG3DRepresentObjectPVS::LoadPvsFile int nRetCode = false; int nResult = false; HRESULT hrRetCode = E_FAIL; IFile* pFile = NULL; DWORD dwVersion = PVS_FILE_VERSION; char szSourcePathName[MAX_PATH] = {0}; char szResName[MAX_PATH] = {0}; long lOffset = 0; size_t objNum = 0; KG_ASSERT_EXIT(cszResourceName); KGLOG_PROCESS_ERROR(cszResourceName[0] != '\0'); nRetCode = _snprintf_s(szSourcePathName, sizeof(szSourcePathName), sizeof(szSourcePathName) - 1, "%s%s", m_szClientPath, cszResourceName); KGLOG_PROCESS_ERROR(nRetCode > 0); pFile = g_OpenFile(cszResourceName, false, false); KGLOG_PROCESS_ERROR(pFile); /* read version */ pFile->Read(&dwVersion, sizeof(dwVersion)); /* load border, the frist model of the pvs object is it's ouside border and the second model is it's inside border */ pFile->Read(szResName, sizeof(szResName)); FindResource(szResName, setResList); pFile->Read(szResName, sizeof(szResName)); FindResource(szResName, setResList); /* load inside objects, the object may be is pvs object too */ pFile->Read(&objNum, sizeof(objNum)); for (size_t i = 0; i < objNum; i++) { DWORD dwObjType = 0; pFile->Read(&dwObjType, sizeof(dwObjType)); switch (dwObjType) { case REPRESENTOBJECT_PVS : case REPRESENTOBJECT_SET : { pFile->Read(szResName, sizeof(szResName)); FindResource(szResName, setResList); } break; case REPRESENTOBJECT_DEFAULT : { /* is normal object */ DWORD dwCount = 0; DWORD dwColor = 0; DWORD dwType = 0; char szAnins[MAX_PATH] = {0}; pFile->Read(&dwCount, sizeof(dwCount)); for (DWORD i = 0; i < dwCount; i++) { pFile->Read(szResName, sizeof(szResName)); FindResource(szResName, setResList); if (dwVersion > PVS_FILE_VERSION_1) { pFile->Read(szAnins, sizeof(szAnins)); FindResource(szAnins, setResList); } TypeInfo* pInfo = NULL; IEKG3DEngineManager* pIEEngineMgr = NULL; IEKG3DModelTable* pIEModelTable = NULL; KG3DModelTable* pModelTable = NULL; pIEEngineMgr = (IEKG3DEngineManager*)m_pEngineMgr; hrRetCode = pIEEngineMgr->GetIEKG3DModelTable(&pIEModelTable); KGLOG_COM_PROCESS_ERROR(hrRetCode); pModelTable= (KG3DModelTable*)pIEModelTable; hrRetCode = pModelTable->GetTypeInfoByFileName(&pInfo, szResName); if (pInfo) dwType = pInfo->dwType; else dwType = MESHTYPE_DEFAULT; switch (dwType) { case MESHTYPE_POINTLIGHT : { pFile->Read(&dwColor, sizeof(dwColor)); } break; default : break; } } } break; default : _ASSERTE(false); break; } lOffset = sizeof(D3DXVECTOR3) + //ScalingCenter sizeof(D3DXQUATERNION) + //ScalingRotation sizeof(D3DXVECTOR3) + //Scaling sizeof(D3DXVECTOR3) + //RotationCenter sizeof(D3DXQUATERNION) + //Rotation sizeof(D3DXVECTOR3) + //Translation sizeof(AABBOX); //aabox pFile->Seek(lOffset, SEEK_CUR); lOffset = 0; } pFile->Close(); SAFE_RELEASE(pFile); nResult = true; Exit0: if (pFile) { pFile->Close(); SAFE_RELEASE(pFile); } return nResult; }
int KGTestMapDisuseResource::FindResInSTree(const char cszResourceName[], set<string>& setResList) { //参照KG3DModelSpeedTree::_LoadFromFile int nRetCode = false; int nResult = false; IFile* pFile = NULL; DWORD dwMark = 0; char szSourcePathName[MAX_PATH] = {0}; char szTreeMeshName[MAX_PATH] = {0}; char szTreeMtlName [MAX_PATH] = {0}; char szPathName[MAX_PATH] = {0}; char szDriver[MAX_PATH] = {0}; char szPath[MAX_PATH] = {0}; char szFileName[MAX_PATH] = {0}; char szExt[MAX_PATH] = {0}; KG_ASSERT_EXIT(cszResourceName); KGLOG_PROCESS_ERROR(cszResourceName[0] != '\0'); nRetCode = _snprintf_s(szSourcePathName, sizeof(szSourcePathName), sizeof(szSourcePathName) - 1, "%s%s", m_szClientPath, cszResourceName); KGLOG_PROCESS_ERROR(nRetCode > 0); pFile = g_OpenFile(szSourcePathName); KGLOG_PROCESS_ERROR(pFile); pFile->Read(&dwMark, sizeof(DWORD)); //Mesh Name pFile->Read(szTreeMeshName, sizeof(char) * MAX_PATH); nRetCode = _splitpath_s( cszResourceName, szDriver, sizeof(szDriver), szPath, sizeof(szPath), NULL, 0, NULL, 0 ); KGLOG_PROCESS_ERROR(nRetCode == 0); nRetCode = _splitpath_s( szTreeMeshName, NULL, 0, NULL, 0, szFileName, sizeof(szFileName), szExt, sizeof(szExt) ); KGLOG_PROCESS_ERROR(nRetCode == 0); nRetCode = _snprintf_s( szPathName, sizeof(szPathName), sizeof(szPathName) - 1, "%s%s", szDriver, szPath ); KGLOG_PROCESS_ERROR(nRetCode > 0); nRetCode = _snprintf_s( szTreeMeshName, sizeof(szTreeMeshName), sizeof(szTreeMeshName) - 1, "%s%s%s", szPathName, szFileName, szExt ); KGLOG_PROCESS_ERROR(nRetCode > 0); FindResource(szTreeMeshName, setResList); //Mtl Name pFile->Read(szTreeMtlName, sizeof(char) * MAX_PATH); nRetCode = _splitpath_s( szTreeMtlName, NULL, 0, NULL, 0, szFileName, sizeof(szFileName), szExt, sizeof(szExt) ); KGLOG_PROCESS_ERROR(nRetCode == 0); nRetCode = _snprintf_s( szTreeMtlName, sizeof(szTreeMtlName), sizeof(szTreeMtlName) - 1, "%s%s%s", szPathName, szFileName, szExt ); KGLOG_PROCESS_ERROR(nRetCode > 0); FindResource(szTreeMtlName, setResList); //Mtl Name nRetCode = _splitpath_s( cszResourceName, NULL, 0, NULL, 0, szFileName, sizeof(szFileName), NULL, 0 ); KGLOG_PROCESS_ERROR(nRetCode == 0); nRetCode = _snprintf_s( szTreeMtlName, sizeof(szTreeMtlName), sizeof(szTreeMtlName) - 1, "%s%s.Mtl", szPathName, szFileName ); KGLOG_PROCESS_ERROR(nRetCode > 0); FindResource(szTreeMtlName, setResList); nResult = true; Exit0: if (pFile) { pFile->Close(); SAFE_RELEASE(pFile); } return nResult; }
int KGTestMapDisuseResource::FindResInMDL(const char cszResourceName[], set<string>& setResList) { //参照KG3DModelST::LoadMDLContent int nResult = false; char szFilePath[MAX_PATH] = {0}; IFile* pFile = NULL; unsigned long uSize = 0; unsigned long uFileSize = 0; char* pBuffer = NULL; std::stringstream ss; std::string strBuffer; std::string strFilePath; MDLFileContent Content; KG_ASSERT_EXIT(cszResourceName); KGLOG_PROCESS_ERROR(cszResourceName[0] != '\0'); Content.dwNumModels = 0; pFile = g_OpenFile(cszResourceName); KG_PROCESS_ERROR(pFile); uFileSize = pFile->Size(); pBuffer = (char*)malloc(uFileSize + 1); KG_PROCESS_ERROR(pBuffer); uSize = pFile->Read(pBuffer, uFileSize); KG_PROCESS_ERROR(uSize == uFileSize); pBuffer[uSize] = '\0'; // TODO : text 文件没有使用'\0'作结束,不能作为字符串处理,特别麻烦,建议使用binary ss << pBuffer; std::getline(ss, strBuffer); strBuffer.erase(strBuffer.find_last_not_of("\n\r") + 1); KG_PROCESS_ERROR(!strBuffer.empty()); g_ExtractFilePath(szFilePath, cszResourceName); strFilePath = szFilePath; strFilePath += "\\"; if (strBuffer[0] == '\\') { Content.strBipFile = strBuffer; } else { Content.strBipFile = std::string(strFilePath + strBuffer); } FindResource(Content.strBipFile.c_str(), setResList); while (std::getline(ss, strBuffer)) { strBuffer.erase(strBuffer.find_last_not_of("\n\r") + 1); if (strBuffer.empty()) break; std::stringstream ssLine(strBuffer); std::string strMesh, strMtl; ssLine >> strMesh >> strMtl; if (strMtl.size()) { Content.strMaterialFile[Content.dwNumModels] = strMtl; } FindResource(Content.strMaterialFile[Content.dwNumModels].c_str(), setResList); if (strMesh.size()) { if (strMesh[0] == '\\') { Content.strMeshFile[Content.dwNumModels] = strMesh; } else { Content.strMeshFile[Content.dwNumModels] = strFilePath + strMesh; } FindResource(Content.strMeshFile[Content.dwNumModels].c_str(), setResList); Content.dwNumModels++; } } nResult = true; Exit0: SAFE_FREE(pBuffer); KG_COM_RELEASE(pFile); if (!nResult && cszResourceName) { KGLogPrintf(KGLOG_ERR, "Find Res In MDL %s failed.\n", cszResourceName); } return nResult; }
BOOL KRegion::LoadTerrainData(const char cszFileName[], KObjAlloctor& rObjectAlloctor) { BOOL bResult = false; BOOL bRetCode = false; IFile* piFile = NULL; IKG_Buffer* piBuffer = NULL; BYTE* pbyBuffer = NULL; size_t uFileSize = 0; size_t uReadBytes = 0; size_t uLeftBytes = 0; BYTE* pbyOffset = NULL; KRegionHeader* pFileHeader = NULL; size_t uBaseCellInfoSize = sizeof(KCell::KBaseInfo) + sizeof(WORD); KCell* pAllocCell = NULL; int nExtCellCount = 0; size_t uExtCellInfoSize = sizeof(int) * 2 + sizeof(KCell::KBaseInfo) + sizeof(WORD) * 2; piFile = g_OpenFile(cszFileName); KGLOG_PROCESS_ERROR(piFile); uFileSize = piFile->Size(); KGLOG_PROCESS_ERROR(uFileSize > 0); piBuffer = KG_MemoryCreateBuffer((unsigned)uFileSize); KGLOG_PROCESS_ERROR(piBuffer); pbyBuffer = (BYTE*)piBuffer->GetData(); KGLOG_PROCESS_ERROR(pbyBuffer); uReadBytes = piFile->Read(pbyBuffer, (unsigned long)uFileSize); KGLOG_PROCESS_ERROR(uReadBytes == uFileSize); KG_COM_RELEASE(piFile); pbyOffset = pbyBuffer; uLeftBytes = uReadBytes; KGLOG_PROCESS_ERROR(uLeftBytes >= sizeof(KRegionHeader)); pFileHeader = (KRegionHeader*)pbyOffset; pbyOffset += sizeof(KRegionHeader); uLeftBytes -= sizeof(KRegionHeader); KGLOG_PROCESS_ERROR(pFileHeader->nRegionX == m_nRegionX); KGLOG_PROCESS_ERROR(pFileHeader->nRegionY == m_nRegionY); KGLOG_PROCESS_ERROR(uLeftBytes >= uBaseCellInfoSize * REGION_GRID_WIDTH * REGION_GRID_HEIGHT); uLeftBytes -= uBaseCellInfoSize * REGION_GRID_WIDTH * REGION_GRID_HEIGHT; for (int nCellY = 0; nCellY < REGION_GRID_HEIGHT; nCellY++) { for (int nCellX = 0; nCellX < REGION_GRID_WIDTH; nCellX++) { KCell* pCell = &m_Cells[nCellX][nCellY]; KCell::KBaseInfo* pBaseInfo = (KCell::KBaseInfo*)pbyOffset; pCell->m_BaseInfo = *pBaseInfo; pCell->m_wLowLayer = 0; pbyOffset += sizeof(KCell::KBaseInfo); pCell->m_wHighLayer = *(WORD*)pbyOffset; pbyOffset += sizeof(WORD); } } KGLOG_PROCESS_ERROR(uLeftBytes >= sizeof(int)); uLeftBytes -= sizeof(int); nExtCellCount = *(int*)pbyOffset; pbyOffset += sizeof(int); KGLOG_PROCESS_ERROR(nExtCellCount >= 0); KGLOG_PROCESS_ERROR(uLeftBytes >= uExtCellInfoSize * nExtCellCount); uLeftBytes -= uExtCellInfoSize * nExtCellCount; for (int nIndex = 0; nIndex < nExtCellCount; nIndex++) { int nCellX = 0; int nCellY = 0; KCell::KBaseInfo* pBaseInfo = NULL; pAllocCell = rObjectAlloctor.NewCell(); KGLOG_PROCESS_ERROR(pAllocCell); nCellX = *(int*)pbyOffset; pbyOffset += sizeof(int); nCellY = *(int*)pbyOffset; pbyOffset += sizeof(int); pBaseInfo = (KCell::KBaseInfo*)pbyOffset; pbyOffset += sizeof(KCell::KBaseInfo); pAllocCell->m_BaseInfo = *pBaseInfo; pAllocCell->m_wHighLayer = *(WORD*)pbyOffset; pbyOffset += sizeof(WORD); pAllocCell->m_wLowLayer = *(WORD*)pbyOffset; pbyOffset += sizeof(WORD); bRetCode = AddObstacle(nCellX, nCellY, pAllocCell); KGLOG_PROCESS_ERROR(bRetCode); pAllocCell = NULL; } if (uLeftBytes >= sizeof(m_dwScriptList)) { memcpy(m_dwScriptList, pbyOffset, sizeof(m_dwScriptList)); pbyOffset += sizeof(m_dwScriptList); uLeftBytes -= sizeof(m_dwScriptList); } KGLOG_PROCESS_ERROR(uLeftBytes == 0); bResult = true; Exit0: if (pAllocCell) { rObjectAlloctor.DeleteCell(pAllocCell); pAllocCell = NULL; } KG_COM_RELEASE(piBuffer); KG_COM_RELEASE(piFile); return bResult; }
void SuiteFile::TestFunctionality(IFile& aFile, TUint32 aBytes) { Print("Testing File implementation functionality on %d byte file\n", aBytes); // We should be able to set the file cursor to all // bytes, from 0, up to /and including/ aBytes. // i.e. it is valid for the cursor to be pointing off // the end, but not to read data from here. // Test absolute seeking - ensure cursor is changed for // each test. aFile.Seek(0, eSeekFromStart); TEST(aFile.Tell() == 0); aFile.Seek(aBytes, eSeekFromStart); TEST(aFile.Tell() == aBytes); aFile.Seek(-(TInt) aBytes, eSeekFromEnd); TEST(aFile.Tell() == 0); aFile.Seek(0, eSeekFromEnd); TEST(aFile.Tell() == aBytes); // Test boundaries // Backwards at start. TEST_THROWS(aFile.Seek(-1, eSeekFromStart), FileSeekError); // Forwards at end //TEST_THROWS(aFile.Seek(+1, eSeekFromEnd), FileSeekError); // Forwards from start //TEST_THROWS(aFile.Seek(aBytes+1, eSeekFromStart), FileSeekError); // Backwards from end TEST_THROWS(aFile.Seek(-(TInt) (aBytes+1), eSeekFromEnd), FileSeekError); // Reading Bwh buffer(aBytes + 20); aFile.Seek(0, eSeekFromStart); aFile.Read(buffer); TEST(aFile.Tell() == aBytes); TEST(buffer.Bytes() == aBytes); const TUint readBytes = 10; aFile.Seek(0, eSeekFromStart); buffer.SetBytes(0); aFile.Read(buffer, readBytes); TEST(aFile.Tell() == readBytes); TEST(buffer.Bytes() == readBytes); aFile.Seek(-(TInt) (readBytes/2), eSeekFromEnd); buffer.SetBytes(0); aFile.Read(buffer); TEST(aFile.Tell() == aBytes); TEST(buffer.Bytes() == readBytes/2); aFile.Seek(0, eSeekFromEnd); buffer.SetBytes(0); TEST_THROWS(aFile.Read(buffer), FileReadError); // Writing buffer.SetBytes(aBytes/2); TEST_THROWS(aFile.Write(buffer), FileWriteError); Print("\n"); }
HRESULT KG3DAnimationWarper::Load(const TCHAR *strFileName) { HRESULT hr = E_FAIL; IFile *pFile = NULL; unsigned long uSize = 0; SerializeData Data; float *pWeights = NULL; KG3DAnimationUpdateExtraInfoCollector** ppCollectors = NULL; DWORD dwStartTime = timeGetTime(); KGLOG_PROCESS_ERROR(strFileName); KG_PROCESS_ERROR(m_pModel); Clear(); pFile = g_OpenFile(strFileName); if (!pFile) { KGLogPrintf(KGLOG_ERR, "KG3DAnimationWarper open file %s failed.", strFileName); goto Exit0; } uSize = pFile->Read(&Data, sizeof(SerializeData)); KGLOG_PROCESS_ERROR(uSize == sizeof(SerializeData)); KG_PROCESS_ERROR(Data.cdwMask == SerializeData::cdwMask); switch(Data.dwVersion) { case SerializeData::cdwVersion: { //read bone name information here hr = Helper_LoadBipExtraInfo(pFile); KGLOG_COM_PROCESS_ERROR(hr); m_Data.resize(Data.dwNumAnimationComposer); ppCollectors = new KG3DAnimationUpdateExtraInfoCollector*[Data.dwNumAnimation]; KGLOG_PROCESS_ERROR(ppCollectors); for (DWORD i = 0; i < Data.dwNumAnimation; i++) { AnimationInfo New; New.pClip = NULL; New.pCollector = new KG3DRTSInfoCollector; KGLOG_PROCESS_ERROR(New.pCollector); ppCollectors[i] = New.pCollector; New.pCollector->CreateStore(m_pModel); New.pCollector->Clear(); m_vecAnimations.push_back(New); m_vecTagContainers.push_back(NULL); } for (DWORD i = 0; i < Data.dwNumAnimationComposer; i++) { m_Data[i].Composer = new KG3DAnimationComposer; KGLOG_PROCESS_ERROR(m_Data[i].Composer); m_Data[i].Composer->Init(&m_Skeleton, m_pModel); m_Data[i].Composer->ReadBlock(pFile, ppCollectors, Data.dwNumAnimation); } break; } default: assert(0); } //Load composer weight information here size_t uIndex = 0; size_t uNumWeight = Data.dwNumBone * Data.dwNumAnimationComposer; pWeights = new float[uNumWeight]; KGLOG_PROCESS_ERROR(pWeights); uSize = pFile->Read(pWeights, sizeof(float) * (unsigned long)uNumWeight); KGLOG_PROCESS_ERROR(uSize == sizeof(float) * uNumWeight); for (size_t i = 0; i < m_Data.size(); i++) { m_Data[i].BoneWeight.resize(Data.dwNumBone); for (size_t j = 0; j < m_Data[i].BoneWeight.size(); j++) { assert(m_BoneMatchTable[j] != -1 && m_BoneMatchTable[j] < static_cast<int>(m_Data[i].BoneWeight.size())); BOOL bWeight = (pWeights[uIndex] == 1.0f) ? TRUE : FALSE; m_Data[i].BoneWeight[m_BoneMatchTable[j]] = bWeight; uIndex++; } } hr = S_OK; Exit0: SAFE_DELETE_ARRAY(pWeights); SAFE_DELETE_ARRAY(ppCollectors); KG_COM_RELEASE(pFile); DWORD dwCost = timeGetTime() - dwStartTime; if(g_cEngineOption.bEnableTimeOptimizeLog && dwCost > 10) { KGLogPrintf(KGLOG_INFO,"TimeOptimize KG3DAnimationWarper::Load cost %d %s",dwCost,strFileName); } return hr; }
HRESULT KG3DTerrainRoad::LoadFromFile(const char cszFileName[]) { //return E_FAIL; HRESULT hr = E_FAIL; int nRetCode = false; TCHAR FileName[MAX_PATH]; _RoadHead RoadHead; DWORD nSize; D3DXVECTOR3* pNodePos = NULL; IFile* pFile = NULL; pFile = g_OpenFile(cszFileName); KG_PROCESS_ERROR(pFile); nSize = pFile->Read(&RoadHead,sizeof(_RoadHead));//fread(&RoadData,sizeof(_RoadData),1,pFile); m_scName = RoadHead.scName; m_scTextureName = RoadHead.scTextureName; m_fBendModulus = RoadHead.fBendModulus; m_fEdgeModulus = RoadHead.fEdgeModulus; m_fTexDensity = RoadHead.fTexDensity; m_fBlendLength = RoadHead.fBlendLength; m_fWidth = RoadHead.fWidth; m_nID = RoadHead.nID; m_fNodeSize = RoadHead.fNodeSize; m_nSegmentLength= RoadHead.dwSegmentLength; wsprintf(FileName,"%s", m_scTextureName.c_str()); LoadRoadTexture(FileName); if (!g_bClient) { nRetCode = pFile->Seek(RoadHead.dwParentTerrainBlock, SEEK_SET); KGLOG_PROCESS_ERROR(nRetCode != -1); for (int nT= 0; nT < (int)RoadHead.dwNumParentBlock; nT++) { TerrainBlockInfo TBI; pFile->Read(&TBI,sizeof(TerrainBlockInfo)); m_vecParentTerrainBlock.push_back(TBI); } nRetCode = pFile->Seek(RoadHead.dwNodePosBlock, SEEK_SET);//fseek(pFile,RoadData.dwNodePosBlock, SEEK_SET); KGLOG_PROCESS_ERROR(nRetCode != -1); pNodePos = new D3DXVECTOR3[RoadHead.dwNumOfNode]; KGLOG_PROCESS_ERROR(pNodePos); nSize = pFile->Read(pNodePos,sizeof(D3DXVECTOR3)*RoadHead.dwNumOfNode);//fread(RoadData.pNodePos,sizeof(D3DXVECTOR3),RoadData.dwNumOfNode,pFile); LoadNode(RoadHead.dwNumOfNode,pNodePos); } nRetCode = pFile->Seek(RoadHead.dwPassageBlock, SEEK_SET); KGLOG_PROCESS_ERROR(nRetCode != -1); { list<KG3DRepresentObjectNode*>::iterator iNode = m_listNode.begin(); float fLengthSum = 0; m_BBox.Clear(); for (DWORD i = 0;i < RoadHead.dwNumOfPassage;i++) { KG3DTerrainRoadPassage* pPassage = new KG3DTerrainRoadPassage(); if(pPassage) { _PassageData ReadData; if(SUCCEEDED(pPassage->ReadDataFromFile(pFile,ReadData))) { pPassage->CreateBuffersFromData(ReadData); pPassage->BulidPassageData(fLengthSum,m_fWidth,m_fBendModulus,m_nSegmentLength,m_fExtendWidth); m_listPassage.push_back(pPassage); m_BBox.AddPosition(pPassage->m_Bbox.A); m_BBox.AddPosition(pPassage->m_Bbox.B); m_ExtendBBox.AddPosition(pPassage->m_ExtendBBox.A); m_ExtendBBox.AddPosition(pPassage->m_ExtendBBox.B); if(iNode!=m_listNode.end()) { pPassage->m_pNodeA = *iNode; ++iNode; if(iNode!=m_listNode.end()) pPassage->m_pNodeB = *iNode; } } else { SAFE_DELETE(pPassage); } } } this->m_fLength = fLengthSum; } hr = S_OK; Exit0: KG_COM_RELEASE(pFile); SAFE_DELETE_ARRAY(pNodePos); return hr; }
bool sMap::Import_VergeMAP(const char* filename, const char* tilesetFilename, IFileSystem& fs) { m_MusicFile = ""; m_EntryScript = ""; m_ExitScript = ""; m_Layers.clear(); m_Entities.clear(); IFile* file = fs.Open(filename, IFileSystem::read); if (file == NULL) return false; // check for v1 maps (ver 4) and v2 maps (ver 5) char signature[6]; file->Read(signature, 6); file->Seek(0); bool success = false; if (signature[0] == 4) { V1MAP_HEADER header; file->Read(&header, sizeof(header)); word* layer_background = new word[header.layer_size_x * header.layer_size_y]; word* layer_foreground = new word[header.layer_size_x * header.layer_size_y]; file->Read(layer_background, header.layer_size_x * header.layer_size_y * sizeof(word)); file->Read(layer_foreground, header.layer_size_x * header.layer_size_y * sizeof(word)); sTileset tileset; if (strcmp_ci(tilesetFilename + strlen(tilesetFilename) - 4, ".vsp") == 0) success = tileset.Import_VSP(tilesetFilename, fs); else success = tileset.Load(tilesetFilename, fs); sLayer layer[2]; if (success) { // process map and see if the map has tiles that are out of range int highestTileIndex = 0; for (int j=0; j<header.layer_size_y; j++) for (int i=0; i<header.layer_size_x; i++) if (layer_background[j * header.layer_size_x + i] >= highestTileIndex) highestTileIndex = layer_background[j * header.layer_size_x + i]; else if (layer_foreground[j * header.layer_size_x + i] >= highestTileIndex) highestTileIndex = layer_foreground[j * header.layer_size_x + i]; if (highestTileIndex >= tileset.GetNumTiles()) success = false; // transfer data across into the sMap now... if (success) { layer[0].SetName("Background"); layer[1].SetName("Foreground"); layer[0].Resize(header.layer_size_x, header.layer_size_y); layer[1].Resize(header.layer_size_x, header.layer_size_y); for (int j=0; j<header.layer_size_y; j++) for (int i=0; i<header.layer_size_x; i++) { layer[0].SetTile(i,j, layer_background[j * header.layer_size_x + i]); if (layer_foreground[j * header.layer_size_x + i]) layer[1].SetTile(i,j, layer_foreground[j * header.layer_size_x + i]); else layer[1].SetTile(i,j, tileset.GetNumTiles()); } tileset.AppendTiles(1); memset(tileset.GetTile(tileset.GetNumTiles() - 1).GetPixels(), 0, 256 * sizeof(RGBA)); m_Tileset = tileset; AppendLayer(layer[0]); AppendLayer(layer[1]); SetMusicFile((char*)header.music_fname); SetStartX(header.x_start); SetStartX(header.y_start); SetStartDirection(4); // calculate the parallax mode for (int i=0; i<2; i++) { // FIXME (set parallax properly) // GetLayer(i).SetParallaxX(1, 1); // GetLayer(i).SetParallaxY(1, 1); // GetLayer(i).SetScrollingX(1, 1); // GetLayer(i).SetScrollingX(1, 1); } switch(header.parallax_mode) { case 0: SetStartLayer(0); break; case 1: SetStartLayer(1); break; case 2: // FIXME (set parallax properly) SetStartLayer(1); // GetLayer(0).SetParallaxX(header.parallax_multiplier, header.parallax_divisor); // GetLayer(0).SetParallaxY(header.parallax_multiplier, header.parallax_divisor); break; case 3: // FIXME (set parallax properly) SetStartLayer(0); // GetLayer(1).SetParallaxX(header.parallax_multiplier, header.parallax_divisor); // GetLayer(1).SetParallaxY(header.parallax_multiplier, header.parallax_divisor); break; } } } // cleanup delete[] layer_background; delete[] layer_foreground; } else if (strcmp(signature, "MAPù5") == 0) { V2MAP_HEADER header; V2MAP_LAYERINFO LayerInfo[7]; sTileset tileset; word *mapLayer[7]; int i,j,k; int highestTileIndex = 0; file->Read(&header, sizeof(header)); for (i=0; i<header.num_layers; i++) { file->Read(LayerInfo + i, sizeof(V2MAP_LAYERINFO)); //bug for v2's map: two bytes are added for no reason word w; file->Read(&w, 2); } // get info about map and uncompress it for (i=0; i<header.num_layers; i++) mapLayer[i] = new word[LayerInfo[i].size_x * LayerInfo[i].size_y]; for (i=0; i<header.num_layers; i++) { // god, this is so dumb. It's supposed to be the buffersize, but do I look like I need it? file->Read(&j, 4); for (j=0; j<LayerInfo[i].size_x*LayerInfo[i].size_y; j++) { word value; byte run; file->Read(&value, sizeof(word)); if ((value & 0xFF00) == 0xFF00) { run = (byte)value & 0x00FF; file->Read(&value, sizeof(word)); mapLayer[i][j] = value; for (k=1; k<run; k++) { j++; mapLayer[i][j] = value; } } else { mapLayer[i][j] = value; } } } if (strcmp_ci(tilesetFilename + strlen(tilesetFilename) - 4, ".vsp") == 0) success = tileset.Import_VSP(tilesetFilename); else success = tileset.Load(tilesetFilename); // transfer map array into the class if (success) { highestTileIndex = 0; // check for any tile index larger than the tilset's index for (i=0; i<header.num_layers; i++) for (j=0; j<LayerInfo[i].size_x*LayerInfo[i].size_y; j++) if (mapLayer[i][j] >= highestTileIndex) highestTileIndex = mapLayer[i][j]; if (highestTileIndex >= tileset.GetNumTiles()) success = false; if (success) { sLayer *layer; layer = new sLayer[header.num_layers]; for (i=0; i<header.num_layers; i++) { char Name[7]; memcpy(Name, "Layer A", 8); Name[6] += i; layer[i].SetName(Name); layer[i].Resize(LayerInfo[i].size_x, LayerInfo[i].size_y); } for (i=0; i<header.num_layers; i++) { for (j=0; j<LayerInfo[i].size_y; j++) for (k=0; k<LayerInfo[i].size_x; k++) layer[i].SetTile(k, j, mapLayer[i][(j * LayerInfo[i].size_x) + k]); // FIXME: set parallax properly // layer[i].SetParallaxX(LayerInfo[i].multx, LayerInfo[i].pdivx); // layer[i].SetParallaxY(LayerInfo[i].multy, LayerInfo[i].pdivy); // layer[i].SetScrollingX(1,1); // layer[i].SetScrollingY(1,1); } for (i=0; i<(int)strlen((char*)header.renderstring); i++) switch(header.renderstring[i]) { case '1': AppendLayer(layer[0]); j = 0; break; case '2': AppendLayer(layer[1]); j = 1; break; case '3': AppendLayer(layer[2]); j = 2; break; case '4': AppendLayer(layer[3]); j = 3; break; case '5': AppendLayer(layer[4]); j = 4; break; case '6': AppendLayer(layer[5]); j = 5; break; case 'E': SetStartLayer(j); break; } SetMusicFile((char*)header.music_name); SetStartX(header.x_start); SetStartY(header.y_start); m_Tileset = tileset; delete[] layer; } } for (i=0; i<header.num_layers; i++) delete mapLayer[i]; } file->Close(); return success; }
bool sMap::Load(const char* filename, IFileSystem& fs) { // open the file IFile* file = fs.Open(filename, IFileSystem::read); if (file == NULL) { return false; } // read the header MAP_HEADER header; file->Read(&header, sizeof(header)); // make sure it's valid if (memcmp(header.signature, ".rmp", 4) != 0 || header.version != 1 || (header.num_strings != 3 && header.num_strings != 5 && header.num_strings != 9)) { file->Close(); return false; } m_StartX = header.startx; m_StartY = header.starty; m_StartLayer = header.startlayer; m_StartDirection = header.startdirection; // read the strings (tileset, music, script) std::string tileset_file = ReadMapString(file); // OBSOLETE m_MusicFile = ReadMapString(file); ReadMapString(file); // script file if (header.num_strings == 3) { m_EntryScript = ""; m_ExitScript = ""; } else { m_EntryScript = ReadMapString(file); m_ExitScript = ReadMapString(file); } if (header.num_strings > 5) { m_EdgeScripts[0] = ReadMapString(file); m_EdgeScripts[1] = ReadMapString(file); m_EdgeScripts[2] = ReadMapString(file); m_EdgeScripts[3] = ReadMapString(file); } // delete the old layer array and allocate a new one m_Layers.clear(); m_Layers.resize(header.num_layers); // read the layers for (int i = 0; i < header.num_layers; i++) { // read the layer header LAYER_HEADER lh; file->Read(&lh, sizeof(lh)); // read the layer name std::string name = ReadMapString(file); // set all layer attributes m_Layers[i].SetName(name.c_str()); m_Layers[i].Resize(lh.width, lh.height); m_Layers[i].SetXParallax(lh.parallax_x); m_Layers[i].SetYParallax(lh.parallax_y); m_Layers[i].SetXScrolling(lh.scrolling_x); m_Layers[i].SetYScrolling(lh.scrolling_y); m_Layers[i].SetVisible((lh.flags & 1) == 0); m_Layers[i].EnableParallax((lh.flags & 2) != 0); m_Layers[i].SetReflective(lh.reflective != 0); // read the layer data for (int iy = 0; iy < lh.height; iy++) { for (int ix = 0; ix < lh.width; ix++) { word tile; file->Read(&tile, sizeof(tile)); m_Layers[i].SetTile(ix, iy, tile); } } // load the obstruction map for (int j = 0; j < lh.num_segments; j++) { dword x1; file->Read(&x1, sizeof(dword)); dword y1; file->Read(&y1, sizeof(dword)); dword x2; file->Read(&x2, sizeof(dword)); dword y2; file->Read(&y2, sizeof(dword)); m_Layers[i].GetObstructionMap().AddSegment(x1, y1, x2, y2); } } // end for layer // delete the old entities m_Entities.clear(); // read entities for (int i = 0; i < header.num_entities; i++) { ENTITY_HEADER eh; file->Read(&eh, sizeof(eh)); sEntity* entity; switch (eh.type) { // PERSON case 1: { sPersonEntity* person = new sPersonEntity; // read the person data person->name = ReadMapString(file); person->spriteset = ReadMapString(file); word num_strings = ReadMapWord(file); // strings if (num_strings >= 1) person->script_create = ReadMapString(file); if (num_strings >= 2) person->script_destroy = ReadMapString(file); if (num_strings >= 3) person->script_activate_touch = ReadMapString(file); if (num_strings >= 4) person->script_activate_talk = ReadMapString(file); if (num_strings >= 5) person->script_generate_commands = ReadMapString(file); // reserved for (int i = 0; i < 16; i++) ReadMapByte(file); entity = person; break; } // TRIGGER case 2: { sTriggerEntity* trigger = new sTriggerEntity; // read/set the trigger data trigger->script = ReadMapString(file); entity = trigger; break; } default: // unknown continue; } // end switch entity->x = eh.mapx; entity->y = eh.mapy; entity->layer = eh.layer; AddEntity(entity); } // clear the zones m_Zones.clear(); // load the zones for (int i = 0; i < header.num_zones; i++) { ZONE_HEADER zh; sZone zone; file->Read(&zh, sizeof(zh)); zone.x1 = zh.x1; zone.y1 = zh.y1; zone.x2 = zh.x2; zone.y2 = zh.y2; zone.layer = zh.layer; zone.reactivate_in_num_steps = zh.reactivate_in_num_steps; zone.script = ReadMapString(file); m_Zones.push_back(zone); } // if no tileset file was specified, it is appended to the map file if (tileset_file.length() == 0) { if (!m_Tileset.LoadFromFile(file)) { file->Close(); return false; } } else m_Tileset.Clear(); file->Close(); return true; }
bool sTileset::Import_VSP(const char* filename, IFileSystem& fs) { IFile* file = fs.Open(filename, IFileSystem::read); if (file == NULL) return false; word version; RGB palette[256]; word numtiles; file->Read(&version, 2); file->Read(palette, 3 * 256); file->Read(&numtiles, 2); m_Tiles.clear(); m_Tiles.resize(numtiles); // decode the file if (version == 2) { for (int i = 0; i < numtiles; i++) { byte tile[256]; file->Read(tile, 256); for (int x = 0; x < 16; x++) for (int y = 0; y < 16; y++) { RGBA color; byte c = tile[y * 16 + x]; if (c == 0) { color.red = 0; color.green = 0; color.blue = 0; color.alpha = 0; } else { color.red = (byte)(palette[c].red * 4); color.green = (byte)(palette[c].green * 4); color.blue = (byte)(palette[c].blue * 4); color.alpha = 255; } m_Tiles[i].GetPixels()[y * 16 + x] = color; } } } else { // for that wierd thing aen never told me in the vsp code dword dw; file->Read(&dw, 4); // create a temporary buffer while setting up the decoding stuff... byte* buffer = (byte*)malloc(numtiles * 256); int len = numtiles * 256; int counter = 0; //start decoding! while (counter < len) { byte c; file->Read(&c, 1); // if the c was 255 then it's a compressed value if (c == 255) { byte run, color; file->Read(&run, 1); file->Read(&color, 1); for (int i = 0; i < run; i++) { buffer[counter] = color; counter++; } } else // it's a normal value { buffer[counter] = c; counter++; } } // now, tranfer the decoded stuff into the tiles' data structure for (int i = 0; i < numtiles; i++) for (int j = 0; j < 256; j++) { if (buffer[i * 256 + j] == 0) { m_Tiles[i].GetPixels()[j].red = 0; m_Tiles[i].GetPixels()[j].green = 0; m_Tiles[i].GetPixels()[j].blue = 0; m_Tiles[i].GetPixels()[j].alpha = 0; } else { m_Tiles[i].GetPixels()[j].red = (palette[buffer[i * 256 + j]].red) * 4; m_Tiles[i].GetPixels()[j].green = (palette[buffer[i * 256 + j]].green) * 4; m_Tiles[i].GetPixels()[j].blue = (palette[buffer[i * 256 + j]].blue) * 4; m_Tiles[i].GetPixels()[j].alpha = 255; } } } file->Close(); return true; }
int TestLoadAllBSP() { int nResult = false; int nRetCode = false; HRESULT hrRetCode = E_FAIL; unsigned uTotalCount = 0; unsigned uFailedCount = 0; unsigned uFailedCountSave = 0; BYTE *pbyTestFileData = NULL; BYTE *pbySourceFileData = NULL; IIniFile *pFile = NULL; IFile *piTestFile = NULL; IKG3DModel *piModel = NULL; IKG3DResourceManager *piModelTable = NULL; char szMessage[MAX_PATH] = ""; char szDirPath[MAX_PATH] = ""; TCHAR strBSPPathName[MAX_PATH] = ""; //vector<string> vecModelList; //vector<string> vecMeshList; MSG msg; nRetCode = GetCurrentDirectory(MAX_PATH, szDirPath); KG_PROCESS_ERROR(nRetCode > 0 && nRetCode < MAX_PATH + 1); strcat(szDirPath, "\\data\\source\\*.*"); szDirPath[MAX_PATH - 1] = '\0'; //strcpy(szDirPath, "D:\\Kingsoft\\Game\\sword3-products\\trunk\\client\\data\\source\\NPC_source\\*.*"); piModelTable = g_cEngineManager.Get3DModelTable(); KGLOG_PROCESS_ERROR(piModelTable); pFile = g_OpenIniFile(g_cszErrorFileName[EXT_MESH],false,true); KGLOG_PROCESS_ERROR(pFile); nRetCode = GetFileList(szDirPath, &g_vecSourceList/*vecMeshList*/, EXT_MESH); KGLOG_PROCESS_ERROR(nRetCode); //g_vecSourceList.push_back("D:\\Kingsoft\\Game\\trunk\\data\\source\\maps_source\\亭塔\\T_erg风车塔001A.Mesh"); uTotalCount = (unsigned)/*vecMeshList*/g_vecSourceList.size(); for (unsigned i = 0; i < uTotalCount; ++i) { char szKeyName[32] = ""; snprintf( szMessage, sizeof(szMessage), "Mesh模型的BSP文件检查:%s", /*vecMeshList*/g_vecSourceList[i].c_str() ); szMessage[sizeof(szMessage) - 1] = '\0'; SetWindowText(g_hWnd, szMessage); TCHAR strDriver[MAX_PATH]; TCHAR strPath[MAX_PATH]; TCHAR strFile[MAX_PATH]; _splitpath_s(g_vecSourceList[i].c_str(), strDriver, MAX_PATH, strPath, MAX_PATH, strFile, MAX_PATH, NULL, 0); //sprintf_s(strBSPPathName, // MAX_PATH, // "%s%s%s.bsp", // strDriver, // strPath, // strFile); //nRetCode = g_IsFileExist(strBSPPathName); //if (!nRetCode) //{ // /*itoa(uFailedCount, szKeyName, 10); // pFile->WriteString("BSP_NotExited",szKeyName, g_vecSourceList[i].c_str()); // ++uFailedCount;*/ // continue; //} try { g_bForceGenerateBspForMesh = /*FALSE*/TRUE; hrRetCode = piModelTable->LoadResourceFromFile(/*vecMeshList*/g_vecSourceList[i].c_str(), 0, 0, (IKG3DResourceBase**)&piModel); if (FAILED(hrRetCode)) { itoa(uFailedCount, szKeyName, 10); pFile->WriteString("ErrorMesh",szKeyName, /*vecMeshList*/g_vecSourceList[i].c_str()); ++uFailedCount; } KG_COM_RELEASE(piModel); g_cEngineManager.FrameMove(); g_bForceGenerateBspForMesh = FALSE; if (FAILED(hrRetCode)) { continue; } //cmp unsigned uTestFileDataSize = 0; unsigned uSourceFileDataSize = 0; unsigned uSizeRead = 0; sprintf_s(strBSPPathName, MAX_PATH, "%s%s%s.bsp", strDriver, strPath, strFile); nRetCode = g_IsFileExist(strBSPPathName); if (!nRetCode) { sprintf_s(strBSPPathName, MAX_PATH, "%s%s%s_test.bsp", strDriver, strPath, strFile); nRetCode = g_IsFileExist(strBSPPathName); if (nRetCode) { itoa(uFailedCount, szKeyName, 10); pFile->WriteString("BSP_NotGenerate",szKeyName, g_vecSourceList[i].c_str()); ++uFailedCount; DeleteFile(strBSPPathName); } continue; } piTestFile = g_OpenFile(strBSPPathName); KGLOG_PROCESS_ERROR(piTestFile); uSourceFileDataSize = piTestFile->Size(); KGLOG_PROCESS_ERROR(uSourceFileDataSize > sizeof(DWORD)); pbySourceFileData = new BYTE[uSourceFileDataSize]; KGLOG_PROCESS_ERROR(pbySourceFileData); uSizeRead = piTestFile->Read(pbySourceFileData, uSourceFileDataSize); KGLOG_PROCESS_ERROR(uSizeRead == uSourceFileDataSize); KG_COM_RELEASE(piTestFile); sprintf_s(strBSPPathName, MAX_PATH, "%s%s%s_test.bsp", strDriver, strPath, strFile); piTestFile = g_OpenFile(strBSPPathName); if (!piTestFile) { itoa(uFailedCount, szKeyName, 10); pFile->WriteString("BSP_Don't Exited",szKeyName, g_vecSourceList[i].c_str()); ++uFailedCount; SAFE_DELETE_ARRAY(pbySourceFileData); continue; } uTestFileDataSize = piTestFile->Size(); KGLOG_PROCESS_ERROR(uTestFileDataSize > sizeof(DWORD)); pbyTestFileData = new BYTE[uTestFileDataSize]; KGLOG_PROCESS_ERROR(pbyTestFileData); uSizeRead = piTestFile->Read(pbyTestFileData, uTestFileDataSize); KGLOG_PROCESS_ERROR(uSizeRead == uTestFileDataSize); KG_COM_RELEASE(piTestFile); if (uTestFileDataSize != uSourceFileDataSize) { itoa(uFailedCount, szKeyName, 10); pFile->WriteString("BSP_NotMatchedSize",szKeyName, g_vecSourceList[i].c_str()); ++uFailedCount; DeleteFile(strBSPPathName); SAFE_DELETE_ARRAY(pbyTestFileData); SAFE_DELETE_ARRAY(pbySourceFileData); continue; } nRetCode = memcmp(pbyTestFileData, pbySourceFileData, uSourceFileDataSize); if (nRetCode) { itoa(uFailedCount, szKeyName, 10); pFile->WriteString("BSP_NotMatched",szKeyName, g_vecSourceList[i].c_str()); ++uFailedCount; DeleteFile(strBSPPathName); SAFE_DELETE_ARRAY(pbyTestFileData); SAFE_DELETE_ARRAY(pbySourceFileData); continue; } DeleteFile(strBSPPathName); SAFE_DELETE_ARRAY(pbyTestFileData); SAFE_DELETE_ARRAY(pbySourceFileData); } catch (...) { itoa(uFailedCount, szKeyName, 10); pFile->WriteString("Mesh_Exception",szKeyName, /*vecMeshList*/g_vecSourceList[i].c_str()); ++uFailedCount; } while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { switch (msg.message) { case WM_QUIT: break; default: TranslateMessage(&msg); DispatchMessage(&msg); } } if (msg.message == WM_QUIT) break; } //uFailedCount += uFailedCountSave; //uTotalCount = (unsigned)(vecModelList.size() + vecMeshList.size()); // snprintf( // szMessage, sizeof(szMessage), // "模型加载检查完成:共检查模型 %u 个 已发现错误 %u 个,请检查文件%s", // uTotalCount, uFailedCount, g_cszErrorFileName[TYPE_MDL] //); //szMessage[sizeof(szMessage) - 1] = '\0'; //::MessageBox(g_hWnd, szMessage, "检查报告", MB_OK); nResult = true; Exit0: if (pFile) { pFile->WriteInteger("ErrorMesh", "ErrorNum", uFailedCount); pFile->Save(g_cszErrorFileName[EXT_MESH]); } SAFE_DELETE_ARRAY(pbyTestFileData); SAFE_DELETE_ARRAY(pbySourceFileData); if (strstr(strBSPPathName, "_test.bsp")) { DeleteFile(strBSPPathName); } KG_COM_RELEASE(piModel); KG_COM_RELEASE(pFile); KG_COM_RELEASE(piTestFile); g_bForceGenerateBspForMesh = FALSE; g_vecSourceList.clear(); return nResult; }
BOOL KScriptManager::Reload(const char* pszFileName) { BOOL bResult = false; BOOL bRetCode = false; IFile* piFile = NULL; char* pszBuffer = NULL; DWORD dwScriptID = 0; DWORD dwFileSize = 0; DWORD dwReadSize = 0; KLuaScriptData* pScriptData = NULL; char szPathName[MAX_PATH]; char szFileName[MAX_PATH]; assert(pszFileName); piFile = g_OpenFile(pszFileName); KG_PROCESS_ERROR(piFile); dwFileSize = piFile->Size(); pszBuffer = new char[dwFileSize]; KG_PROCESS_ERROR(pszBuffer); dwReadSize = piFile->Read(pszBuffer, dwFileSize); KG_PROCESS_ERROR(dwReadSize == dwFileSize); g_GetFullPath(szPathName, pszFileName); bRetCode = g_GetFilePathFromFullPath(szFileName, szPathName); KG_PROCESS_ERROR(bRetCode); dwScriptID = g_FileNameHash(szFileName); bRetCode = IsScriptExist(dwScriptID); KG_PROCESS_ERROR(bRetCode); bRetCode = m_piScript->LoadFromBuffer(dwScriptID, szPathName, pszBuffer, dwFileSize); KG_PROCESS_ERROR(bRetCode); pScriptData = m_piScript->GetScriptData(dwScriptID); if (pScriptData) { std::vector<DWORD>::iterator it = pScriptData->vecIncludeScriptID.begin(); std::vector<DWORD>::iterator itEnd = pScriptData->vecIncludeScriptID.end(); for (NULL; it != itEnd; ++it) { KLuaScriptData* pNewScriptData = NULL; pNewScriptData = m_piScript->GetScriptData(*it); if (pNewScriptData) Reload(pNewScriptData->szName); } } bResult = true; Exit0: if (!bResult) { KGLogPrintf(KGLOG_ERR, "[Lua] Failed to reload file \"%s\" !\n", pszFileName); } KG_DELETE_ARRAY(pszBuffer); KG_COM_RELEASE(piFile); return bResult; }
bool sTileset::Import_TST(const char* filename, IFileSystem& fs) { // TST file format created by Christoper B. Matthews for the RPG Toolkit Development System IFile* file = fs.Open(filename, IFileSystem::read); if (file == NULL) return false; // read header word version; word numtiles; word detail; file->Read(&version, 2); file->Read(&numtiles, 2); file->Read(&detail, 2); // check header for errors // only support details 2, 4, 6 if (version != 20 && (detail == 2 || detail == 4 || detail == 6)) { file->Close(); return false; } // allocate new tiles m_Tiles.clear(); m_Tiles.resize(numtiles); // read them from file for (int i = 0; i < m_Tiles.size(); i++) { sTile& tile = m_Tiles[i]; switch (detail) { case 2: // 16x16, 24-bit color { for (int ix = 0; ix < 16; ix++) for (int iy = 0; iy < 16; iy++) { RGB rgb; file->Read(&rgb, 3); byte alpha = 255; if (rgb.red == 0 && rgb.green == 1 && rgb.blue == 2) alpha = 0; tile.GetPixels()[iy * 16 + ix].red = rgb.red; tile.GetPixels()[iy * 16 + ix].green = rgb.green; tile.GetPixels()[iy * 16 + ix].blue = rgb.blue; tile.GetPixels()[iy * 16 + ix].alpha = alpha; } break; } case 4: // 16x16, 8-bit color case 6: // 16x16, 4-bit color // these two are effectively the same format { for (int ix = 0; ix < 16; ix++) for (int iy = 0; iy < 16; iy++) { byte b; file->Read(&b, 1); RGB rgb = dos_palette[b]; byte alpha = 255; if (b == 255) alpha = 0; tile.GetPixels()[iy * 16 + ix].red = rgb.red; tile.GetPixels()[iy * 16 + ix].green = rgb.green; tile.GetPixels()[iy * 16 + ix].blue = rgb.blue; tile.GetPixels()[iy * 16 + ix].alpha = alpha; } break; } } } file->Close(); return true; }
void ScanFileRecursively(const std::string dir, BlockFS* pFS, std::map<std::string, MD5Index>& mapEntries, std::vector<std::string>& add) { WIN32_FIND_DATAA finddata; std::string searchstring = dir + "/*"; HANDLE hfine = FindFirstFileA(searchstring.c_str(), &finddata); if (hfine != INVALID_HANDLE_VALUE) { do { if (finddata.dwFileAttributes&FILE_ATTRIBUTE_DIRECTORY) { if(strcmp(finddata.cFileName, ".svn")!=0&& strcmp(finddata.cFileName, ".")!=0&& strcmp(finddata.cFileName, "..")!=0) ScanFileRecursively(dir + "/" + finddata.cFileName, pFS, mapEntries, add); continue; } std::string name = dir; name += "/"; name += finddata.cFileName; std::transform(name.begin(), name.end(), name.begin(), tolower); std::map<std::string, MD5Index>::iterator it = mapEntries.find(name); if(it != mapEntries.end()) { IFile* pTemp = OpenDiskFile(name.c_str(), IFile::O_ReadOnly); offset_type length = pTemp->GetSize(); if(it->second.size==length) { char* buff = new char[(size_t)length.offset]; pTemp->Read(buff, length); std::transform(name.begin(), name.end(), name.begin(), tolower); printf("checking %s, %d bytes\n", name.c_str(), length); unsigned char ucCheckSum[16]; GetMD5CheckSum((unsigned char*)buff, (unsigned)length.offset, ucCheckSum); if(!memcmp(ucCheckSum, it->second.md5, sizeof(ucCheckSum))) { printf("file %s, ignored update\n", it->first.c_str()); mapEntries.erase(it); } else { printf("file %s, need update\n", it->first.c_str()); add.push_back(it->first); } //pFS->AddFile(name.c_str(), buff, length, length > pFS->GetBlockDataSize()); delete[]buff; } else { printf("file %s, with different size %d, original %d", name.c_str(), length, it->second.size); add.push_back(name); } delete pTemp; } else { printf("file %s will be added\n",name.c_str()); add.push_back(name); } } while (FindNextFileA(hfine, &finddata)); } FindClose(hfine); }
HRESULT KG3DAnimationTagContainer::_Load(LPCSTR strFileName) { HRESULT hrResult = E_FAIL; HRESULT hrRetCode = E_FAIL; IFile* pFile = NULL; FileHeader Header; AnimationTagBlockHeader BlockHeader; unsigned long uRetCode = 0; IKG3DAnimationTag* pNewTag = NULL; Clear(); KG_PROCESS_ERROR(strFileName); pFile = g_OpenFile(strFileName); KGLOG_PROCESS_ERROR(pFile); uRetCode = pFile->Read(&Header, sizeof(FileHeader)); KGLOG_PROCESS_ERROR(uRetCode == sizeof(FileHeader)); KG_PROCESS_ERROR(Header.dwMask == FileHeader::s_dwMask); strncpy(m_szAnimationName, Header.strAnimationFileName, _countof(m_szAnimationName) - 1); m_szAnimationName[_countof(m_szAnimationName) - 1] = '\0'; hrRetCode = g_cClipTable.LoadResourceFromFile(m_szAnimationName, 0, 0, &m_pClip); KGLOG_COM_PROCESS_ERROR(hrRetCode); switch(Header.dwVersion) { case FileHeader::s_dwCurrentVersion: { for (DWORD i = 0; i < Header.dwNumBlock; i++) { Item NewItem; uRetCode = pFile->Read(&BlockHeader, sizeof(AnimationTagBlockHeader)); KGLOG_PROCESS_ERROR(uRetCode == sizeof(AnimationTagBlockHeader)); if (BlockHeader.dwNumKeyFrames == 0) { hrRetCode = SkipBlock(&BlockHeader, pFile); KGLOG_COM_PROCESS_ERROR(hrRetCode); continue; } pNewTag = GetNewInstance(static_cast<enuTagType>(BlockHeader.dwType)); KG_PROCESS_ERROR(pNewTag); hrRetCode = pNewTag->LoadFromFile(pFile, BlockHeader.dwVersion, BlockHeader.dwNumKeyFrames); KG_COM_PROCESS_ERROR(hrRetCode); pNewTag->SetParentModel(m_pModel); NewItem.pTag = pNewTag; NewItem.Type = static_cast<enuTagType>(BlockHeader.dwType); m_vecTags.push_back(NewItem); pNewTag = NULL; } } break; default: _ASSERTE(0); } m_IsLoaded = TRUE; hrResult = S_OK; Exit0: SAFE_DELETE(pNewTag); KG_COM_RELEASE(pFile); return hrResult; }
DLLEXPORT void LoadActions(IServer* pServer) { Server=pServer; std::string compress_file = Server->getServerParameter("compress"); if(!compress_file.empty()) { IFile* in = Server->openFile(compress_file, MODE_READ_SEQUENTIAL); if(in==NULL) { Server->Log("Cannot open file \""+compress_file+"\" to compress", LL_ERROR); exit(1); } { Server->deleteFile(compress_file+".urz"); CompressedFile compFile(compress_file+".urz", MODE_RW_CREATE); if(compFile.hasError()) { Server->Log("Error opening compressed file", LL_ERROR); exit(3); } char buffer[32768]; _u32 read; do { read = in->Read(buffer, 32768); if(read>0) { if(compFile.Write(buffer, read)!=read) { Server->Log("Error writing to compressed file", LL_ERROR); exit(2); } } } while (read>0); compFile.finish(); delete in; } exit(0); } std::string decompress = Server->getServerParameter("decompress"); if(!decompress.empty()) { bool selected_via_gui=false; #ifdef _WIN32 if(decompress=="SelectViaGUI") { std::string filter; filter += "Compressed image files (*.vhdz)"; filter += '\0'; filter += "*.vhdz"; filter += '\0'; filter += '\0'; std::vector<std::string> res = file_via_dialog("Please select compressed image file to decompress", filter, false, true, ""); if(!res.empty()) { decompress = res[0]; } else { decompress.clear(); } if(decompress.empty()) { exit(1); } else { selected_via_gui=true; } } #endif std::string targetName = decompress; if(findextension(decompress)!="vhdz" && findextension(decompress)!="urz") { Server->Log("Unknown file extension: "+findextension(decompress), LL_ERROR); exit(1); } if(!Server->getServerParameter("output_fn").empty() && !selected_via_gui) { targetName = Server->getServerParameter("output_fn"); } bool b = decompress_vhd(decompress, targetName); exit(b?0:3); } std::string assemble = Server->getServerParameter("assemble"); if(!assemble.empty()) { bool selected_via_gui=false; std::vector<std::string> input_files; std::string output_file; #ifdef _WIN32 if(assemble=="SelectViaGUI") { std::string filter; filter += "Image files (*.vhdz;*.vhd)"; filter += '\0'; filter += "*.vhdz;*.vhd"; filter += '\0'; /*filter += L"Image files (*.vhd)"; filter += '\0'; filter += L"*.vhd"; filter += '\0';*/ filter += '\0'; std::vector<std::string> new_input_files; do { new_input_files = file_via_dialog("Please select all the images to assemble into one image. Cancel once finished.", filter, true, true, ""); input_files.insert(input_files.end(), new_input_files.begin(), new_input_files.end()); } while (!new_input_files.empty()); filter.clear(); filter += "Image file (*.vhd)"; filter += '\0'; filter += "*.vhd"; filter += '\0'; filter += '\0'; std::vector<std::string> output_files = file_via_dialog("Please select where to save the output image", filter, false, false, "vhd"); if(!output_files.empty()) { output_file = output_files[0]; } selected_via_gui=true; } #endif if(!selected_via_gui) { Tokenize(assemble, input_files, ";"); output_file = Server->getServerParameter("output_file"); } if(input_files.empty()) { Server->Log("No input files selected", LL_ERROR); exit(1); } if(output_file.empty()) { Server->Log("No output file selected", LL_ERROR); exit(1); } bool b = assemble_vhd(input_files, output_file); exit(b?0:3); } std::string devinfo=Server->getServerParameter("devinfo"); if(!devinfo.empty()) { FSNTFS ntfs("\\\\.\\"+devinfo+":", IFSImageFactory::EReadaheadMode_None, false, NULL); if(!ntfs.hasError()) { Server->Log("Used Space: "+convert(ntfs.calculateUsedSpace())+" of "+convert(ntfs.getSize())); Server->Log(convert(((float)ntfs.calculateUsedSpace()/(float)ntfs.getSize())*100.0f)+" %"); } } std::string vhdcopy_in=Server->getServerParameter("vhdcopy_in"); if(!vhdcopy_in.empty()) { Server->Log("VHDCopy."); VHDFile in(vhdcopy_in, true,0); if(in.isOpen()==false) { Server->Log("Error opening VHD-File \""+vhdcopy_in+"\"", LL_ERROR); exit(4); } uint64 vhdsize=in.getSize(); float vhdsize_gb=(vhdsize/1024)/1024.f/1024.f; uint64 vhdsize_mb=vhdsize/1024/1024; Server->Log("VHD Info: Size: "+convert(vhdsize_gb)+" GB "+convert(vhdsize_mb)+" MB",LL_INFO); unsigned int vhd_blocksize=in.getBlocksize(); std::string vhdcopy_out=Server->getServerParameter("vhdcopy_out"); if(vhdcopy_out.empty()) { Server->Log("'vhdcopy_out' not specified. Not copying.", LL_ERROR); exit(5); } else { IFile *out=Server->openFile(vhdcopy_out, MODE_RW); if(out==NULL) { Server->Log("Couldn't open output file", LL_ERROR); exit(6); } else { std::string skip_s=Server->getServerParameter("skip"); int skip=1024*512; if(!skip_s.empty()) { skip=atoi(skip_s.c_str()); } else if (is_disk_mbr(vhdcopy_in + ".mbr")) { skip = 0; } Server->Log("Skipping "+convert(skip)+" bytes...", LL_INFO); in.Seek(skip); char buffer[4096]; size_t read; int last_pc=0; int p_skip=0; uint64 currpos=skip; bool is_ok=true; out->Seek(0); while(currpos%vhd_blocksize!=0) { is_ok=in.Read(buffer, 512, read); if(read>0) { _u32 rc=out->Write(buffer, (_u32)read); if(rc!=read) { Server->Log("Writing to output file failed", LL_ERROR); exit(7); } } currpos+=read; } if(currpos!=skip) { Server->Log("First VHD sector at "+convert(currpos), LL_INFO); } do { if(in.has_sector()) { is_ok=in.Read(buffer, 4096, read); if(read>0) { _u32 rc=out->Write(buffer, (_u32)read); if(rc!=read) { Server->Log("Writing to output file failed", LL_ERROR); exit(7); } } currpos+=read; } else { read=4096; currpos+=read; in.Seek(currpos); out->Seek(currpos-skip); } ++p_skip; if(p_skip>100) { p_skip=0; int pc=(int)(((float)currpos/(float)vhdsize)*100.f+0.5f); if(pc!=last_pc) { Server->Log(convert(pc)+"%", LL_INFO); last_pc=pc; } } } while( read==4096 && is_ok ); Server->destroy(out); Server->Log("Copy process finished successfully.", LL_INFO); exit(0); } } } std::string hashfilecomp_1=Server->getServerParameter("hashfilecomp_1"); if(!hashfilecomp_1.empty()) { IFile *hf1=Server->openFile(hashfilecomp_1, MODE_READ); IFile *hf2=Server->openFile(Server->getServerParameter("hashfilecomp_2"), MODE_READ); if(hf1==NULL || hf2==NULL ) { Server->Log("Error opening hashfile", LL_ERROR); } else { size_t h_equal=0; size_t h_diff=0; _i64 fsize=hf1->Size(); for(_i64 p=0;p<fsize;p+=32) { char buf1[32]; hf1->Read(buf1, 32); char buf2[32]; hf2->Read(buf2, 32); if( memcmp(buf1, buf2, 32)==0) { ++h_equal; } else { ++h_diff; } } std::cout << "Hashfile analysis: " << h_equal << " equal hashes; " << h_diff << " differences " << std::endl; } exit(5); } std::string vhdinfo=Server->getServerParameter("vhdinfo"); if(!vhdinfo.empty()) { std::cout << "--VHDINFO--" << std::endl; VHDFile in(vhdinfo, true,0); if(in.isOpen()==false) { Server->Log("Error opening VHD-File \""+vhdinfo+"\"", LL_ERROR); exit(4); } uint64 vhdsize=in.getSize(); float vhdsize_gb=(vhdsize/1024)/1024.f/1024.f; uint64 vhdsize_mb=vhdsize/1024/1024; std::cout << ("VHD Info: Size: "+convert(vhdsize_gb)+" GB "+convert(vhdsize_mb)+" MB") << std::endl; std::cout << "Blocksize: " << in.getBlocksize() << " Bytes" << std::endl; uint64 new_blocks=0; uint64 total_blocks=0; unsigned int bs=in.getBlocksize(); for(uint64 pos=0;pos<vhdsize;pos+=bs) { in.Seek(pos); if(in.this_has_sector()) { ++new_blocks; } ++total_blocks; } std::cout << "Blocks: " << new_blocks << "/" << total_blocks << std::endl; exit(3); } std::string image_verify=Server->getServerParameter("image_verify"); if(!image_verify.empty()) { std::auto_ptr<IVHDFile> in(open_device_file(image_verify)); if(in.get()==NULL || in->isOpen()==false) { Server->Log("Error opening Image-File \""+image_verify+"\"", LL_ERROR); exit(4); } std::string s_hashfile=Server->getServerParameter("hashfile"); bool has_hashfile=true; if(s_hashfile.empty()) { has_hashfile=false; s_hashfile=image_verify+".hash"; } IFile *hashfile=Server->openFile(s_hashfile, MODE_READ); if(hashfile==NULL) { Server->Log("Error opening hashfile"); exit(5); } bool verify_all = Server->getServerParameter("verify_all")=="true"; if(verify_all) { Server->Log("Verifying empty blocks"); } const int64 vhd_blocksize=(1024*1024)/2; int skip=1024*512; std::string s_verify_skip = Server->getServerParameter("verify_skip"); if (!s_verify_skip.empty()) { skip = watoi(s_verify_skip); } in->Seek(skip); uint64 currpos=skip; uint64 size=in->getSize(); sha256_ctx ctx; sha256_init(&ctx); char buf[512]; int diff=0; int diff_w=0; size_t ok_blocks=0; int last_pc=0; unsigned char dig_z[32]; bool has_dig_z=false; for(;currpos<size;currpos+=vhd_blocksize) { in->Seek(currpos); bool has_sector=verify_all || in->this_has_sector(vhd_blocksize); if(!has_sector && !has_dig_z) { for(unsigned int i=0;i<vhd_blocksize;i+=512) { size_t read; in->Read(buf, 512, read); sha256_update(&ctx, (unsigned char*)buf, 512); } sha256_final(&ctx, dig_z); sha256_init(&ctx); has_dig_z=true; } unsigned char dig_r[32]; unsigned char dig_f[32]; if(has_sector) { for(unsigned int i=0;i<vhd_blocksize && currpos+i<size;i+=512) { size_t read; in->Read(buf, 512, read); sha256_update(&ctx, (unsigned char*)buf, 512); } _u32 dr=hashfile->Read((char*)dig_f, 32); if( dr!=32 ) { Server->Log("Could not read hash from file", LL_ERROR); } sha256_final(&ctx, dig_r); sha256_init(&ctx); } else { hashfile->Read((char*)dig_f, 32); memcpy(dig_r, dig_z, 32); } if(memcmp(dig_r, dig_f, 32)!=0) { ++diff; Server->Log("Different blocks: "+convert(diff)+" at pos "+convert(currpos)+" has_sector="+convert(has_sector)); } else if(has_sector && has_hashfile) { ++diff_w; Server->Log("Wrong difference: "+convert(diff_w)+" at pos "+convert(currpos)); } else { ++ok_blocks; } int pc=(int)((float)((float)currpos/(float)size)*100.f+0.5f); if(pc!=last_pc) { last_pc=pc; Server->Log("Checking hashfile: "+convert(pc)+"%"); } } if(diff==0) { Server->Log("Hashfile does match"); } Server->Log("Blocks with correct hash: "+convert(ok_blocks)); Server->Log("Different blocks: "+convert(diff)); Server->Log("Wrong differences: "+convert(diff_w)); exit(diff==0?0:7); } std::string device_verify=Server->getServerParameter("device_verify"); if(!device_verify.empty()) { std::auto_ptr<IVHDFile> in(open_device_file(device_verify)); if(in.get()==NULL || in->isOpen()==false) { Server->Log("Error opening Image-File \""+device_verify+"\"", LL_ERROR); exit(4); } int skip=1024*512; FileWrapper wrapper(in.get(), skip); FSNTFS fs(&wrapper, IFSImageFactory::EReadaheadMode_None, false, NULL); if(fs.hasError()) { Server->Log("Error opening device file", LL_ERROR); exit(3); } PrintInfo(&fs); std::string s_hashfile=Server->getServerParameter("hash_file"); if(s_hashfile.empty()) { s_hashfile = device_verify+".hash"; } IFile *hashfile=Server->openFile(s_hashfile, MODE_READ); if(hashfile==NULL) { Server->Log("Error opening hashfile "+s_hashfile); exit(7); } unsigned int ntfs_blocksize=(unsigned int)fs.getBlocksize(); unsigned int vhd_sectorsize=(1024*1024)/2; uint64 currpos=0; uint64 size=fs.getSize(); sha256_ctx ctx; sha256_init(&ctx); int diff=0; int last_pc=0; int mixed=0; std::vector<char> zerobuf; zerobuf.resize(ntfs_blocksize); memset(&zerobuf[0], 0, ntfs_blocksize); for(;currpos<size;currpos+=ntfs_blocksize) { bool has_block=fs.hasBlock(currpos/ntfs_blocksize); if(has_block) { fs_buffer buf(&fs, fs.readBlock(currpos/ntfs_blocksize)); if(buf.get()==NULL) { Server->Log("Could not read block "+convert(currpos/ntfs_blocksize), LL_ERROR); } else { sha256_update(&ctx, (unsigned char*)buf.get(), ntfs_blocksize); } mixed = mixed | 1; } else { sha256_update(&ctx, (unsigned char*)&zerobuf[0], ntfs_blocksize); mixed = mixed | 2; } if( (currpos+ntfs_blocksize)%vhd_sectorsize==0 ) { unsigned char dig_r[32]; unsigned char dig_f[32]; _u32 dr=hashfile->Read((char*)dig_f, 32); if( dr!=32 ) { Server->Log("Could not read hash from file", LL_ERROR); } sha256_final(&ctx, dig_r); sha256_init(&ctx); if(memcmp(dig_r, dig_f, 32)!=0 && mixed!=2) { ++diff; Server->Log("Different blocks: "+convert(diff)+" at pos "+convert(currpos)+" mixed = "+ (mixed==3? "true":"false")+" ("+convert(mixed)+")" ); } mixed=0; } int pc=(int)((float)((float)currpos/(float)size)*100.f+0.5f); if(pc!=last_pc) { last_pc=pc; Server->Log("Checking device hashsums: "+convert(pc)+"%"); } } if(diff>0) { Server->Log("Device does not match hash file"); } Server->Log("Different blocks: "+convert(diff)); exit(7); } std::string vhd_cmp=Server->getServerParameter("vhd_cmp"); if(!vhd_cmp.empty()) { VHDFile in(vhd_cmp, true,0); if(in.isOpen()==false) { Server->Log("Error opening VHD-File \""+vhd_cmp+"\"", LL_ERROR); exit(4); } std::string other=Server->getServerParameter("other"); VHDFile other_in(other, true,0); if(other_in.isOpen()==false) { Server->Log("Error opening VHD-File \""+other+"\"", LL_ERROR); exit(4); } unsigned int blocksize=in.getBlocksize(); int skip=1024*512; in.Seek(skip); other_in.Seek(skip); uint64 currpos=skip; uint64 size=(std::min)(in.getSize(), other_in.getSize()); char buf1[512]; char buf2[512]; int diff=0; int last_pc=0; for(;currpos<size;currpos+=blocksize) { in.Seek(currpos); other_in.Seek(currpos); bool has_sector=in.this_has_sector() || other_in.this_has_sector(); if(in.this_has_sector() && !other_in.this_has_sector()) { Server->Log("Sector only in file 1 at pos "+convert(currpos)); } if(!in.this_has_sector() && other_in.this_has_sector()) { Server->Log("Sector only in file 2 at pos "+convert(currpos)); } if(has_sector) { bool hdiff=false; for(unsigned int i=0;i<blocksize;i+=512) { size_t read; in.Read(buf1, 512, read); other_in.Read(buf2, 512, read); int mr=memcmp(buf1, buf2, 512); if(mr!=0) { int n=0; for(size_t i=0;i<512;++i) { if(buf1[i]!=buf2[i]) { ++n; } } if(n==2) { NTFSFileRecord *fr=(NTFSFileRecord*)buf1; if(fr->magic[0]=='F' && fr->magic[1]=='I' && fr->magic[2]=='L' && fr->magic[3]=='E' ) { MFTAttribute attr; attr.length=fr->attribute_offset; int pos=0; do { pos+=attr.length; memcpy((char*)&attr, buf1+pos, sizeof(MFTAttribute) ); if(attr.type==0x30 && attr.nonresident==0) //FILENAME { MFTAttributeFilename fn; memcpy((char*)&fn, buf1+pos+attr.attribute_offset, sizeof(MFTAttributeFilename) ); std::string fn_uc; fn_uc.resize(fn.filename_length*2); memcpy(&fn_uc[0], buf1+pos+attr.attribute_offset+sizeof(MFTAttributeFilename), fn.filename_length*2); Server->Log("Filename="+Server->ConvertFromUTF16(fn_uc) , LL_DEBUG); } Server->Log("Attribute Type: "+convert(attr.type)+" nonresident="+convert(attr.nonresident)+" length="+convert(attr.length), LL_DEBUG); }while( attr.type!=0xFFFFFFFF && attr.type!=0x80); } for(size_t i=0;i<512;++i) { if(buf1[i]!=buf2[i]) { Server->Log("Position "+convert(i)+": "+convert((int)buf1[i])+"<->"+convert((int)buf2[i])); } } } hdiff=true; break; } } if(hdiff) { ++diff; Server->Log("Different blocks: "+convert(diff)+" at pos "+convert(currpos)); } } int pc=(int)((float)((float)currpos/(float)size)*100.f+0.5f); if(pc!=last_pc) { last_pc=pc; Server->Log("Checking hashfile: "+convert(pc)+"%"); } } Server->Log("Different blocks: "+convert(diff)); exit(7); } std::string vhd_fixmftmirr=Server->getServerParameter("vhd_checkmftmirr"); if(!vhd_fixmftmirr.empty()) { VHDFile vhd(vhd_fixmftmirr, false, 0); vhd.addVolumeOffset(1024*512); if(vhd.isOpen()==false) { Server->Log("Could not open VHD file", LL_ERROR); exit(7); } if(Server->getServerParameter("fix")!="true") { FSNTFS fs(&vhd, IFSImageFactory::EReadaheadMode_None, false, NULL); if(fs.hasError()) { Server->Log("NTFS filesystem has errors", LL_ERROR); } exit(7); } else { FSNTFS fs(&vhd, IFSImageFactory::EReadaheadMode_None, false, NULL); if(fs.hasError()) { Server->Log("NTFS filesystem has errors", LL_ERROR); } exit(7); } exit(0); } #ifdef _DEBUG std::string fibmap_test_fn = Server->getServerParameter("fibmap_test"); if (!fibmap_test_fn.empty()) { #ifdef __linux__ fibmap_test(fibmap_test_fn, Server->getServerParameter("bitmap_source")); #endif exit(0); } #endif imagepluginmgr=new CImagePluginMgr; Server->RegisterPluginThreadsafeModel( imagepluginmgr, "fsimageplugin"); #ifndef STATIC_PLUGIN Server->Log("Loaded -fsimageplugin- plugin", LL_INFO); #endif }