//ファイルの暗号化 CIPHER_RESULT PmCipher::EncryptFile(const char *source_path, unsigned long file_size, bool compress, fstream *cipher_file, PmCipherProperty **cipher_property) { //戻り値・・・ステータス //第1引数・・・暗号化するファイルのパス //第2引数・・・暗号化するファイルの元サイズ //第3引数・・・圧縮フラグ(true:圧縮, false:無圧縮) //第4引数・・・暗号化(出力)ファイルストリームのポインタ //第5引数(out)・・・暗号化ファイルのプロパティ CIPHER_RESULT cr = CIPHER_OK; //サイズチェック if(Over2GB(file_size)) { return CIPHER_ERR_INVALID_FILE_SIZE; } //入力ファイルのストリーム fstream in_fs; //合計バッファサイズ unsigned long total_buf_size = 0, total_comp_buf_size = 0, total_cipher_buf_size = 0; //バッファサイズ DWORD buf_size, comp_size; //処理継続フラグ bool loop = true; //バッファメモリの確保 unsigned char *comp_input_buf = new unsigned char[PmCipher::CIPHER_BUF_SIZE]; unsigned char *input_buf = new unsigned char[PmCipher::CIPHER_BUF_SIZE]; unsigned char *output_buf = new unsigned char[PmCipher::CIPHER_BUF_SIZE]; //入力ファイルのオープン in_fs.open(source_path, ios::in|ios::binary); //圧縮あり if(compress) { //ZLIBストリーム初期化 z_stream z; z.zalloc = Z_NULL; z.zfree = Z_NULL; z.opaque = Z_NULL; //ZLIBストリーム初期化 if (deflateInit(&z, Z_DEFAULT_COMPRESSION) != Z_OK) { //失敗時は処理終了 cr = CIPHER_ERR_FATAL; loop = false; } //ZLIB入力バッファの初期化 z.avail_in = 0; z.next_out = input_buf; z.avail_out = PmCipher::CIPHER_BUF_SIZE; int status, flush = Z_NO_FLUSH; while(loop) { //入力バッファが空になったら平文ファイル読み込み if (z.avail_in == 0) { z.next_in = comp_input_buf; comp_size = (total_buf_size + (unsigned long)PmCipher::CIPHER_BUF_SIZE > file_size)?(DWORD)(file_size - total_buf_size):PmCipher::CIPHER_BUF_SIZE; z.avail_in = comp_size; if(total_buf_size + comp_size >= file_size) { flush = Z_FINISH; } in_fs.read((char *)comp_input_buf, comp_size); total_buf_size += comp_size; } //圧縮 status = deflate(&z, flush); //圧縮が完了したらループ脱出 if (status == Z_STREAM_END) { break; } //エラー時はループ脱出 if (status != Z_OK) { break; } //出力バッファが一杯になったら暗号化ファイルに書き出し if (z.avail_out == 0) { //バッファサイズ算出 buf_size = CIPHER_BUF_SIZE; total_comp_buf_size += buf_size; buf_size = m_blow_fish.GetOutputLength(buf_size); total_cipher_buf_size += buf_size; //暗号化 m_blow_fish.Encode(input_buf, output_buf, buf_size); //ファイルへ書き込み cipher_file->write((char *)output_buf, buf_size); //バッファメモリ、バッファサイズ設定 z.next_out = input_buf; z.avail_out = PmCipher::CIPHER_BUF_SIZE; } } //最後のバッファを出力 if ((buf_size = CIPHER_BUF_SIZE - z.avail_out) != 0) { //バッファサイズ算出 total_comp_buf_size += buf_size; buf_size = m_blow_fish.GetOutputLength(buf_size); total_cipher_buf_size += buf_size; //暗号化 m_blow_fish.Encode(input_buf, output_buf, buf_size); //ファイルへ書き込み cipher_file->write((char *)output_buf, buf_size); *cipher_file << std::flush; } //エラー時はサイズを0に if (deflateEnd(&z) != Z_OK) { cr = CIPHER_ERR_FATAL; total_buf_size = 0; } } //無圧縮 else { //EOFまでループ while(!in_fs.eof()) { //バッファサイズ算出 buf_size = (total_buf_size + (unsigned long)PmCipher::CIPHER_BUF_SIZE > file_size)?(DWORD)(file_size - total_buf_size):PmCipher::CIPHER_BUF_SIZE; //平文ファイルの読み込み in_fs.read((char *)input_buf, buf_size); buf_size = m_blow_fish.GetOutputLength((DWORD)buf_size); //暗号化 m_blow_fish.Encode(input_buf, output_buf, buf_size); //暗号化(出力)ファイルに書き出し cipher_file->write((char *)output_buf, buf_size); total_buf_size += buf_size; //ファイルサイズ分読み込んだらループ脱出 if(file_size <= total_buf_size) { total_cipher_buf_size = total_buf_size; break; } } *cipher_file << std::flush; } //バッファメモリの解放 SAFE_DELETE_ARRAY(comp_input_buf); SAFE_DELETE_ARRAY(input_buf); SAFE_DELETE_ARRAY(output_buf); //平文(入力)ファイルのクローズ in_fs.close(); if(cr == CIPHER_OK) { //ファイルプロパティの生成、設定 *cipher_property = new PmCipherProperty(); (*cipher_property)->SetSourceSize(file_size); (*cipher_property)->SetCompressSize(total_comp_buf_size); (*cipher_property)->SetCipherSize(total_cipher_buf_size); (*cipher_property)->SetPath(source_path); } return cr; }
LRESULT CALLBACK SongListProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); switch (wmId) { case IDM_SONGLIST_ADD_DIR: { DWORD size = 1024; TCHAR* path = new TCHAR[size]; ZeroMemory(path, size); BROWSEINFO bi; bi.hwndOwner = songlist.hWnd; bi.pidlRoot = NULL; bi.pszDisplayName = path; bi.lpszTitle = L"ÇëÑ¡ÔñĿ¼"; bi.ulFlags = 0; bi.lpfn = NULL; bi.lParam = 0; bi.iImage = 0; LPITEMIDLIST lp = SHBrowseForFolder(&bi); if (lp != NULL && SHGetPathFromIDList(lp, path)) PostThreadMessage(songlist.thread_id, ID_CMD_DIR, (WPARAM)path, 0); else SAFE_DELETE_ARRAY(path); } break; case IDM_SONGLIST_ADD_FILE: { DWORD size = 1024; TCHAR* filename = new TCHAR[size]; ZeroMemory(filename, size); OPENFILENAME ofn = {0}; ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = songlist.hWnd; ofn.lpstrFile = filename; ofn.nMaxFile = size; ofn.lpstrFileTitle = L"Ñ¡Ôñ²¥·ÅÎļþ"; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST; if (GetOpenFileName(&ofn) && wcslen(filename) > 0) PostThreadMessage(songlist.thread_id, ID_CMD_FILE, (WPARAM)filename, 0); else SAFE_DELETE_ARRAY(filename); } break; case IDM_SONGLIST_ADD_CD: { PostThreadMessage(songlist.thread_id, ID_CMD_CD, (WPARAM)lParam, 0); } break; } break; case WM_DRAWITEM: { DrawItem((LPDRAWITEMSTRUCT)lParam); } break; case WM_MEASUREITEM: { LPMEASUREITEMSTRUCT lpMeasureItemStruct = (LPMEASUREITEMSTRUCT)lParam; lpMeasureItemStruct->itemHeight = 16; } break; case WM_DROPFILES: { HDROP hDrop = (HDROP)wParam; UINT n = DragQueryFile(hDrop, -1, NULL, 0); if (n > 0) { DWORD size = 512; wchar_t* filename = new wchar_t[size]; wmemset(filename, 0, size); DragQueryFile(hDrop, 0, filename, size); PostThreadMessage(songlist.thread_id, ID_CMD_FILE, (WPARAM)filename, 0); } DragFinish(hDrop); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
PCMAudioFrame::~PCMAudioFrame() { SAFE_DELETE_ARRAY(data_); }
bool CVertexShader::LoadVariant( IShaderDefines *pDefines, bool bCompile ) { // check for already compiled default version of the shader if (pDefines == NULL && m_VertexShader != NULL) return true; // check for already compiled variant of the shader if (pDefines != NULL) { unsigned long iEncoding = pDefines->GetValuesEncoding().iEncoding; SHADERVARIANTSMAP::iterator itr = m_ShaderVariants.find( iEncoding ); if (itr != m_ShaderVariants.end()) return true; } D3DXMACRO *pMacros = NULL; if (pDefines) { const int iMaxShaderDefineCount = 32; const int iValueCharSize = 64; static char szValues[iMaxShaderDefineCount][iValueCharSize]; static D3DXMACRO vMacros[iMaxShaderDefineCount + 1]; if (iMaxShaderDefineCount < pDefines->GetDefineCount()) { m_ToolBox->Log( LOGFATALERROR, _T("Shader Define Count exceeds the internal buffer!\n") ); return false; } DWORD i; for (i=0; i < pDefines->GetDefineCount(); i++) { vMacros[i].Name = pDefines->GetDefineName(i); vMacros[i].Definition = _itoa(pDefines->GetDefineValue(i), szValues[i], 10); } // null terminate macro list vMacros[i].Name = NULL; vMacros[i].Definition = NULL; pMacros = vMacros; } LPDIRECT3DVERTEXSHADER9 pShader = NULL; LPD3DXBUFFER shaderBuf = NULL; LPD3DXBUFFER pErrorMsgs = NULL; CDX9IncludeManager includeInterface; LPDIRECT3DDEVICE9 pDevice = (LPDIRECT3DDEVICE9)m_Renderer->GetAPIDevice(); if( pDevice ) { int len = _tcslen( (const TCHAR*)m_Code ); LPCSTR profile = D3DXGetVertexShaderProfile( pDevice ); bool bLoadedCompiled = false; HRESULT hr = E_FAIL; const TCHAR *szFile = GetName()->GetString(); TCHAR drive[MAX_PATH]; TCHAR directory[MAX_PATH]; TCHAR filename[MAX_PATH]; TCHAR fileext[MAX_PATH]; TCHAR szDefinesTemp[65] = { '\0' }; _tsplitpath( szFile, drive, directory, filename, fileext ); StdString szCompiledFile; szCompiledFile += drive; szCompiledFile += directory; szCompiledFile += _T("Compiled\\"); szCompiledFile += filename; if (pDefines) { szCompiledFile += _T("_enc"); szCompiledFile += _itot(pDefines->GetValuesEncoding().iEncoding, szDefinesTemp, 10); } szCompiledFile += fileext; #ifdef XBOX szCompiledFile = SetPathDrive( szCompiledFile, EngineGetToolBox()->GetDrive() ); #endif LPVOID pShaderFileData = NULL; UINT shaderLen = 0; struct _stat shaderFilestat; // checking if compiled version exists, if we can load it into a buffer and if the file stats of the shader (not compiled) are readable if (CheckFileExists(szCompiledFile) && ( _tstat( szFile, &shaderFilestat ) == 0) && LoadFileIntoBuffer( szCompiledFile, pShaderFileData, shaderLen, true )) { m_ToolBox->Log( LOGINFORMATION, _T("Reading compiled shader file: %s\n"), szCompiledFile.c_str() ); // create a shader buffer to store the compiled shader hr = D3DXCreateBuffer( shaderLen, &shaderBuf ); if (SUCCEEDED(hr)) { time_t storedMTime = 0; // get the compiled date out of the file memcpy( &storedMTime, pShaderFileData, sizeof(time_t) ); // if the stored modified time in the compiled shader file is the same as the current // modified time of the shader file if( storedMTime == shaderFilestat.st_mtime ) { // reduce the buffer size by the preamble (mod time) shaderLen -= (int)sizeof(time_t); // copy the compiled shader into the shader buffer memcpy( shaderBuf->GetBufferPointer(), ((TCHAR *) pShaderFileData)+ sizeof(time_t), shaderLen); bLoadedCompiled = true; } } SAFE_DELETE_ARRAY( pShaderFileData ); } if (!bLoadedCompiled && bCompile) { if (pDefines) EngineGetToolBox()->Log( LOGINFORMATION, _T("Compiling shader %s:%d\n"), GetName()->GetString(), pDefines->GetValuesEncoding().iEncoding ); else EngineGetToolBox()->Log( LOGINFORMATION, _T("Compiling shader %s\n"), GetName()->GetString() ); hr = D3DXCompileShader( m_Code, len,//length of string in bytes pMacros, //can add that matrix of macros here &includeInterface, //for include directories "main",//? temp profile, //vs_1_1 for example 0, //compiling options? &shaderBuf, &pErrorMsgs, NULL ); } //now actually create the shader if( hr == D3D_OK && shaderBuf ) { if (!bLoadedCompiled) { struct _stat shaderFilestat; // get the shader file's modified time if (_tstat( szFile, &shaderFilestat ) == 0) { m_ToolBox->Log( LOGINFORMATION, _T("Writing compiled shader file: %s\n"), szCompiledFile.c_str() ); // open a compiled shader file for writing FILE *fp = fopen( szCompiledFile, "wb" ); if (fp) { // write shader file's modified time fwrite( &shaderFilestat.st_mtime, sizeof(time_t), 1, fp ); // write compiled shader data fwrite( shaderBuf->GetBufferPointer(), shaderBuf->GetBufferSize(), 1, fp ); fclose(fp); } else { m_ToolBox->Log( LOGWARNING, _T("Failed to write compiled shader file: %s\n"), szCompiledFile.c_str() ); } } } hr = pDevice->CreateVertexShader( (DWORD *) shaderBuf->GetBufferPointer(), &pShader ); assert( SUCCEEDED(hr) ); if (!SUCCEEDED(hr)) { m_ToolBox->Log( LOGWARNING, _T("Failed to create shader : %s\n"), szCompiledFile.c_str() ); } SAFE_RELEASE( shaderBuf ); SAFE_RELEASE( pErrorMsgs ); if (pDefines == NULL) // we are compiling the default shader with no macro defines { assert( m_VertexShader == NULL ); // the default shader should only be compiled on Init when this is NULL m_VertexShader = pShader; } else if (pDefines != NULL) // we are compiling a variant of the shader { unsigned long iEncoding = pDefines->GetValuesEncoding().iEncoding; m_ShaderVariants[iEncoding] = pShader; } return true; } } if( pErrorMsgs ) { IHashString * name = GetName(); TCHAR* debug_errors = (TCHAR*)pErrorMsgs->GetBufferPointer(); m_ToolBox->Log( LOGERROR, _T("Could not create Vertex shader %s\nError message: %s\n"), name->GetString(), debug_errors ); SAFE_RELEASE( pErrorMsgs ); } SAFE_RELEASE( shaderBuf ); return false; }
VertexDeclImpl::~VertexDeclImpl() { //SAFE_RELEASE(m_pDecl); SAFE_DELETE_ARRAY(m_pVertexElement); m_pGraphics->UnregisterResource(this); }
/** @brief openGL 디바이스 텍스쳐를 생성하고 pSrc의 이미지를 로딩시킨다. */ GLuint XGraphicsOpenGL::CreateTextureGL( void* const pImgSrc , int wSrc, int hSrc , XE::xtPixelFormat formatImgSrc , int wSrcAligned, int hSrcAligned , XE::xtPixelFormat formatSurface ) const { // XBREAK( pImgSrc == nullptr ); const int bppImgSrc = XE::GetBpp( formatImgSrc ); const int bppSurface = XE::GetBpp( formatSurface ); const auto glFormatSurface = XGraphicsOpenGL::sToGLFormat( formatSurface ); const auto glTypeSurface = XGraphicsOpenGL::sToGLType( formatSurface ); XBREAK( pImgSrc && bppImgSrc == 2 ); // 아직 16bit픽셀소스는 지원하지 않음. GLuint idTexture = 0; glGenTextures( 1, &idTexture ); CHECK_GL_ERROR(); if( idTexture == 0 ) { XERROR( "failed create texture: sizeSrc(%d,%d)", wSrc, hSrc ); return 0; } XGraphicsOpenGL::sBindTexture( idTexture ); CHECK_GL_ERROR(); const int sizeSrcAligned = wSrcAligned * hSrcAligned; ////////////////////////////////////////////////////////////////////////// if( bppSurface == 4 ) { DWORD *temp = nullptr; if( pImgSrc ) { // gl텍스쳐로 쓰기 위해 정렬된 사이즈의 메모리에 이미지를 복사 DWORD* _temp = temp = new DWORD[sizeSrcAligned]; memset( _temp, 0, sizeSrcAligned * bppSurface ); int i, j; DWORD *src = (DWORD* const)pImgSrc; for( i = 0; i < hSrc; i++ ) { for( j = 0; j < wSrc; j++ ) { *_temp++ = *src++; } _temp += (wSrcAligned - wSrc); } } glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, wSrcAligned, hSrcAligned, 0, GL_RGBA, GL_UNSIGNED_BYTE, temp ); s_glFmt = GL_RGBA; s_glType = GL_UNSIGNED_BYTE; #ifdef _DEBUG auto glErr = glGetError(); XASSERT( glErr == GL_NO_ERROR ); #endif // _DEBUG SAFE_DELETE_ARRAY( temp ); } else ////////////////////////////////////////////////////////////////////////// if( bppSurface == 2 ) { WORD *pDst = nullptr; // gl텍스쳐로 쓰기 위해 정렬된 사이즈의 메모리에 이미지를 복사 if( pImgSrc ) { WORD *_pDst = pDst = new WORD[ sizeSrcAligned ]; memset( _pDst, 0, sizeSrcAligned * bppSurface ); if( formatSurface == XE::xPF_RGB565 || formatSurface == XE::xPF_RGB555 ) { XE::ConvertBlockABGR8888ToRGB565( pDst, wSrcAligned, hSrcAligned, (DWORD*)pImgSrc, wSrc, hSrc ); } else if( formatSurface == XE::xPF_ARGB4444 ) { // 현재 WIN32 opengl에서는 RGBA4444로 넘겨야 제대로 나오지만 기기 opengl에서는 어떤게 맞는지 알수없음. 아마도 같지 않을까 함. XE::ConvertBlockABGR8888ToRGBA4444( pDst, wSrcAligned, hSrcAligned, (DWORD*)pImgSrc, wSrc, hSrc ); } else if( formatSurface == XE::xPF_ARGB1555 ) { XE::ConvertBlockABGR8888ToRGBA1555( pDst, wSrcAligned, hSrcAligned, (DWORD*)pImgSrc, wSrc, hSrc ); } else { XBREAK(1); } } const auto glFormatImgSrc = glFormatSurface; const auto glTypeSrc = glTypeSurface; glTexImage2D( GL_TEXTURE_2D, 0, glFormatSurface, // internal format wSrcAligned, hSrcAligned, 0, glFormatImgSrc, // pImgSrc의 포맷이지만 위에거랑 맞춰야 해서 같은걸 씀. glTypeSrc, pDst ); s_glFmt = glFormatSurface; s_glType = glTypeSrc; CHECK_GL_ERROR(); SAFE_DELETE_ARRAY( pDst ); } // XGraphicsOpenGL::sBindTexture( 0 ); CHECK_GL_ERROR(); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); // // XSurface::sAddSizeTotalVMem( sizeSrcAligned * bppSurface ); CHECK_GL_ERROR(); // return idTexture; } // CreateTextureGL
/** @brief 이미지의 일부분을 gl텍스쳐로 만든다. */ GLuint XGraphicsOpenGL::CreateTextureSubGL( void* const pImgSrc , const XE::POINT& sizeSrc // pImgSrc의 크기 , const XE::xRECTi& rectSrc // pImgSrc에서 잘라낼 영역 , XE::xtPixelFormat formatImgSrc , XE::xtPixelFormat formatSurface ) { const XE::POINT sizeTex = rectSrc.GetSize(); const XE::POINT sizeTexAligned = XGraphics::sAlignPowSize( sizeTex ); const int bppSurface = XE::GetBpp( formatSurface ); GLuint glTexture = 0; glGenTextures( 1, &glTexture ); CHECK_GL_ERROR(); if( XBREAK( glTexture == 0 ) ) return 0; if( pImgSrc ) { XGraphicsOpenGL::sBindTexture( glTexture ); CHECK_GL_ERROR(); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE ); glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE ); CHECK_GL_ERROR(); const auto glTypeTexel = XGraphicsOpenGL::sToGLType( formatSurface ); const auto glformatTexel = XGraphicsOpenGL::sToGLFormat( formatSurface ); // 영역만큼 이미지 잘라내어 pDst에 옮김. DWORD *pSrc = (DWORD*)pImgSrc; DWORD *pBuffClipped = new DWORD[ sizeTexAligned.Size() ]; DWORD *_pDst = pBuffClipped; pSrc += (rectSrc.GetTop() * sizeSrc.w + rectSrc.GetLeft()); memset( pBuffClipped, 0, sizeTexAligned.Size() * bppSurface ); for( int i = 0; i < sizeTexAligned.h; ++i ) { for( int j = 0; j < sizeTexAligned.w; ++j ) *_pDst++ = *pSrc++; pSrc += ( sizeSrc.w - sizeTex.w ); _pDst += ( sizeTexAligned.w - sizeTex.w ); } if( bppSurface == 4 ) { glTexImage2D( GL_TEXTURE_2D, 0, glformatTexel, sizeTexAligned.w, sizeTexAligned.h, 0, glformatTexel, glTypeTexel, pBuffClipped ); CHECK_GL_ERROR(); } else // if( bppSurface == 4 ) { if( bppSurface == 2 ) { WORD *pDst16 = new WORD[ sizeTexAligned.Size() ]; memset( pDst16, 0, sizeTexAligned.Size() * bppSurface ); if( formatSurface == XE::xPF_RGB565 ) { XE::ConvertBlockABGR8888ToRGB565( pDst16, sizeTexAligned, pBuffClipped, sizeTexAligned ); } else if( formatSurface == XE::xPF_ARGB4444 ) { XE::ConvertBlockABGR8888ToRGBA4444( pDst16, sizeTexAligned, pBuffClipped, sizeTexAligned ); } glTexImage2D( GL_TEXTURE_2D, 0, glformatTexel, sizeTexAligned.w, sizeTexAligned.h, 0, glformatTexel, glTypeTexel, pDst16 ); CHECK_GL_ERROR(); SAFE_DELETE_ARRAY( pDst16 ); } // if( bppSurface == 2 ) { // XSurface::sAddSizeTotalVMem( sizeTexAligned.Size() * bppSurface ); SAFE_DELETE_ARRAY( pBuffClipped ); } // if( pImgSrc ) { return glTexture; } // CreateTextureSubGL()
void CSXFile::Cleanup() { SAFE_DELETE_ARRAY(m_Filename); Close(); }
void WrappedID3D11DeviceContext::ProcessChunk(uint64_t offset, D3D11ChunkType chunk, bool forceExecute) { if(chunk < FIRST_CONTEXT_CHUNK && !forceExecute) { if(m_State == READING) { m_pDevice->GetResourceManager()->MarkInFrame(false); m_pDevice->ProcessChunk(offset, chunk); m_pSerialiser->PopContext(NULL, chunk); m_pDevice->GetResourceManager()->MarkInFrame(true); } else if(m_State == EXECUTING) { m_pSerialiser->SkipCurrentChunk(); m_pSerialiser->PopContext(NULL, chunk); } return; } m_CurChunkOffset = offset; RDCASSERT(GetType() == D3D11_DEVICE_CONTEXT_IMMEDIATE); uint64_t cOffs = m_pSerialiser->GetOffset(); ResourceId ctxId; m_pSerialiser->Serialise("context", ctxId); WrappedID3D11DeviceContext *context = (WrappedID3D11DeviceContext *)m_pDevice->GetResourceManager()->GetLiveResource(ctxId); if(m_FakeContext != ResourceId()) { if(m_FakeContext == ctxId) context = this; else { m_pSerialiser->SetOffset(cOffs); m_pSerialiser->SkipCurrentChunk(); m_pSerialiser->PopContext(NULL, chunk); return; } } RDCASSERT(WrappedID3D11DeviceContext::IsAlloc(context)); LogState state = context->m_State; if(forceExecute) context->m_State = EXECUTING; else context->m_State = m_State; m_AddedDrawcall = false; switch(chunk) { case SET_INPUT_LAYOUT: context->Serialise_IASetInputLayout(0x0); break; case SET_VBUFFER: context->Serialise_IASetVertexBuffers(0, 0, 0x0, 0x0, 0x0); break; case SET_IBUFFER: context->Serialise_IASetIndexBuffer(0, DXGI_FORMAT_UNKNOWN, 0); break; case SET_TOPOLOGY: context->Serialise_IASetPrimitiveTopology(D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED); break; case SET_VS_CBUFFERS: context->Serialise_VSSetConstantBuffers(0, 0, 0x0); break; case SET_VS_RESOURCES: context->Serialise_VSSetShaderResources(0, 0, 0x0); break; case SET_VS_SAMPLERS: context->Serialise_VSSetSamplers(0, 0, 0x0); break; case SET_VS: context->Serialise_VSSetShader(0x0, 0x0, 0); break; case SET_HS_CBUFFERS: context->Serialise_HSSetConstantBuffers(0, 0, 0x0); break; case SET_HS_RESOURCES: context->Serialise_HSSetShaderResources(0, 0, 0x0); break; case SET_HS_SAMPLERS: context->Serialise_HSSetSamplers(0, 0, 0x0); break; case SET_HS: context->Serialise_HSSetShader(0x0, 0x0, 0); break; case SET_DS_CBUFFERS: context->Serialise_DSSetConstantBuffers(0, 0, 0x0); break; case SET_DS_RESOURCES: context->Serialise_DSSetShaderResources(0, 0, 0x0); break; case SET_DS_SAMPLERS: context->Serialise_DSSetSamplers(0, 0, 0x0); break; case SET_DS: context->Serialise_DSSetShader(0x0, 0x0, 0); break; case SET_GS_CBUFFERS: context->Serialise_GSSetConstantBuffers(0, 0, 0x0); break; case SET_GS_RESOURCES: context->Serialise_GSSetShaderResources(0, 0, 0x0); break; case SET_GS_SAMPLERS: context->Serialise_GSSetSamplers(0, 0, 0x0); break; case SET_GS: context->Serialise_GSSetShader(0x0, 0x0, 0); break; case SET_SO_TARGETS: context->Serialise_SOSetTargets(0, 0x0, 0x0); break; case SET_PS_CBUFFERS: context->Serialise_PSSetConstantBuffers(0, 0, 0x0); break; case SET_PS_RESOURCES: context->Serialise_PSSetShaderResources(0, 0, 0x0); break; case SET_PS_SAMPLERS: context->Serialise_PSSetSamplers(0, 0, 0x0); break; case SET_PS: context->Serialise_PSSetShader(0x0, 0x0, 0); break; case SET_CS_CBUFFERS: context->Serialise_CSSetConstantBuffers(0, 0, 0x0); break; case SET_CS_RESOURCES: context->Serialise_CSSetShaderResources(0, 0, 0x0); break; case SET_CS_UAVS: context->Serialise_CSSetUnorderedAccessViews(0, 0, 0x0, 0x0); break; case SET_CS_SAMPLERS: context->Serialise_CSSetSamplers(0, 0, 0x0); break; case SET_CS: context->Serialise_CSSetShader(0x0, 0x0, 0); break; case SET_VIEWPORTS: context->Serialise_RSSetViewports(0, 0x0); break; case SET_SCISSORS: context->Serialise_RSSetScissorRects(0, 0x0); break; case SET_RASTER: context->Serialise_RSSetState(0x0); break; case SET_RTARGET: context->Serialise_OMSetRenderTargets(0, 0x0, 0x0); break; case SET_RTARGET_AND_UAVS: context->Serialise_OMSetRenderTargetsAndUnorderedAccessViews(0, 0x0, 0x0, 0, 0, 0x0, 0x0); break; case SET_BLEND: context->Serialise_OMSetBlendState(0x0, (FLOAT*)0x0, 0); break; case SET_DEPTHSTENCIL: context->Serialise_OMSetDepthStencilState(0x0, 0); break; case DRAW_INDEXED_INST: context->Serialise_DrawIndexedInstanced(0, 0, 0, 0, 0); break; case DRAW_INST: context->Serialise_DrawInstanced(0, 0, 0, 0); break; case DRAW_INDEXED: context->Serialise_DrawIndexed(0, 0, 0); break; case DRAW: context->Serialise_Draw(0, 0); break; case DRAW_AUTO: context->Serialise_DrawAuto(); break; case DRAW_INDEXED_INST_INDIRECT: context->Serialise_DrawIndexedInstancedIndirect(0x0, 0); break; case DRAW_INST_INDIRECT: context->Serialise_DrawInstancedIndirect(0x0, 0); break; case MAP: context->Serialise_Map(0, 0, (D3D11_MAP)0, 0, 0); break; case UNMAP: context->Serialise_Unmap(0, 0); break; case COPY_SUBRESOURCE_REGION: context->Serialise_CopySubresourceRegion(0x0, 0, 0, 0, 0, 0x0, 0, 0x0); break; case COPY_RESOURCE: context->Serialise_CopyResource(0x0, 0x0); break; case UPDATE_SUBRESOURCE: context->Serialise_UpdateSubresource(0x0, 0, 0x0, 0x0, 0, 0); break; case COPY_STRUCTURE_COUNT: context->Serialise_CopyStructureCount(0x0, 0, 0x0); break; case RESOLVE_SUBRESOURCE: context->Serialise_ResolveSubresource(0x0, 0, 0x0, 0, DXGI_FORMAT_UNKNOWN); break; case GENERATE_MIPS: context->Serialise_GenerateMips(0x0); break; case CLEAR_DSV: context->Serialise_ClearDepthStencilView(0x0, 0, 0.0f, 0); break; case CLEAR_RTV: context->Serialise_ClearRenderTargetView(0x0, (FLOAT*)0x0); break; case CLEAR_UAV_INT: context->Serialise_ClearUnorderedAccessViewUint(0x0, (UINT*)0x0); break; case CLEAR_UAV_FLOAT: context->Serialise_ClearUnorderedAccessViewFloat(0x0, (FLOAT*)0x0); break; case CLEAR_STATE: context->Serialise_ClearState(); break; case EXECUTE_CMD_LIST: context->Serialise_ExecuteCommandList(0x0, 0); break; case DISPATCH: context->Serialise_Dispatch(0, 0, 0); break; case DISPATCH_INDIRECT: context->Serialise_DispatchIndirect(0x0, 0); break; case FINISH_CMD_LIST: context->Serialise_FinishCommandList(0, 0x0); break; case FLUSH: context->Serialise_Flush(); break; case SET_PREDICATION: context->Serialise_SetPredication(0x0, 0x0); break; case SET_RESOURCE_MINLOD: context->Serialise_SetResourceMinLOD(0x0, 0); break; case BEGIN: context->Serialise_Begin(0x0); break; case END: context->Serialise_End(0x0); break; #if defined(INCLUDE_D3D_11_1) case COPY_SUBRESOURCE_REGION1: context->Serialise_CopySubresourceRegion1(0x0, 0, 0, 0, 0, 0x0, 0, 0x0, 0); break; case UPDATE_SUBRESOURCE1: context->Serialise_UpdateSubresource1(0x0, 0, 0x0, 0x0, 0, 0, 0); break; case CLEAR_VIEW: context->Serialise_ClearView(0x0, 0x0, 0x0, 0); break; case SET_VS_CBUFFERS1: context->Serialise_VSSetConstantBuffers1(0, 0, 0x0, 0x0, 0x0); break; case SET_HS_CBUFFERS1: context->Serialise_HSSetConstantBuffers1(0, 0, 0x0, 0x0, 0x0); break; case SET_DS_CBUFFERS1: context->Serialise_DSSetConstantBuffers1(0, 0, 0x0, 0x0, 0x0); break; case SET_GS_CBUFFERS1: context->Serialise_GSSetConstantBuffers1(0, 0, 0x0, 0x0, 0x0); break; case SET_PS_CBUFFERS1: context->Serialise_PSSetConstantBuffers1(0, 0, 0x0, 0x0, 0x0); break; case SET_CS_CBUFFERS1: context->Serialise_CSSetConstantBuffers1(0, 0, 0x0, 0x0, 0x0); break; #else case COPY_SUBRESOURCE_REGION1: case UPDATE_SUBRESOURCE1: case CLEAR_VIEW: case SET_VS_CBUFFERS1: case SET_HS_CBUFFERS1: case SET_DS_CBUFFERS1: case SET_GS_CBUFFERS1: case SET_PS_CBUFFERS1: case SET_CS_CBUFFERS1: RDCERR("Replaying log with D3D11.1 events on a build without D3D11.1 support"); break; #endif case BEGIN_EVENT: context->Serialise_BeginEvent(0, L""); break; case SET_MARKER: context->Serialise_SetMarker(0, L""); break; case END_EVENT: context->Serialise_EndEvent(); break; case CONTEXT_CAPTURE_FOOTER: { bool HasCallstack = false; m_pSerialiser->Serialise("HasCallstack", HasCallstack); if(HasCallstack) { size_t numLevels = 0; uint64_t *stack = NULL; m_pSerialiser->Serialise("callstack", stack, numLevels); m_pSerialiser->SetCallstack(stack, numLevels); SAFE_DELETE_ARRAY(stack); } if(m_State == READING) { AddEvent(CONTEXT_CAPTURE_FOOTER, "IDXGISwapChain::Present()"); FetchDrawcall draw; draw.name = L"Present()"; draw.flags |= eDraw_Present; AddDrawcall(draw, true); } } break; default: RDCERR("Unrecognised Chunk type %d", chunk); break; } m_pSerialiser->PopContext(NULL, chunk); if(context->m_State == READING && chunk == SET_MARKER) { // no push/pop necessary } else if(context->m_State == READING && chunk == BEGIN_EVENT) { // push down the drawcallstack to the latest drawcall context->m_DrawcallStack.push_back(&context->m_DrawcallStack.back()->children.back()); } else if(context->m_State == READING && chunk == END_EVENT) { // refuse to pop off further than the root drawcall (mismatched begin/end events e.g.) RDCASSERT(context->m_DrawcallStack.size() > 1); if(context->m_DrawcallStack.size() > 1) context->m_DrawcallStack.pop_back(); } else if(context->m_State == READING) { if(!m_AddedDrawcall) context->AddEvent(chunk, m_pSerialiser->GetDebugStr()); } m_AddedDrawcall = false; if(forceExecute) context->m_State = state; }
bool WrappedVulkan::Serialise_vkQueueSubmit( Serialiser* localSerialiser, VkQueue queue, uint32_t submitCount, const VkSubmitInfo* pSubmits, VkFence fence) { SERIALISE_ELEMENT(ResourceId, queueId, GetResID(queue)); SERIALISE_ELEMENT(ResourceId, fenceId, fence != VK_NULL_HANDLE ? GetResID(fence) : ResourceId()); SERIALISE_ELEMENT(uint32_t, numCmds, pSubmits->commandBufferCount); vector<ResourceId> cmdIds; VkCommandBuffer *cmds = m_State >= WRITING ? NULL : new VkCommandBuffer[numCmds]; for(uint32_t i=0; i < numCmds; i++) { ResourceId bakedId; if(m_State >= WRITING) { VkResourceRecord *record = GetRecord(pSubmits->pCommandBuffers[i]); RDCASSERT(record->bakedCommands); if(record->bakedCommands) bakedId = record->bakedCommands->GetResourceID(); } SERIALISE_ELEMENT(ResourceId, id, bakedId); if(m_State < WRITING) { cmdIds.push_back(id); cmds[i] = id != ResourceId() ? Unwrap(GetResourceManager()->GetLiveHandle<VkCommandBuffer>(id)) : NULL; } } if(m_State < WRITING) { queue = GetResourceManager()->GetLiveHandle<VkQueue>(queueId); if(fenceId != ResourceId()) fence = GetResourceManager()->GetLiveHandle<VkFence>(fenceId); else fence = VK_NULL_HANDLE; } // we don't serialise semaphores at all, just whether we waited on any. // For waiting semaphores, since we don't track state we have to just conservatively // wait for queue idle. Since we do that, there's equally no point in signalling semaphores SERIALISE_ELEMENT(uint32_t, numWaitSems, pSubmits->waitSemaphoreCount); if(m_State < WRITING && numWaitSems > 0) ObjDisp(queue)->QueueWaitIdle(Unwrap(queue)); VkSubmitInfo submitInfo = { VK_STRUCTURE_TYPE_SUBMIT_INFO, NULL, 0, NULL, NULL, // wait semaphores numCmds, cmds, // command buffers 0, NULL, // signal semaphores }; const string desc = localSerialiser->GetDebugStr(); if(m_State == READING) { ObjDisp(queue)->QueueSubmit(Unwrap(queue), 1, &submitInfo, Unwrap(fence)); for(uint32_t i=0; i < numCmds; i++) { ResourceId cmd = GetResourceManager()->GetLiveID(cmdIds[i]); GetResourceManager()->ApplyBarriers(m_BakedCmdBufferInfo[cmd].imgbarriers, m_ImageLayouts); } AddEvent(QUEUE_SUBMIT, desc); // we're adding multiple events, need to increment ourselves m_RootEventID++; string basename = "vkQueueSubmit(" + ToStr::Get(numCmds) + ")"; for(uint32_t c=0; c < numCmds; c++) { string name = StringFormat::Fmt("=> %s[%u]: vkBeginCommandBuffer(%s)", basename.c_str(), c, ToStr::Get(cmdIds[c]).c_str()); // add a fake marker FetchDrawcall draw; draw.name = name; draw.flags |= eDraw_SetMarker; AddEvent(SET_MARKER, name); AddDrawcall(draw, true); m_RootEventID++; // insert the baked command buffer in-line into this list of notes, assigning new event and drawIDs InsertDrawsAndRefreshIDs(m_BakedCmdBufferInfo[cmdIds[c]].draw->children, m_RootEventID, m_RootDrawcallID); m_PartialReplayData.cmdBufferSubmits[cmdIds[c]].push_back(m_RootEventID); m_RootEventID += m_BakedCmdBufferInfo[cmdIds[c]].eventCount; m_RootDrawcallID += m_BakedCmdBufferInfo[cmdIds[c]].drawCount; name = StringFormat::Fmt("=> %s[%u]: vkEndCommandBuffer(%s)", basename.c_str(), c, ToStr::Get(cmdIds[c]).c_str()); draw.name = name; AddEvent(SET_MARKER, name); AddDrawcall(draw, true); m_RootEventID++; } // account for the outer loop thinking we've added one event and incrementing, // since we've done all the handling ourselves this will be off by one. m_RootEventID--; } else if(m_State == EXECUTING) { // account for the queue submit event m_RootEventID++; uint32_t startEID = m_RootEventID; // advance m_CurEventID to match the events added when reading for(uint32_t c=0; c < numCmds; c++) { // 2 extra for the virtual labels around the command buffer m_RootEventID += 2+m_BakedCmdBufferInfo[cmdIds[c]].eventCount; m_RootDrawcallID += 2+m_BakedCmdBufferInfo[cmdIds[c]].drawCount; } // same accounting for the outer loop as above m_RootEventID--; if(numCmds == 0) { // do nothing, don't bother with the logic below } else if(m_LastEventID <= startEID) { RDCDEBUG("Queue Submit no replay %u == %u", m_LastEventID, startEID); } else if(m_DrawcallCallback && m_DrawcallCallback->RecordAllCmds()) { RDCDEBUG("Queue Submit re-recording from %u", m_RootEventID); vector<VkCommandBuffer> rerecordedCmds; for(uint32_t c=0; c < numCmds; c++) { VkCommandBuffer cmd = RerecordCmdBuf(cmdIds[c]); ResourceId rerecord = GetResID(cmd); RDCDEBUG("Queue Submit fully re-recorded replay of %llu, using %llu", cmdIds[c], rerecord); rerecordedCmds.push_back(Unwrap(cmd)); GetResourceManager()->ApplyBarriers(m_BakedCmdBufferInfo[rerecord].imgbarriers, m_ImageLayouts); } submitInfo.commandBufferCount = (uint32_t)rerecordedCmds.size(); submitInfo.pCommandBuffers = &rerecordedCmds[0]; ObjDisp(queue)->QueueSubmit(Unwrap(queue), 1, &submitInfo, Unwrap(fence)); } else if(m_LastEventID > startEID && m_LastEventID < m_RootEventID) { RDCDEBUG("Queue Submit partial replay %u < %u", m_LastEventID, m_RootEventID); uint32_t eid = startEID; vector<ResourceId> trimmedCmdIds; vector<VkCommandBuffer> trimmedCmds; for(uint32_t c=0; c < numCmds; c++) { // account for the virtual vkBeginCommandBuffer label at the start of the events here // so it matches up to baseEvent eid++; uint32_t end = eid + m_BakedCmdBufferInfo[cmdIds[c]].eventCount; if(eid == m_PartialReplayData.baseEvent) { ResourceId partial = GetResID(RerecordCmdBuf(cmdIds[c])); RDCDEBUG("Queue Submit partial replay of %llu at %u, using %llu", cmdIds[c], eid, partial); trimmedCmdIds.push_back(partial); trimmedCmds.push_back(Unwrap(RerecordCmdBuf(cmdIds[c]))); } else if(m_LastEventID >= end) { RDCDEBUG("Queue Submit full replay %llu", cmdIds[c]); trimmedCmdIds.push_back(cmdIds[c]); trimmedCmds.push_back(Unwrap(GetResourceManager()->GetLiveHandle<VkCommandBuffer>(cmdIds[c]))); } else { RDCDEBUG("Queue not submitting %llu", cmdIds[c]); } // 1 extra to account for the virtual end command buffer label (begin is accounted for above) eid += 1+m_BakedCmdBufferInfo[cmdIds[c]].eventCount; } RDCASSERT(trimmedCmds.size() > 0); submitInfo.commandBufferCount = (uint32_t)trimmedCmds.size(); submitInfo.pCommandBuffers = &trimmedCmds[0]; ObjDisp(queue)->QueueSubmit(Unwrap(queue), 1, &submitInfo, Unwrap(fence)); for(uint32_t i=0; i < trimmedCmdIds.size(); i++) { ResourceId cmd = trimmedCmdIds[i]; GetResourceManager()->ApplyBarriers(m_BakedCmdBufferInfo[cmd].imgbarriers, m_ImageLayouts); } } else { RDCDEBUG("Queue Submit full replay %u >= %u", m_LastEventID, m_RootEventID); ObjDisp(queue)->QueueSubmit(Unwrap(queue), 1, &submitInfo, Unwrap(fence)); for(uint32_t i=0; i < numCmds; i++) { ResourceId cmd = GetResourceManager()->GetLiveID(cmdIds[i]); GetResourceManager()->ApplyBarriers(m_BakedCmdBufferInfo[cmd].imgbarriers, m_ImageLayouts); } } } SAFE_DELETE_ARRAY(cmds); return true; }
//! 保存个人房屋内的物品信息 bool CRsDupRgn::SaveDupRgnObj(const CGUID& ownerID, map<CGUID,CDBRgnGoods*>& goodsGroup, _ConnectionPtr& cn) { if(cn == NULL) { AddLogText(CStringReading::LoadString(IDS_DBS_RSDUPRGN,STR_DBS_DUPRGN_CNPTRNULL)); return false; } _RecordsetPtr rs; // 比物品个数多分配2048字节 char *sql = new char[1024 * (goodsGroup.size()+2)]; string iniName = "phrgnobj"; string tableName = "CSL_DUPRGN_GOODS"; try { TESTHR(CreateRs(rs)); char szGUID[128]; ownerID.tostring(szGUID); sprintf(sql, "DELETE FROM CSL_DUPRGN_GOODS WHERE DupRgnGUID='%s'", szGUID); // 先删除该个人房屋的成员 if(!ExecuteCn(sql, cn)) { PrintErr(CStringReading::LoadString(IDS_DBS_RSDUPRGN,STR_DBS_DUPRGN_DELRGNOBJFAIL)); return false; } // 清空sql语句 memset(sql, 0, 1024 * (goodsGroup.size()+2)); // 生成语句头 strcpy(sql, "INSERT INTO CSL_DUPRGN_GOODS("); CDataEntityManager* pObjAttrDef = NULL; std::map<string, CDataEntityManager*>::iterator itr = GetGame()->GetDBEntityManager()->GetObjAttrDef().find(iniName); if(itr != GetGame()->GetDBEntityManager()->GetObjAttrDef().end()) pObjAttrDef = itr->second; if(!pObjAttrDef) return false; //! 生成语句身 CDataEntityManager::EntityPropertyMapItr attrItr = pObjAttrDef->GetEntityPropertyMap().begin(); for (; attrItr != pObjAttrDef->GetEntityPropertyMap().end(); attrItr++) { if(attrItr->second->GetDBTableName() == tableName) { CWrapDataObject* wdo = attrItr->second->GetDataObject(0); if(wdo) { // 添加属性字段名 strcat(sql, attrItr->second->GetEPName().c_str()); strcat(sql, ","); } } } long sqlLen = strlen(sql); sql[sqlLen-1] = '\0'; strcat(sql, ") select "); map<CGUID,CDBRgnGoods*>::iterator goodsItr = goodsGroup.begin(); for(; goodsItr != goodsGroup.end(); goodsItr++) { //! 生成语句身 attrItr = pObjAttrDef->GetEntityPropertyMap().begin(); for (; attrItr != pObjAttrDef->GetEntityPropertyMap().end(); attrItr++) { if(attrItr->second) { if(attrItr->second->GetDBTableName() == tableName) { // 添加属性字段值 CEntityProperty* ep = (goodsItr->second)->GetDataEntityManager().GetEntityProperty(attrItr->second->GetEPName()); if(ep) { if(ep->GetDBTableName() == tableName) { switch(ep->GetDataType()) { case DATA_OBJECT_TIME: { char szTimeValue[2048]; DWORD timeValue[6] = {0}; ep->GetBufAttr(0, (void*)&timeValue[0], sizeof(DWORD)*6); sprintf(szTimeValue, "%d-%d-%d %d:%d:%d", timeValue[0], timeValue[1], timeValue[2], timeValue[3], timeValue[4], timeValue[5]); //rs->PutCollect((*epItr).c_str(), szTimeValue); strcat(sql, "'"); strcat(sql, szTimeValue); strcat(sql, "',"); } break; case DATA_OBJECT_STRING: { //rs->PutCollect((*epItr).c_str(), ); strcat(sql, "'"); const char* pStr = ep->GetStringAttr(0); if(pStr) strcat(sql, pStr); else strcat(sql, ""); strcat(sql, "',"); } break; case DATA_OBJECT_BUFFER: { //SaveBufferField((*goodsItr), (*epItr).c_str(), rs); } break; case DATA_OBJECT_GUID: { CGUID tGUID; ep->GetGuidAttr(0, tGUID); char szGuid[128]; tGUID.tostring(szGuid); //rs->PutCollect((*epItr).c_str(), szGuid); strcat(sql, "'"); strcat(sql, szGuid); strcat(sql, "',"); } break; case DATA_OBJECT_BOOL: case DATA_OBJECT_CHAR: case DATA_OBJECT_BYTE: { //rs->PutCollect((*epItr).c_str(), (BYTE)ep->GetLongAttr(0)); char value[32]; memset(value, 0, sizeof(value)); itoa((BYTE)ep->GetLongAttr(0), value, 10); strcat(sql, value); strcat(sql, ","); } break; case DATA_OBJECT_SHORT: case DATA_OBJECT_WORD: case DATA_OBJECT_USHORT: { //rs->PutCollect((*epItr).c_str(), (WORD)ep->GetLongAttr(0)); char value[32]; memset(value, 0, sizeof(value)); itoa((WORD)ep->GetLongAttr(0), value, 10); strcat(sql, value); strcat(sql, ","); } break; case DATA_OBJECT_FLOAT: case DATA_OBJECT_LONG: case DATA_OBJECT_ULONG: case DATA_OBJECT_DWORD: { //rs->PutCollect((*epItr).c_str(), (DWORD)ep->GetLongAttr(0)); char value[32]; memset(value, 0, sizeof(value)); itoa((DWORD)ep->GetLongAttr(0), value, 10); strcat(sql, value); strcat(sql, ","); } break; } } } } } } sqlLen = strlen(sql); sql[sqlLen-1] = '\0'; strcat(sql, " union all select "); } sqlLen = strlen(sql); sql[sqlLen-17] = '\0'; TESTHR(ExecuteCn(sql, cn)); SAFE_DELETE_ARRAY(sql); return true; } catch (_com_error &e) { SAFE_DELETE_ARRAY(sql); ReleaseRs(rs); PrintErr(CStringReading::LoadString(IDS_DBS_RSDUPRGN,STR_DBS_DUPRGN_SAVERGNGOODSFAIL), e); return false; } SAFE_DELETE_ARRAY(sql); return false; }
AnimationValue::~AnimationValue() { SAFE_DELETE_ARRAY(_value); }
AppStatus::~AppStatus(void) { pC=0; SAFE_DELETE_ARRAY(pItems); }
//暗号化ファイルの解析 CIPHER_RESULT PmCipher::ParseCipherFile(const char *cipher_path) { //戻り値・・・ステータス //第1引数・・・暗号化ファイルのパス //ファイルプロパティ文字列 char ch, str_size[10], *str_index, key_word[CIPHER_KEY_WORD_SIZE], cipher_key_word[CIPHER_KEY_WORD_SIZE]; //戻り値 CIPHER_RESULT cr = CIPHER_OK; //プロパティ一覧の解放(未解放時のための処理) SAFE_DELETE(m_property_list); //復号準備フラグOFF m_decrypt_init = false; //圧縮フラグOFF m_compress = false; //ファイルが存在しかつ、ディレクトリ属性ではない場合に処理開始 if(PathFileExists(cipher_path) && !(GetFileAttributes(cipher_path) & FILE_ATTRIBUTE_DIRECTORY)) { m_cipher_path = string(cipher_path); //暗号化ファイルのオープン m_fs_decrypt.open(cipher_path, ios::in|ios::binary); //キーワード読み込み m_fs_decrypt.read(cipher_key_word, CIPHER_KEY_WORD_SIZE); m_blow_fish.Decode((unsigned char *)cipher_key_word, (unsigned char *)key_word, CIPHER_KEY_WORD_SIZE); key_word[7] = '\0'; if(strcmp(key_word, CIPHER_KEY_WORD)) { DecryptEnd(); return CIPHER_ERR_INVALID_FILE; } m_fs_decrypt.get(ch); //圧縮フラグ読み込み if(ch == '0') { m_compress = false; } else { m_compress = true; } //プロパティ一覧ファイルの元サイズ読み込み m_fs_decrypt.read(str_size, 10); m_current_source_size = AlphaToLong(str_size, 10); //プロパティ一覧ファイルの圧縮サイズ読み込み m_fs_decrypt.read(str_size, 10); m_current_compress_size = AlphaToLong(str_size, 10); //プロパティ一覧ファイルの暗号化サイズ読み込み m_fs_decrypt.read(str_size, 10); m_cipher_index_size = AlphaToLong(str_size, 10); m_current_cipher_size = m_cipher_index_size; m_fs_decrypt.read(str_size, 10); //平文受け取りバッファ char *buf; //サイズ等 unsigned int size, buf_size, j; PmCipherProperty *cipher_property; m_total_buf_size = 0ul; m_total_decomp_buf_size = 0ul; m_decrypt_init = true; //ZLIBストリーム初期化 if(m_compress) { m_z.zalloc = Z_NULL; m_z.zfree = Z_NULL; m_z.opaque = Z_NULL; if (inflateInit(&m_z) != Z_OK) { DecryptEnd(); return CIPHER_ERR_INVALID_FILE; } m_z.avail_in = 0; m_z.avail_out = (unsigned int)(min(CIPHER_BUF_SIZE, m_current_source_size - m_total_buf_size)); m_z.next_out = m_output_buf; } CIPHER_RESULT dec_cr; buf_size = 0; str_index = new char[m_current_source_size]; //暗号化プロパティ一覧の復号完了までループ do { dec_cr = Decrypt(&buf, &size); memcpy(str_index + buf_size, buf, size); buf_size += size; } while(dec_cr == CIPHER_DEC_NEXT); char str_path[MAX_PATH]; //プロパティ一覧の生成 m_property_list = new PmCipherPropertyList(); buf_size = 0; //ルートパスの取得 j = 0; ZeroMemory(str_path, MAX_PATH); for(j = 0; buf_size + j < m_current_source_size && j < MAX_PATH; j++) { if(str_index[buf_size + j] == '\n') { memcpy(str_path, str_index + buf_size, j); m_root_path = string(str_path); buf_size += j + 1; break; } } //プロパティ一覧文字列の解析 while(dec_cr == CIPHER_DEC_FINISH && buf_size < m_current_source_size) { cipher_property = new PmCipherProperty(); //ファイル位置の取得 cipher_property->SetOffset(AlphaToLong(str_index + buf_size, 10)); buf_size += 10; //元ファイルサイズの取得 cipher_property->SetSourceSize(AlphaToLong(str_index + buf_size, 10)); buf_size += 10; //圧縮ファイルサイズの取得 cipher_property->SetCompressSize(AlphaToLong(str_index + buf_size, 10)); buf_size += 10; //暗号化ファイルサイズの取得 cipher_property->SetCipherSize(AlphaToLong(str_index + buf_size, 10)); buf_size += 10; //ファイルパスの取得 j = 0; ZeroMemory(str_path, MAX_PATH); for(j = 0; buf_size + j < m_current_source_size && j < MAX_PATH; j++) { if(str_index[buf_size + j] == '\n') { memcpy(str_path, str_index + buf_size, j); cipher_property->SetPath(string(str_path)); buf_size += j + 1; break; } } //プロパティをプロパティ一覧に追加 m_property_list->AddProperty(cipher_property); } //バッファメモリの解放 SAFE_DELETE_ARRAY(str_index); DecryptEnd(); } //ファイルが見つからないまたは、ディレクトリの場合エラー終了 else { cr = CIPHER_ERR_FILE_NOT_FOUND; } return cr; }
// using the supplied font, build up a quad for each character in the string // and assemble the quads into a vertex buffer ready for drawing/memcpy //-------------------------------------------------------------------------------- void CPUTText::Recalculate() { SAFE_DELETE_ARRAY(mpMirrorBuffer); mNumCharsInString = (int) mStaticText.size(); mpMirrorBuffer = new CPUTGUIVertex[(mNumCharsInString+1)*6]; bool Enabled = false; if(CPUT_CONTROL_ACTIVE == mControlState) { Enabled = true; } // walk each character and build a quad from it float characterPosition=0; for(int ii=0; ii<mNumCharsInString; ii++) { // todo: unsafe cast from wchar_t to char! Some other way??? char character = (char) mStaticText[ii]; float3 UV1, UV2; CPUT_SIZE size = mpFont->GetGlyphSize(character); mpFont->GetGlyphUVS(character, Enabled, UV1, UV2); if('\t'!=character) { AddQuadIntoMirrorBuffer(mpMirrorBuffer, ii*6, (float)mPosition.x+characterPosition, (float)mPosition.y, (float)size.width, (float)size.height, UV1, UV2); } else { // calculate tab width = # pixels to get to next tabstop // Tabs are relative from BEGINNNING of the string, not absolute based on x-position of string. So in order for columns to line // up, you need the starts of the strings to line up too. // If you want 'absolute' x alignment behavior, use this: //size.width = size.width - ((mPosition.x+characterPosition) % size.width); // simply skip the amount of space indicated in the font's tab slot int CurrentPositionForNextGlyph = (int) characterPosition; size.width = size.width - (CurrentPositionForNextGlyph % size.width); AddQuadIntoMirrorBuffer(mpMirrorBuffer, ii*6, (float)mPosition.x+characterPosition, (float)mPosition.y, (float)size.width, (float)size.height, UV1, UV2); } // store the max height of the string mQuadSize.height = max(mQuadSize.height, size.height); // step to next X location for next character characterPosition+=size.width; } // store the total width of the string mQuadSize.width = (int)characterPosition; // width of string in pixels // tell gui system this control image is now dirty // and needs to rebuild it's draw list CPUTGuiControllerDX11::GetController()->ControlIsDirty(); // position or size may move - force a recalculation of this control's location // if it is managed by the auto-arrange function if(this->IsAutoArranged()) { CPUTGuiControllerDX11::GetController()->Resize(); } }
bool CProactorUDPHandler::SendMessage(const char* pMessage, uint32 u4Len, const char* szIP, int nPort, bool blHead, uint16 u2CommandID) { ACE_Time_Value m_tvBegin = ACE_OS::gettimeofday(); ACE_INET_Addr AddrRemote; int nErr = AddrRemote.set(nPort, szIP); if(nErr != 0) { OUR_DEBUG((LM_INFO, "[CProactorUDPHandler::SendMessage]set_address error[%d].\n", errno)); SAFE_DELETE(pMessage); return false; } //如果需要拼接包头,则拼接包头 if(blHead == true) { CPacketParse PacketParse; ACE_Message_Block* pMbData = NULL; uint32 u4SendLength = PacketParse.MakePacketLength(0, u4Len); pMbData = App_MessageBlockManager::instance()->Create(u4SendLength); if(NULL == pMbData) { SAFE_DELETE(pMessage); return false; } PacketParse.MakePacket(0, pMessage, u4Len, pMbData); uint32 u4DataLen = (uint32)pMbData->length(); int nSize = (int)m_skRemote.send(pMbData->rd_ptr(), u4DataLen, AddrRemote); if((uint32)nSize == u4DataLen) { m_atvOutput = ACE_OS::gettimeofday(); m_u4SendSize += u4DataLen; m_u4SendPacketCount++; SAFE_DELETE_ARRAY(pMessage); //统计发送信息 ACE_Time_Value tvInterval = ACE_OS::gettimeofday() - m_tvBegin; uint32 u4SendCost = (uint32)(tvInterval.msec()); m_CommandAccount.SaveCommandData(u2CommandID, u4SendCost, PACKET_UDP, u4Len, u4DataLen, COMMAND_TYPE_OUT); //释放发送体 pMbData->release(); return true; } else { OUR_DEBUG((LM_ERROR, "[CProactorUDPHandler::SendMessage]send error(%d).\n", errno)); SAFE_DELETE_ARRAY(pMessage); //释放发送体 pMbData->release(); return false; } } else { int nSize = (int)m_skRemote.send(pMessage, u4Len, AddrRemote); if((uint32)nSize == u4Len) { m_atvOutput = ACE_OS::gettimeofday(); m_u4SendSize += u4Len; m_u4SendPacketCount++; SAFE_DELETE_ARRAY(pMessage); //统计发送信息 ACE_Time_Value tvInterval = ACE_OS::gettimeofday() - m_tvBegin; uint32 u4SendCost = (uint32)(tvInterval.msec()); m_CommandAccount.SaveCommandData(u2CommandID, u4SendCost, PACKET_UDP, u4Len, u4Len, COMMAND_TYPE_OUT); return true; } else { OUR_DEBUG((LM_ERROR, "[CProactorUDPHandler::SendMessage]send error(%d).\n", errno)); SAFE_DELETE_ARRAY(pMessage); return false; } } }
void XGraphicsOpenGL::UnlockBackBufferPtr() { SAFE_DELETE_ARRAY( m_pLockBackBuffer ); }
// Load and register all the resources needed by the GUI system //----------------------------------------------------------------------------- CPUTResult CPUTGuiControllerDX11::RegisterGUIResources(ID3D11DeviceContext *pImmediateContext, cString VertexShaderFilename, cString PixelShaderFilename, cString RenderStateFile, cString DefaultFontFilename, cString ControlAtlasTexture) { if(NULL==pImmediateContext) { return CPUT_ERROR_INVALID_PARAMETER; } CPUTResult result; HRESULT hr; ID3D11Device *pD3dDevice = NULL; CPUTOSServices *pServices = NULL; CPUTAssetLibraryDX11 *pAssetLibrary = NULL; cString ErrorMessage; // Get the services/resource pointers we need pServices = CPUTOSServices::GetOSServices(); pImmediateContext->GetDevice(&pD3dDevice); pAssetLibrary = (CPUTAssetLibraryDX11*)CPUTAssetLibraryDX11::GetAssetLibrary(); // Get the resource directory cString ResourceDirectory; CPUTGuiControllerDX11::GetController()->GetResourceDirectory(ResourceDirectory); // 1. Load the renderstate configuration for the GUI system mpGUIRenderStateBlock = (CPUTRenderStateBlockDX11*) pAssetLibrary->GetRenderStateBlock(ResourceDirectory+RenderStateFile); ASSERT(mpGUIRenderStateBlock, _L("Error loading the render state file (.rs) needed for the CPUT GUI system")); // 2. Store the shader path from AssetLibrary, change it to OUR resource directory cString OriginalAssetLibraryDirectory = pAssetLibrary->GetShaderDirectory(); pAssetLibrary->SetShaderDirectoryName(ResourceDirectory); // 3. load the shaders for gui drawing // Load the GUI Vertex Shader cString FullPath, FinalPath; FullPath = mResourceDirectory + VertexShaderFilename; pServices->ResolveAbsolutePathAndFilename(FullPath, &FinalPath); result = pAssetLibrary->GetVertexShader(FinalPath, pD3dDevice, _L("VS"), _L("vs_4_0"), &mpGUIVertexShader, true); CPUTSetDebugName( mpGUIVertexShader->GetNativeVertexShader(), _L("GUIVertexShader")); if(CPUTFAILED(result)) { ASSERT(CPUTSUCCESS(result), _L("Error loading the vertex shader needed for the CPUT GUI system.")); } ID3DBlob *pVertexShaderBlob = mpGUIVertexShader->GetBlob(); // Load the GUI Pixel Shader FullPath = mResourceDirectory + PixelShaderFilename; pServices->ResolveAbsolutePathAndFilename(FullPath, &FinalPath); result = pAssetLibrary->GetPixelShader(FinalPath, pD3dDevice, _L("PS"), _L("ps_4_0"), &mpGUIPixelShader, true); CPUTSetDebugName( mpGUIPixelShader->GetNativePixelShader(), _L("GUIPixelShader")); if(CPUTFAILED(result)) { ASSERT(CPUTSUCCESS(result), _L("Error loading the pixel shader needed for the CPUT GUI system.")); } // Restore the previous shader directory pAssetLibrary->SetShaderDirectoryName(OriginalAssetLibraryDirectory); // 4. Create the vertex layout description for all the GUI controls we'll draw // set vertex shader as active so we can configure it ID3D11VertexShader *pVertexShader = mpGUIVertexShader->GetNativeVertexShader(); pImmediateContext->VSSetShader( pVertexShader, NULL, 0 ); D3D11_INPUT_ELEMENT_DESC layout[] = { { "POSITION", 0, DXGI_FORMAT_R32G32B32_FLOAT, 0, 0, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "TEXCOORD", 0, DXGI_FORMAT_R32G32_FLOAT, 0, 12, D3D11_INPUT_PER_VERTEX_DATA, 0 }, { "COLOR", 0, DXGI_FORMAT_R32G32B32A32_FLOAT, 0, 20, D3D11_INPUT_PER_VERTEX_DATA, 0 }, }; UINT numElements = ARRAYSIZE( layout ); // Create the input layout hr = pD3dDevice->CreateInputLayout( layout, numElements, pVertexShaderBlob->GetBufferPointer(), pVertexShaderBlob->GetBufferSize(), &mpVertexLayout ); ASSERT( SUCCEEDED(hr), _L("Error creating CPUT GUI system input layout" )); CPUTSetDebugName( mpVertexLayout, _L("CPUT GUI InputLayout object")); // 5. create the vertex shader constant buffer pointers D3D11_BUFFER_DESC bd; ZeroMemory( &bd, sizeof(bd) ); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof(GUIConstantBufferVS); bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = 0; hr = pD3dDevice->CreateBuffer( &bd, NULL, &mpConstantBufferVS ); ASSERT( SUCCEEDED(hr), _L("Error creating constant buffer VS" )); CPUTSetDebugName( mpConstantBufferVS, _L("GUI ConstantBuffer")); // Set the texture directory for loading the control texture atlas pAssetLibrary->SetTextureDirectoryName(ResourceDirectory); // load the control atlas mpControlTextureAtlas = (CPUTTextureDX11*) pAssetLibrary->GetTexture(ControlAtlasTexture); if(NULL==mpControlTextureAtlas) { return CPUT_TEXTURE_LOAD_ERROR; } mpControlTextureAtlasView = mpControlTextureAtlas->GetShaderResourceView(); mpControlTextureAtlasView->AddRef(); // restore the asset library's texture directory pAssetLibrary->SetTextureDirectoryName(OriginalAssetLibraryDirectory); // 6. Load the font atlas // store the existing asset library font directory OriginalAssetLibraryDirectory = pAssetLibrary->GetFontDirectory(); // set font directory to the resource directory pAssetLibrary->SetFontDirectoryName(ResourceDirectory); mpFont = (CPUTFontDX11*) pAssetLibrary->GetFont(DefaultFontFilename); if(NULL==mpFont) { return CPUT_TEXTURE_LOAD_ERROR; } mpTextTextureAtlas = mpFont->GetAtlasTexture(); mpTextTextureAtlas->AddRef(); mpTextTextureAtlasView = mpFont->GetAtlasTextureResourceView(); mpTextTextureAtlasView->AddRef(); // restore the asset library's font directory pAssetLibrary->SetTextureDirectoryName(OriginalAssetLibraryDirectory); // 7. Set up the DirectX uber-buffers that the controls draw into int maxSize = max(CPUT_GUI_BUFFER_STRING_SIZE, CPUT_GUI_BUFFER_SIZE); maxSize = max(maxSize, CPUT_GUI_VERTEX_BUFFER_SIZE); maxSize *= sizeof( CPUTGUIVertex ); char *pZeroedBuffer= new char[maxSize]; memset(pZeroedBuffer, 0, maxSize); // set up buffer description ZeroMemory( &bd, sizeof(bd) ); bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = sizeof( CPUTGUIVertex ) * CPUT_GUI_VERTEX_BUFFER_SIZE; //mUberBufferIndex; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; // initialization data (all 0's for now) D3D11_SUBRESOURCE_DATA InitData; ZeroMemory( &InitData, sizeof(InitData) ); InitData.pSysMem = mpMirrorBuffer; // mpUberBuffer SAFE_RELEASE(mpUberBuffer); hr = pD3dDevice->CreateBuffer( &bd, &InitData, &mpUberBuffer ); ASSERT( !FAILED( hr ), _L("CPUT GUI FPS counter buffer creation failure")); CPUTSetDebugName(mpUberBuffer, _L("CPUT GUI: Control's main vertex buffer")); // mpTextUberBuffer bd.ByteWidth = sizeof( CPUTGUIVertex ) * CPUT_GUI_BUFFER_STRING_SIZE; hr = pD3dDevice->CreateBuffer( &bd, &InitData, &mpTextUberBuffer ); ASSERT( !FAILED( hr ), _L("CPUT GUI FPS counter buffer creation failure")); CPUTSetDebugName(mpTextUberBuffer, _L("CPUT GUI: control text vertex buffer")); // mpFocusedControlBuffer bd.ByteWidth = sizeof( CPUTGUIVertex ) * CPUT_GUI_VERTEX_BUFFER_SIZE; hr = pD3dDevice->CreateBuffer( &bd, &InitData, &mpFocusedControlBuffer ); ASSERT( !FAILED( hr ), _L("CPUT GUI FPS counter buffer creation failure")); CPUTSetDebugName(mpFocusedControlBuffer, _L("CPUT GUI: focused control images vertex buffer")); // mpFocusedControlTextBuffer bd.ByteWidth = sizeof( CPUTGUIVertex ) * CPUT_GUI_BUFFER_STRING_SIZE; //mFocusedControlTextBufferIndex; hr = pD3dDevice->CreateBuffer( &bd, &InitData, &mpFocusedControlTextBuffer ); ASSERT( !FAILED( hr ), _L("CPUT GUI FPS counter buffer creation failure")); CPUTSetDebugName(mpFocusedControlTextBuffer, _L("CPUT GUI: focused control text vertex buffer")); // mpFPSDirectXBuffer bd.ByteWidth = sizeof( CPUTGUIVertex ) * CPUT_GUI_BUFFER_STRING_SIZE; hr = pD3dDevice->CreateBuffer( &bd, &InitData, &mpFPSDirectXBuffer ); ASSERT( !FAILED( hr ), _L("CPUT GUI FPS counter buffer creation failure")); CPUTSetDebugName(mpFPSDirectXBuffer, _L("CPUT GUI: FPS display text")); // no longer need the device - release it. SAFE_RELEASE(pD3dDevice); SAFE_DELETE_ARRAY(pZeroedBuffer); // 8. Register all GUI sub-resources // Walk all the controls/fonts and have them register all their required static resources // Returning errors if you couldn't find your resources result = CPUTText::RegisterStaticResources(); if(CPUTFAILED(result)) { return result; } result = CPUTButton::RegisterStaticResources(); if(CPUTFAILED(result)) { return result; } result = CPUTCheckbox::RegisterStaticResources(); if(CPUTFAILED(result)) { return result; } result = CPUTSlider::RegisterStaticResources(); if(CPUTFAILED(result)) { return result; } result = CPUTDropdown::RegisterStaticResources(); if(CPUTFAILED(result)) { return result; } // create the FPS CPUTText object for drawing FPS mpFPSCounter = new CPUTText(_L("FPS:"), ID_CPUT_GUI_FPS_COUNTER, mpFont); mpFPSCounter->SetAutoArranged(false); mpFPSCounter->SetPosition(0,0); // start the timer mpFPSTimer->StartTimer(); // done return CPUT_SUCCESS; }
/** @brief @param sizeTex 목표 크기 */ void XGraphicsOpenGL::ResizeTexture( ID idTex, const XE::POINT& sizeTexPrev, const XE::POINT& sizeTexNew, GLenum glType, GLenum glFormatSurface ) { // FBO생성 GLuint fbo; glGenFramebuffers( 1, &fbo ); glBindFramebuffer( GL_FRAMEBUFFER, fbo ); // idTex를 어태치 glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, idTex, 0 ); _CHECK_GL_ERROR(); GLenum status = glCheckFramebufferStatus( GL_FRAMEBUFFER ); if( status != GL_FRAMEBUFFER_COMPLETE ) { XTRACE( "fbo status=%d", status ); return; } // 임시 텍스쳐버퍼 생성 GLuint glTexTemp; glGenTextures( 1, &glTexTemp ); _CHECK_GL_ERROR(); glBindTexture( GL_TEXTURE_2D, glTexTemp ); _CHECK_GL_ERROR(); auto glFormatMem = glFormatSurface; // 둘은 반드시 일치해야한다., glTexImage2D( GL_TEXTURE_2D, 0, glFormatSurface, // internal format sizeTexPrev.w, sizeTexPrev.h, 0, glFormatMem, // pImgSrc의 포맷 glType, nullptr ); _CHECK_GL_ERROR(); // 어태치된 소스측 텍스쳐로부터 임시버퍼로 카피 glCopyTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, 0, 0, sizeTexPrev.w, sizeTexPrev.h ); _CHECK_GL_ERROR(); // 소스측 어태치 해제 glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, 0, 0 ); _CHECK_GL_ERROR(); // 임시버퍼를 FBO에 어태치 glFramebufferTexture2D( GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, glTexTemp, 0 ); _CHECK_GL_ERROR(); status = glCheckFramebufferStatus( GL_FRAMEBUFFER ); if( status != GL_FRAMEBUFFER_COMPLETE ) { XTRACE( "fbo status=%d", status ); return; } // 리사이징 XGraphicsOpenGL::sBindTexture( idTex ); _CHECK_GL_ERROR(); auto pClearBuff = new DWORD[ (int)sizeTexNew.Size() ]; memset( pClearBuff, 0, sizeof(DWORD) * (int)sizeTexNew.Size() ); glTexImage2D( GL_TEXTURE_2D, 0, glFormatSurface, // internal format sizeTexNew.w, sizeTexNew.h, 0, glFormatMem, // pImgSrc의 포맷 glType, pClearBuff /*nullptr*/ ); _CHECK_GL_ERROR(); SAFE_DELETE_ARRAY( pClearBuff ); // 어태치된 임시버퍼 텍스쳐로부터 리사이징된 원래텍스쳐로 카피 glCopyTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, 0, 0, sizeTexPrev.w, sizeTexPrev.h ); _CHECK_GL_ERROR(); // 임시버퍼 삭제 glDeleteTextures( 1, &glTexTemp ); glTexTemp = 0; _CHECK_GL_ERROR(); glDeleteFramebuffers( 1, &fbo ); _CHECK_GL_ERROR(); }
//----[ destroy ]------------------------------------------------------------ void ClientMapData::destroy() { SAFE_DELETE_ARRAY(unique_locations_); SAFE_DELETE_ARRAY(locations_); zero(); }
void VulkanDebugManager::CopyDepthArrayToTex2DMS(VkImage destMS, VkImage srcArray, VkExtent3D extent, uint32_t layers, uint32_t samples, VkFormat fmt) { VkImageAspectFlags aspectFlags = VK_IMAGE_ASPECT_DEPTH_BIT; int pipeIndex = 0; switch(fmt) { case VK_FORMAT_D16_UNORM: pipeIndex = 0; break; case VK_FORMAT_D16_UNORM_S8_UINT: pipeIndex = 1; aspectFlags |= VK_IMAGE_ASPECT_STENCIL_BIT; break; case VK_FORMAT_X8_D24_UNORM_PACK32: pipeIndex = 2; break; case VK_FORMAT_D24_UNORM_S8_UINT: pipeIndex = 3; aspectFlags |= VK_IMAGE_ASPECT_STENCIL_BIT; break; case VK_FORMAT_D32_SFLOAT: pipeIndex = 4; break; case VK_FORMAT_D32_SFLOAT_S8_UINT: pipeIndex = 5; aspectFlags |= VK_IMAGE_ASPECT_STENCIL_BIT; break; default: RDCERR("Unexpected depth format: %d", fmt); return; } // 0-based from 2x MSAA uint32_t sampleIndex = SampleIndex((VkSampleCountFlagBits)samples) - 1; if(sampleIndex >= ARRAY_COUNT(m_DepthArray2MSPipe[0])) { RDCERR("Unsupported sample count %u", samples); return; } VkPipeline pipe = m_DepthArray2MSPipe[pipeIndex][sampleIndex]; if(pipe == VK_NULL_HANDLE) return; VkDevice dev = m_Device; VkResult vkr = VK_SUCCESS; VkImageView srcDepthView = VK_NULL_HANDLE, srcStencilView = VK_NULL_HANDLE; VkImageView *destView = new VkImageView[layers]; VkImageViewCreateInfo viewInfo = { VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO, NULL, 0, srcArray, VK_IMAGE_VIEW_TYPE_2D_ARRAY, fmt, {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_ZERO, VK_COMPONENT_SWIZZLE_ZERO, VK_COMPONENT_SWIZZLE_ZERO}, { VK_IMAGE_ASPECT_DEPTH_BIT, 0, VK_REMAINING_MIP_LEVELS, 0, VK_REMAINING_ARRAY_LAYERS, }, }; vkr = ObjDisp(dev)->CreateImageView(Unwrap(dev), &viewInfo, NULL, &srcDepthView); RDCASSERTEQUAL(vkr, VK_SUCCESS); if(aspectFlags & VK_IMAGE_ASPECT_STENCIL_BIT) { viewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT; vkr = ObjDisp(dev)->CreateImageView(Unwrap(dev), &viewInfo, NULL, &srcStencilView); RDCASSERTEQUAL(vkr, VK_SUCCESS); } viewInfo.subresourceRange.aspectMask = aspectFlags; viewInfo.image = destMS; viewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY; viewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY; viewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY; viewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY; for(uint32_t i = 0; i < layers; i++) { viewInfo.subresourceRange.baseArrayLayer = i; viewInfo.subresourceRange.layerCount = 1; vkr = ObjDisp(dev)->CreateImageView(Unwrap(dev), &viewInfo, NULL, &destView[i]); RDCASSERTEQUAL(vkr, VK_SUCCESS); } VkDescriptorImageInfo srcdesc[2]; srcdesc[0].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; srcdesc[0].imageView = srcDepthView; srcdesc[0].sampler = Unwrap(m_ArrayMSSampler); // not used - we use texelFetch srcdesc[1].imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; srcdesc[1].imageView = srcStencilView; srcdesc[1].sampler = Unwrap(m_ArrayMSSampler); // not used - we use texelFetch VkWriteDescriptorSet writeSet[] = { {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, Unwrap(m_ArrayMSDescSet), 0, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &srcdesc[0], NULL, NULL}, {VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET, NULL, Unwrap(m_ArrayMSDescSet), 1, 0, 1, VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER, &srcdesc[1], NULL, NULL}, }; if(aspectFlags & VK_IMAGE_ASPECT_STENCIL_BIT) ObjDisp(dev)->UpdateDescriptorSets(Unwrap(dev), 2, writeSet, 0, NULL); else ObjDisp(dev)->UpdateDescriptorSets(Unwrap(dev), 1, writeSet, 0, NULL); // create a bespoke framebuffer and renderpass for rendering VkAttachmentDescription attDesc = {0, fmt, (VkSampleCountFlagBits)samples, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_STORE, VK_ATTACHMENT_LOAD_OP_CLEAR, VK_ATTACHMENT_STORE_OP_STORE, VK_IMAGE_LAYOUT_GENERAL, VK_IMAGE_LAYOUT_GENERAL}; VkAttachmentReference attRef = {0, VK_IMAGE_LAYOUT_GENERAL}; VkSubpassDescription sub = {}; sub.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS; sub.pDepthStencilAttachment = &attRef; VkRenderPassCreateInfo rpinfo = { VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO, NULL, 0, 1, &attDesc, 1, &sub, 0, NULL, // dependencies }; VkRenderPass rp = VK_NULL_HANDLE; ObjDisp(dev)->CreateRenderPass(Unwrap(dev), &rpinfo, NULL, &rp); VkFramebufferCreateInfo fbinfo = { VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO, NULL, 0, rp, 1, NULL, extent.width, extent.height, 1, }; VkFramebuffer *fb = new VkFramebuffer[layers]; for(uint32_t i = 0; i < layers; i++) { fbinfo.pAttachments = destView + i; vkr = ObjDisp(dev)->CreateFramebuffer(Unwrap(dev), &fbinfo, NULL, &fb[i]); RDCASSERTEQUAL(vkr, VK_SUCCESS); } VkCommandBuffer cmd = m_pDriver->GetNextCmd(); VkCommandBufferBeginInfo beginInfo = {VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO, NULL, VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT}; ObjDisp(cmd)->BeginCommandBuffer(Unwrap(cmd), &beginInfo); VkClearValue clearval = {}; VkRenderPassBeginInfo rpbegin = { VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO, NULL, rp, VK_NULL_HANDLE, {{0, 0}, {extent.width, extent.height}}, 1, &clearval, }; uint32_t numStencil = 1; if(aspectFlags & VK_IMAGE_ASPECT_STENCIL_BIT) numStencil = 256; Vec4u params; params.x = samples; params.y = 0; // currentSample; for(uint32_t i = 0; i < layers; i++) { rpbegin.framebuffer = fb[i]; ObjDisp(cmd)->CmdBeginRenderPass(Unwrap(cmd), &rpbegin, VK_SUBPASS_CONTENTS_INLINE); ObjDisp(cmd)->CmdBindPipeline(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(pipe)); ObjDisp(cmd)->CmdBindDescriptorSets(Unwrap(cmd), VK_PIPELINE_BIND_POINT_GRAPHICS, Unwrap(m_ArrayMSPipeLayout), 0, 1, UnwrapPtr(m_ArrayMSDescSet), 0, NULL); VkViewport viewport = {0.0f, 0.0f, (float)extent.width, (float)extent.height, 0.0f, 1.0f}; ObjDisp(cmd)->CmdSetViewport(Unwrap(cmd), 0, 1, &viewport); params.z = i; // currentSlice; for(uint32_t s = 0; s < numStencil; s++) { params.w = numStencil == 1 ? 1000 : s; // currentStencil; ObjDisp(cmd)->CmdSetStencilReference(Unwrap(cmd), VK_STENCIL_FRONT_AND_BACK, s); ObjDisp(cmd)->CmdPushConstants(Unwrap(cmd), Unwrap(m_ArrayMSPipeLayout), VK_SHADER_STAGE_ALL, 0, sizeof(Vec4u), ¶ms); ObjDisp(cmd)->CmdDraw(Unwrap(cmd), 4, 1, 0, 0); } ObjDisp(cmd)->CmdEndRenderPass(Unwrap(cmd)); } ObjDisp(cmd)->EndCommandBuffer(Unwrap(cmd)); // submit cmds and wait for idle so we can readback m_pDriver->SubmitCmds(); m_pDriver->FlushQ(); for(uint32_t i = 0; i < layers; i++) ObjDisp(dev)->DestroyFramebuffer(Unwrap(dev), fb[i], NULL); ObjDisp(dev)->DestroyRenderPass(Unwrap(dev), rp, NULL); ObjDisp(dev)->DestroyImageView(Unwrap(dev), srcDepthView, NULL); if(srcStencilView != VK_NULL_HANDLE) ObjDisp(dev)->DestroyImageView(Unwrap(dev), srcStencilView, NULL); for(uint32_t i = 0; i < layers; i++) ObjDisp(dev)->DestroyImageView(Unwrap(dev), destView[i], NULL); SAFE_DELETE_ARRAY(destView); SAFE_DELETE_ARRAY(fb); }
/// Deallocate memory created in initialize void CvGrandStrategyAI::Uninit() { SAFE_DELETE_ARRAY(m_paiGrandStrategyPriority); SAFE_DELETE_ARRAY(m_eGuessOtherPlayerActiveGrandStrategy); SAFE_DELETE_ARRAY(m_eGuessOtherPlayerActiveGrandStrategyConfidence); }
// Destructor //----------------------------------------------------------------------------- CPUTGuiController::~CPUTGuiController() { SAFE_RELEASE(mpFont); SAFE_DELETE_ARRAY(mpMirrorBuffer); DeleteAllControls(); }
//------------------------------------------------------------------------------ CvAIGrandStrategyXMLEntry::~CvAIGrandStrategyXMLEntry(void) { SAFE_DELETE_ARRAY(m_piFlavorValue); SAFE_DELETE_ARRAY(m_piSpecializationBoost); SAFE_DELETE_ARRAY(m_piFlavorModValue); }
// -------------------------------------------------------------------------------- void CvArea::uninit() { SAFE_DELETE_ARRAY(m_paiNumResources); SAFE_DELETE_ARRAY(m_paiNumImprovements); }
//----------------------------------------------------------------------------- // Name: v::Open() // Desc: Opens a wave file for reading //----------------------------------------------------------------------------- HRESULT CHMWaveFile::Open( LPTSTR strFileName, WAVEFORMATEX* pwfx, DWORD dwFlags ) { HRESULT hr; m_dwFlags = dwFlags; m_bIsReadingFromMemory = FALSE; if( m_dwFlags == WAVEFILE_READ ) { if( strFileName == NULL ) return E_INVALIDARG; SAFE_DELETE_ARRAY( m_pwfx ); m_hmmio = mmioOpen( strFileName, NULL, MMIO_ALLOCBUF | MMIO_READ ); if( NULL == m_hmmio ) { HRSRC hResInfo; HGLOBAL hResData; DWORD dwSize; VOID* pvRes; // Loading it as a file failed, so try it as a resource if( NULL == ( hResInfo = FindResource( NULL, strFileName, TEXT("WAVE") ) ) ) { if( NULL == ( hResInfo = FindResource( NULL, strFileName, TEXT("WAV") ) ) ) // return DXTRACE_ERR_NOMSGBOX( TEXT("FindResource"), E_FAIL ); return -1; } if( NULL == ( hResData = LoadResource( NULL, hResInfo ) ) ) //return DXTRACE_ERR( TEXT("LoadResource"), E_FAIL ); return -1; if( 0 == ( dwSize = SizeofResource( NULL, hResInfo ) ) ) //return DXTRACE_ERR( TEXT("SizeofResource"), E_FAIL ); return -1; if( NULL == ( pvRes = LockResource( hResData ) ) ) //return DXTRACE_ERR( TEXT("LockResource"), E_FAIL ); return -1; CHAR* pData = new CHAR[ dwSize ]; memcpy( pData, pvRes, dwSize ); MMIOINFO mmioInfo; ZeroMemory( &mmioInfo, sizeof(mmioInfo) ); mmioInfo.fccIOProc = FOURCC_MEM; mmioInfo.cchBuffer = dwSize; mmioInfo.pchBuffer = (CHAR*) pData; m_hmmio = mmioOpen( NULL, &mmioInfo, MMIO_ALLOCBUF | MMIO_READ ); } if( FAILED( hr = ReadMMIO() ) ) { // ReadMMIO will fail if its an not a wave file mmioClose( m_hmmio, 0 ); //return DXTRACE_ERR_NOMSGBOX( TEXT("ReadMMIO"), hr ); return -1; } if( FAILED( hr = ResetFile() ) ) //return DXTRACE_ERR( TEXT("ResetFile"), hr ); return -1; // After the reset, the size of the wav file is m_ck.cksize so store it now m_dwSize = m_ck.cksize; } else { m_hmmio = mmioOpen( strFileName, NULL, MMIO_ALLOCBUF | MMIO_READWRITE | MMIO_CREATE ); if( NULL == m_hmmio ) //return DXTRACE_ERR( TEXT("mmioOpen"), E_FAIL ); return -1; if( FAILED( hr = WriteMMIO( pwfx ) ) ) { mmioClose( m_hmmio, 0 ); //return DXTRACE_ERR( TEXT("WriteMMIO"), hr ); return -1; } if( FAILED( hr = ResetFile() ) ) //return DXTRACE_ERR( TEXT("ResetFile"), hr ); return -1; } return hr; }
bool eZ80AccessorSZX::SetState(xIo::eStreamMemory& is) { ZXSTHEADER header; if(is.Read(&header, sizeof(header)) != sizeof(header)) return false; if(header.dwMagic != FOURCC('Z', 'X', 'S', 'T')) return false; bool model48k = false; switch(header.chMachineId) { case ZXSTMID_16K: case ZXSTMID_48K: case ZXSTMID_NTSC48K: model48k = true; break; case ZXSTMID_128K: case ZXSTMID_PENTAGON128: break; default: return false; } SetupDevices(model48k); ZXSTBLOCK block; while(is.Read(&block, sizeof(block)) == sizeof(block)) { switch(block.dwId) { case FOURCC('Z', '8', '0', 'R'): { ZXSTZ80REGS regs; if(!ReadBlock(is, ®s, block)) return false; af = SwapWord(regs.AF); bc = SwapWord(regs.BC); de = SwapWord(regs.DE); hl = SwapWord(regs.HL); alt.af = SwapWord(regs.AF1); alt.bc = SwapWord(regs.BC1); alt.de = SwapWord(regs.DE1); alt.hl = SwapWord(regs.HL1); ix = SwapWord(regs.IX); iy = SwapWord(regs.IY); sp = SwapWord(regs.SP); pc = SwapWord(regs.PC); i = regs.I; r_low = regs.R; r_hi = regs.R & 0x80; im = regs.IM; iff1 = regs.IFF1; iff2 = regs.IFF2; t = Dword((const byte*)®s.dwCyclesStart) % frame_tacts; if(regs.wMemPtr) memptr = SwapWord(regs.wMemPtr); } break; case FOURCC('S', 'P', 'C', 'R'): { ZXSTSPECREGS regs; if(!ReadBlock(is, ®s, block)) return false; devices->IoWrite(0xfe, (regs.chFe&0x18) | regs.chBorder, t); devices->IoWrite(0x7ffd, model48k ? 0x30 : regs.ch7ffd, t); if(model48k) devices->Get<eMemory>()->SetRomPage(eMemory::P_ROM_48); else devices->Get<eMemory>()->SetRomPage((regs.ch7ffd & 0x10) ? eMemory::P_ROM_128_0 : eMemory::P_ROM_128_1); } break; case FOURCC('R', 'A', 'M', 'P'): { ZXSTRAMPAGE ram_page; if(!ReadBlock(is, &ram_page, block, sizeof(ZXSTRAMPAGE) - sizeof(ZXSTBLOCK) - 1)) return false; byte* buf = new byte[eMemory::PAGE_SIZE]; bool ok = false; if(SwapWord(ram_page.wFlags)&ZXSTRF_COMPRESSED) { #ifdef USE_ZIP size_t size = ram_page.blk.dwSize - (sizeof(ZXSTRAMPAGE) - sizeof(ZXSTBLOCK) - 1); byte* buf_compr = new byte[size]; ok = is.Read(buf_compr, size) == size; if(ok) { z_stream zs; memset(&zs, 0, sizeof(zs)); zs.next_in = buf_compr; zs.avail_in = size; zs.next_out = buf; zs.avail_out = eMemory::PAGE_SIZE; ok = inflateInit2(&zs, 15) == Z_OK; if(ok) ok = inflate(&zs, Z_NO_FLUSH) == Z_STREAM_END; inflateEnd(&zs); } SAFE_DELETE_ARRAY(buf_compr); #endif//USE_ZIP } else { size_t size = ram_page.blk.dwSize - (sizeof(ZXSTRAMPAGE) - sizeof(ZXSTBLOCK) - 1); ok = size == eMemory::PAGE_SIZE; if(ok) { ok = is.Read(buf, size) == size; } } if(ok && ram_page.chPageNo <= 7) { memcpy(memory->Get(eMemory::P_RAM0 + ram_page.chPageNo), buf, eMemory::PAGE_SIZE); } SAFE_DELETE(buf); if(!ok) return false; } break; case FOURCC('A', 'Y', '\0', '\0'): { ZXSTAYBLOCK ay_state; if(!ReadBlock(is, &ay_state, block)) return false; devices->Get<eAY>()->SetRegs(ay_state.chAyRegs); devices->Get<eAY>()->Select(ay_state.chCurrentRegister); } break; default: if(is.Seek(block.dwSize, xIo::eStreamMemory::S_CUR) != 0) return false; } if(is.Pos() == is.Size()) return true; } return false; }
// Release all instance data //-------------------------------------------------------------------------------- void CPUTText::ReleaseInstanceData() { SAFE_DELETE_ARRAY(mpMirrorBuffer); }
MarmaladeKeyboard::~MarmaladeKeyboard() { SAFE_DELETE_ARRAY(m_keys); SAFE_DELETE_ARRAY(m_lockedKeys); }
//暗号化 CIPHER_RESULT PmCipher::Encrypt(const char *source_path, const char *cipher_path, bool compress, bool recursive) { //戻り値・・・ステータス //第1引数・・・暗号化するファイル/ディレクトリのパス //第2引数・・・暗号化ファイルのパス //第3引数・・・圧縮フラグ(true:圧縮, false:無圧縮) //第4引数・・・再帰処理フラグ(true:再帰処理あり(デフォルト), false:再帰処理なし) //ファイルストリーム fstream fs_cipher, fs_cipher_idx, fs_cipher_temp; //パス string str_find_path, str_source_path, str_idx_path, str_idx2_path, str_temp_path, str_cipher_path; //ファイルソート用 unsigned int depth = 0, directory_num = 0; //ファイル検索続行フラグ BOOL next = TRUE; //戻り値 CIPHER_RESULT cr = CIPHER_OK; //再帰処理用スタック stack<HANDLE> stack_handle; stack<BOOL> stack_next; stack<string> stack_directory; hash_map<string, unsigned int> map_directory_num; pair<string, unsigned int> pair_directory_num; //カレントディレクトリ string current_directory; //ファイル検索用変数 WIN32_FIND_DATA FindFileData; HANDLE hFind; //ファイルの位置 unsigned long offset = 0; //圧縮フラグ保存 m_compress = compress; char key_word[] = CIPHER_KEY_WORD; char cipher_key_word[CIPHER_KEY_WORD_SIZE]; m_blow_fish.Encode((unsigned char *)key_word, (unsigned char *)cipher_key_word, 8); //ファイルプロパティクラス変数 PmCipherProperty *cipher_property = NULL; //元ファイルパス、中間ファイルパスの生成 str_source_path = string(source_path); if(str_source_path.rfind("\\") == str_source_path.size() - 1) { str_source_path = str_source_path.substr(0, str_source_path.size() - 1); } str_cipher_path = string(cipher_path); str_idx_path = str_cipher_path + string(".idx"); str_idx2_path = str_cipher_path + string(".idx2"); str_temp_path = str_cipher_path + string(".tmp"); if(!PathFileExists(str_cipher_path.substr(0, str_cipher_path.rfind("\\")).c_str()) || !PathIsDirectory(str_cipher_path.substr(0, str_cipher_path.rfind("\\")).c_str())) { return CIPHER_ERR_FILE_NOT_FOUND; } //最初のファイル検索 hFind = FindFirstFile(str_source_path.c_str(), &FindFileData); current_directory = str_source_path; //暗号化ファイル(中間ファイル)のオープン fs_cipher_temp.open(str_temp_path.c_str(), ios::out|ios::binary); //検索が成功した場合 if(hFind != INVALID_HANDLE_VALUE) { //引数で指定されたパスがファイルの場合 if(!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { //サイズチェック if(FindFileData.nFileSizeHigh > 0 || Over2GB(FindFileData.nFileSizeLow)) { cr = CIPHER_ERR_INVALID_FILE_SIZE; } else { //ファイルを暗号化 if((cr = PmCipher::EncryptFile(str_source_path.c_str(), FindFileData.nFileSizeLow, compress, &fs_cipher_temp, &cipher_property)) == CIPHER_OK) { cipher_property->SetOffset(offset); m_property_list->AddProperty(cipher_property); offset += cipher_property->GetCipherSize(); cipher_property = NULL; FindClose(hFind); } } next = FALSE; } //引数で指定されたパスがディレクトリの場合 else { //ワイルドカードを付加して再検索 str_find_path = str_source_path + string("\\*"); hFind = FindFirstFile(str_find_path.c_str(), &FindFileData); pair_directory_num.first = current_directory; pair_directory_num.second = directory_num; map_directory_num.insert(pair_directory_num); } } //検索が失敗した場合エラー終了 else { cr = CIPHER_ERR_FILE_NOT_FOUND; next = FALSE; } //再帰処理が終了しかつ、ファイル検索が終了するまでループ while(!stack_handle.empty() || next) { //ディレクトリのすべてのファイルを検索し終わったら検索処理終了 if(!next) { FindClose(hFind); //再帰処理の途中の場合、上位フォルダを復帰 if(!stack_handle.empty()) { hFind = stack_handle.top(); stack_handle.pop(); next = stack_next.top(); stack_next.pop(); current_directory = stack_directory.top(); stack_directory.pop(); depth--; if(next) { next = FindNextFile(hFind, &FindFileData); } } } //検索したファイル属性がディレクトリの場合でかつ、再帰処理を行う場合 if((FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && recursive && next) { //下位ディレクトリの場合は再帰処理 if(strcmp(FindFileData.cFileName, ".") && strcmp(FindFileData.cFileName, "..")) { stack_handle.push(hFind); stack_next.push(next); stack_directory.push(current_directory); current_directory = current_directory + string("\\") + string(FindFileData.cFileName); depth++; directory_num++; pair_directory_num.first = current_directory; pair_directory_num.second = directory_num; map_directory_num.insert(pair_directory_num); str_find_path = current_directory + string("\\*"); hFind = FindFirstFile(str_find_path.c_str(), &FindFileData); if(hFind != INVALID_HANDLE_VALUE) { next = TRUE; continue; } else { next = FALSE; cr = CIPHER_ERR_INVALID_FILE; } } } //検索したファイル属性がファイルの場合は暗号化 if(!(FindFileData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && next) { //サイズチェック if(FindFileData.nFileSizeHigh > 0 || Over2GB(FindFileData.nFileSizeLow + offset)) { next = FALSE; cr = CIPHER_ERR_INVALID_FILE_SIZE; } else { str_find_path = current_directory + string("\\") + string(FindFileData.cFileName); if((cr = PmCipher::EncryptFile(str_find_path.c_str(), FindFileData.nFileSizeLow, compress, &fs_cipher_temp, &cipher_property)) == CIPHER_OK) { cipher_property->SetOffset(offset); offset += cipher_property->GetCipherSize(); cipher_property->SetDepth(depth); hash_map<string, unsigned int>::iterator it; if((it = map_directory_num.find(current_directory)) != map_directory_num.end()) { cipher_property->SetDirectoryNum(it->second); } else { cr = CIPHER_ERR_FATAL; next = FALSE; } m_property_list->AddProperty(cipher_property); cipher_property = NULL; } } } //エラーが起きたら直ちに終了 if(cr != CIPHER_OK) { while(!stack_handle.empty()) { hFind = stack_handle.top(); FindClose(hFind); stack_handle.pop(); } next = FALSE; } //次のファイルを検索 if(next) { next = FindNextFile(hFind, &FindFileData); } } //暗号化ファイル(中間ファイル)のクローズ fs_cipher_temp.close(); //暗号化が正常に終了した場合 if(cr == CIPHER_OK) { //ファイル、バッファ等のサイズ unsigned long index_size = 0, cipher_index_size, compress_index_size, buf_size, total_buf_size; //バッファメモリの確保 unsigned char *input_buf = new unsigned char[PmCipher::CIPHER_BUF_SIZE]; unsigned char *output_buf = new unsigned char[PmCipher::CIPHER_BUF_SIZE]; //文字列 char str[CIPHER_MAX_INDEX_SIZE]; //インデックスのソート m_property_list->SortProperty(); //インデックス書き込み(平文中間ファイル) fs_cipher_idx.open(str_idx_path.c_str(), ios::out|ios::binary); //ルートディレクトリ書き込み sprintf_s(str, MAX_PATH + 1, "%s\n", str_source_path.c_str()); index_size += str_source_path.length() + 1; fs_cipher_idx.write(str, str_source_path.length() + 1); for(unsigned int i = 0; i < m_property_list->GetPropertySize(); i++) { unsigned int str_size = 40 + m_property_list->GetProperty(i)->GetPath().length() + 1; sprintf_s(str, CIPHER_MAX_INDEX_SIZE, "%010lu%010lu%010lu%010lu%s\n", m_property_list->GetProperty(i)->GetOffset(), m_property_list->GetProperty(i)->GetSourceSize(), m_property_list->GetProperty(i)->GetCompressSize(), m_property_list->GetProperty(i)->GetCipherSize(), m_property_list->GetProperty(i)->GetPath().c_str()); fs_cipher_idx.write(str, str_size); index_size += (unsigned long)str_size; } fs_cipher_idx.close(); //インデックス書き込み(暗号化中間ファイル) fs_cipher_idx.open(str_idx2_path.c_str(), ios::out|ios::binary); if((cr = EncryptFile(str_idx_path.c_str(), index_size, compress, &fs_cipher_idx, &cipher_property)) == CIPHER_OK) { if(!Over2GB(cipher_property->GetCipherSize() + offset + CIPHER_HEADER_SIZE + CIPHER_KEY_WORD_SIZE)) { compress_index_size = cipher_property->GetCompressSize(); cipher_index_size = cipher_property->GetCipherSize(); SAFE_DELETE(cipher_property); fs_cipher_idx.close(); fs_cipher.open(str_cipher_path.c_str(), ios::out|ios::binary); //キーワード書き込み fs_cipher.write(cipher_key_word, CIPHER_KEY_WORD_SIZE); //ヘッダの書き込み sprintf_s(str, CIPHER_MAX_INDEX_SIZE, "%d%010lu%010lu%010lu%010lu", compress?1:0, index_size, compress_index_size, cipher_index_size, offset); fs_cipher.write(str, CIPHER_HEADER_SIZE); fs_cipher_idx.open(str_idx2_path.c_str(), ios::in|ios::binary); //ヘッダと暗号化したインデックス、データファイルの結合 total_buf_size = 0; while(!fs_cipher_idx.eof()) { buf_size = (total_buf_size + CIPHER_BUF_SIZE > cipher_index_size)?(cipher_index_size - total_buf_size):CIPHER_BUF_SIZE; fs_cipher_idx.read((char *)input_buf, buf_size); fs_cipher.write((char *)input_buf, buf_size); total_buf_size += buf_size; if(cipher_index_size <= total_buf_size) { break; } } fs_cipher_idx.close(); fs_cipher_temp.open(str_temp_path.c_str(), ios::in|ios::binary); total_buf_size = 0; while(!fs_cipher_temp.eof()) { buf_size = (total_buf_size + CIPHER_BUF_SIZE > offset)?(offset - total_buf_size):CIPHER_BUF_SIZE; fs_cipher_temp.read((char *)input_buf, buf_size); fs_cipher.write((char *)input_buf, buf_size); total_buf_size += buf_size; if(offset <= total_buf_size) { break; } } fs_cipher << std::flush; } else { cr = CIPHER_ERR_INVALID_FILE_SIZE; } } //ファイルのクローズ fs_cipher_temp.close(); fs_cipher.close(); m_cipher_index_size = cipher_index_size; //バッファメモリの解放 SAFE_DELETE_ARRAY(input_buf); SAFE_DELETE_ARRAY(output_buf); } return cr; }