static BOOL xf_rail_window_common(rdpContext* context, WINDOW_ORDER_INFO* orderInfo, WINDOW_STATE_ORDER* windowState) { xfAppWindow* appWindow = NULL; xfContext* xfc = (xfContext*) context; UINT32 fieldFlags = orderInfo->fieldFlags; BOOL position_or_size_updated = FALSE; if (fieldFlags & WINDOW_ORDER_STATE_NEW) { appWindow = (xfAppWindow*) calloc(1, sizeof(xfAppWindow)); if (!appWindow) return FALSE; appWindow->xfc = xfc; appWindow->windowId = orderInfo->windowId; appWindow->dwStyle = windowState->style; appWindow->dwExStyle = windowState->extendedStyle; appWindow->x = appWindow->windowOffsetX = windowState->windowOffsetX; appWindow->y = appWindow->windowOffsetY = windowState->windowOffsetY; appWindow->width = appWindow->windowWidth = windowState->windowWidth; appWindow->height = appWindow->windowHeight = windowState->windowHeight; /* Ensure window always gets a window title */ if (fieldFlags & WINDOW_ORDER_FIELD_TITLE) { char* title = NULL; if (windowState->titleInfo.length == 0) { if (!(title = _strdup(""))) { WLog_ERR(TAG, "failed to duplicate empty window title string"); /* error handled below */ } } else if (ConvertFromUnicode(CP_UTF8, 0, (WCHAR*) windowState->titleInfo.string, windowState->titleInfo.length / 2, &title, 0, NULL, NULL) < 1) { WLog_ERR(TAG, "failed to convert window title"); /* error handled below */ } appWindow->title = title; } else { if (!(appWindow->title = _strdup("RdpRailWindow"))) WLog_ERR(TAG, "failed to duplicate default window title string"); } if (!appWindow->title) { free(appWindow); return FALSE; } HashTable_Add(xfc->railWindows, (void*)(UINT_PTR) orderInfo->windowId, (void*) appWindow); xf_AppWindowInit(xfc, appWindow); } else { appWindow = (xfAppWindow*) HashTable_GetItemValue(xfc->railWindows, (void*)(UINT_PTR) orderInfo->windowId); } if (!appWindow) return FALSE; /* Keep track of any position/size update so that we can force a refresh of the window */ if ((fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) || (fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) || (fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) || (fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) || (fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) || (fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) || (fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY)) { position_or_size_updated = TRUE; } /* Update Parameters */ if (fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET) { appWindow->windowOffsetX = windowState->windowOffsetX; appWindow->windowOffsetY = windowState->windowOffsetY; } if (fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE) { appWindow->windowWidth = windowState->windowWidth; appWindow->windowHeight = windowState->windowHeight; } if (fieldFlags & WINDOW_ORDER_FIELD_OWNER) { appWindow->ownerWindowId = windowState->ownerWindowId; } if (fieldFlags & WINDOW_ORDER_FIELD_STYLE) { appWindow->dwStyle = windowState->style; appWindow->dwExStyle = windowState->extendedStyle; } if (fieldFlags & WINDOW_ORDER_FIELD_SHOW) { appWindow->showState = windowState->showState; } if (fieldFlags & WINDOW_ORDER_FIELD_TITLE) { char* title = NULL; if (windowState->titleInfo.length == 0) { if (!(title = _strdup(""))) { WLog_ERR(TAG, "failed to duplicate empty window title string"); return FALSE; } } else if (ConvertFromUnicode(CP_UTF8, 0, (WCHAR*) windowState->titleInfo.string, windowState->titleInfo.length / 2, &title, 0, NULL, NULL) < 1) { WLog_ERR(TAG, "failed to convert window title"); return FALSE; } free(appWindow->title); appWindow->title = title; } if (fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_OFFSET) { appWindow->clientOffsetX = windowState->clientOffsetX; appWindow->clientOffsetY = windowState->clientOffsetY; } if (fieldFlags & WINDOW_ORDER_FIELD_CLIENT_AREA_SIZE) { appWindow->clientAreaWidth = windowState->clientAreaWidth; appWindow->clientAreaHeight = windowState->clientAreaHeight; } if (fieldFlags & WINDOW_ORDER_FIELD_WND_CLIENT_DELTA) { appWindow->windowClientDeltaX = windowState->windowClientDeltaX; appWindow->windowClientDeltaY = windowState->windowClientDeltaY; } if (fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) { if (appWindow->windowRects) { free(appWindow->windowRects); appWindow->windowRects = NULL; } appWindow->numWindowRects = windowState->numWindowRects; if (appWindow->numWindowRects) { appWindow->windowRects = (RECTANGLE_16*) calloc(appWindow->numWindowRects, sizeof(RECTANGLE_16)); if (!appWindow->windowRects) return FALSE; CopyMemory(appWindow->windowRects, windowState->windowRects, appWindow->numWindowRects * sizeof(RECTANGLE_16)); } } if (fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET) { appWindow->visibleOffsetX = windowState->visibleOffsetX; appWindow->visibleOffsetY = windowState->visibleOffsetY; } if (fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY) { if (appWindow->visibilityRects) { free(appWindow->visibilityRects); appWindow->visibilityRects = NULL; } appWindow->numVisibilityRects = windowState->numVisibilityRects; if (appWindow->numVisibilityRects) { appWindow->visibilityRects = (RECTANGLE_16*) calloc( appWindow->numVisibilityRects, sizeof(RECTANGLE_16)); if (!appWindow->visibilityRects) return FALSE; CopyMemory(appWindow->visibilityRects, windowState->visibilityRects, appWindow->numVisibilityRects * sizeof(RECTANGLE_16)); } } /* Update Window */ if (fieldFlags & WINDOW_ORDER_FIELD_STYLE) { } if (fieldFlags & WINDOW_ORDER_FIELD_SHOW) { xf_ShowWindow(xfc, appWindow, appWindow->showState); } if (fieldFlags & WINDOW_ORDER_FIELD_TITLE) { if (appWindow->title) xf_SetWindowText(xfc, appWindow, appWindow->title); } if (position_or_size_updated) { UINT32 visibilityRectsOffsetX = (appWindow->visibleOffsetX - (appWindow->clientOffsetX - appWindow->windowClientDeltaX)); UINT32 visibilityRectsOffsetY = (appWindow->visibleOffsetY - (appWindow->clientOffsetY - appWindow->windowClientDeltaY)); /* * The rail server like to set the window to a small size when it is minimized even though it is hidden * in some cases this can cause the window not to restore back to its original size. Therefore we don't * update our local window when that rail window state is minimized */ if (appWindow->rail_state != WINDOW_SHOW_MINIMIZED) { /* Redraw window area if already in the correct position */ if (appWindow->x == appWindow->windowOffsetX && appWindow->y == appWindow->windowOffsetY && appWindow->width == appWindow->windowWidth && appWindow->height == appWindow->windowHeight) { xf_UpdateWindowArea(xfc, appWindow, 0, 0, appWindow->windowWidth, appWindow->windowHeight); } else { xf_MoveWindow(xfc, appWindow, appWindow->windowOffsetX, appWindow->windowOffsetY, appWindow->windowWidth, appWindow->windowHeight); } xf_SetWindowVisibilityRects(xfc, appWindow, visibilityRectsOffsetX, visibilityRectsOffsetY, appWindow->visibilityRects, appWindow->numVisibilityRects); } } /* We should only be using the visibility rects for shaping the window */ /*if (fieldFlags & WINDOW_ORDER_FIELD_WND_RECTS) { xf_SetWindowRects(xfc, appWindow, appWindow->windowRects, appWindow->numWindowRects); }*/ return TRUE; }
//游戏场景 bool CGameClientDlg::OnGameSceneMessage(BYTE cbGameStation, bool bLookonOther, const void * pBuffer, WORD wDataSize) { switch (cbGameStation) { case GS_FREE: //空闲状态 { //效验数据 if (wDataSize!=sizeof(CMD_S_StatusFree)) return false; CMD_S_StatusFree * pStatusFree=(CMD_S_StatusFree *)pBuffer; //设置控件 if (IsLookonMode()==false) { m_GameClientView.m_btStart.ShowWindow(SW_SHOW); m_GameClientView.m_btStart.SetFocus(); } //设置时间 if (IsLookonMode()==false) SetGameTimer(GetMeChairID(),IDI_START_GAME,30); return true; } case GS_PLAYING: //游戏状态 { //效验数据 if (wDataSize!=sizeof(CMD_S_StatusPlay)) return false; CMD_S_StatusPlay * pStatusPlay=(CMD_S_StatusPlay *)pBuffer; //下注信息 m_lMaxScore=pStatusPlay->lMaxScore; m_lCellScore=pStatusPlay->lCellScore; m_lTurnMaxScore=pStatusPlay->lTurnMaxScore; m_lTurnLessScore=pStatusPlay->lTurnLessScore; CopyMemory(m_lTableScore,pStatusPlay->lTableScore,sizeof(m_lTableScore)); //状态变量 m_wCurrentUser=pStatusPlay->wCurrentUser; m_bAddScore=(pStatusPlay->bAddScore==TRUE)?true:false; m_bShowHand=(pStatusPlay->bShowHand==TRUE)?true:false; CopyMemory(m_cbPlayStatus,pStatusPlay->cbPlayStatus,sizeof(m_cbPlayStatus)); //帐号名字 for (WORD i=0;i<GAME_PLAYER;i++) { const tagUserData * pUserData=GetUserData(i); if (pUserData!=NULL) lstrcpyn(m_szAccounts[i],pUserData->szName,CountArray(m_szAccounts[i])); } //设置界面 LONG lTableScore=0L; for (WORD i=0;i<GAME_PLAYER;i++) { //设置位置 WORD wViewChairID=SwitchViewChairID(i); //设置扑克 if (m_cbPlayStatus[i]==TRUE) { BYTE cbCardCount=pStatusPlay->cbCardCount[i]; m_GameClientView.m_CardControl[wViewChairID].SetCardData(pStatusPlay->cbHandCardData[i],cbCardCount); } lTableScore += m_lTableScore[2*i+1]; //筹码设置 m_GameClientView.m_PlayerJeton[wViewChairID].SetScore(m_lTableScore[2*i]); //设置下注 m_GameClientView.SetUserTableScore(wViewChairID,m_lTableScore[2*i]+m_lTableScore[2*i+1]); } m_GameClientView.m_PlayerJeton[GAME_PLAYER].SetScore(lTableScore); // m_GameClientView.SetCellScore(m_lCellScore); //玩家设置 if (IsLookonMode()==false) { //控制设置 m_GameClientView.m_CardControl[2].SetPositively(true); if (m_wCurrentUser==GetMeChairID()) UpdateScoreControl(); } //设置定时器 SetGameTimer(m_wCurrentUser,IDI_USER_ADD_SCORE,TIME_USER_ADD_SCORE); return true; } } return false; }
LONG WINAPI DetourAttachEx(PVOID *ppPointer, PVOID pDetour, PDETOUR_TRAMPOLINE *ppRealTrampoline, PVOID *ppRealTarget, PVOID *ppRealDetour) { LONG error = NO_ERROR; if (ppRealTrampoline != NULL) { *ppRealTrampoline = NULL; } if (ppRealTarget != NULL) { *ppRealTarget = NULL; } if (ppRealDetour != NULL) { *ppRealDetour = NULL; } if (s_nPendingThreadId != (LONG)GetCurrentThreadId()) { DETOUR_TRACE(("transaction conflict with thread id=%d\n", s_nPendingThreadId)); return ERROR_INVALID_OPERATION; } // If any of the pending operations failed, then we don't need to do this. if (s_nPendingError != NO_ERROR) { DETOUR_TRACE(("pending transaction error=%d\n", s_nPendingError)); return s_nPendingError; } if (ppPointer == NULL) { DETOUR_TRACE(("ppPointer is null\n")); return ERROR_INVALID_HANDLE; } if (*ppPointer == NULL) { error = ERROR_INVALID_HANDLE; s_nPendingError = error; s_ppPendingError = ppPointer; DETOUR_TRACE(("*ppPointer is null (ppPointer=%p)\n", ppPointer)); DETOUR_BREAK(); return error; } PBYTE pbTarget = (PBYTE)*ppPointer; PDETOUR_TRAMPOLINE pTrampoline = NULL; DetourOperation *o = NULL; #ifdef DETOURS_IA64 #error Feature not supported in this release. #else // DETOURS_IA64 pbTarget = (PBYTE)DetourCodeFromPointer(pbTarget, NULL); pDetour = DetourCodeFromPointer(pDetour, NULL); #endif // !DETOURS_IA64 // Don't follow a jump if its destination is the target function. // This happens when the detour does nothing other than call the target. if (pDetour == (PVOID)pbTarget) { if (s_fIgnoreTooSmall) { goto stop; } else { DETOUR_BREAK(); goto fail; } } if (ppRealTarget != NULL) { *ppRealTarget = pbTarget; } if (ppRealDetour != NULL) { *ppRealDetour = pDetour; } o = new DetourOperation; if (o == NULL) { error = ERROR_NOT_ENOUGH_MEMORY; fail: s_nPendingError = error; DETOUR_BREAK(); stop: if (pTrampoline != NULL) { detour_free_trampoline(pTrampoline); pTrampoline = NULL; if (ppRealTrampoline != NULL) { *ppRealTrampoline = NULL; } } if (o != NULL) { delete o; o = NULL; } s_ppPendingError = ppPointer; return error; } pTrampoline = detour_alloc_trampoline(pbTarget); if (pTrampoline == NULL) { error = ERROR_NOT_ENOUGH_MEMORY; DETOUR_BREAK(); goto fail; } if (ppRealTrampoline != NULL) { *ppRealTrampoline = pTrampoline; } DETOUR_TRACE(("detours: pbTramp=%p, pDetour=%p\n", pTrampoline, pDetour)); memset(pTrampoline->rAlign, 0, sizeof(pTrampoline->rAlign)); // Determine the number of movable target instructions. PBYTE pbSrc = pbTarget; PBYTE pbTrampoline = pTrampoline->rbCode; PBYTE pbPool = pbTrampoline + sizeof(pTrampoline->rbCode); ULONG cbTarget = 0; ULONG cbJump = SIZE_OF_JMP; ULONG nAlign = 0; #ifdef DETOURS_ARM #error Feature not supported in this release. #endif while (cbTarget < cbJump) { PBYTE pbOp = pbSrc; LONG lExtra = 0; DETOUR_TRACE((" DetourCopyInstruction(%p,%p)\n", pbTrampoline, pbSrc)); pbSrc = (PBYTE) DetourCopyInstruction(pbTrampoline, (PVOID*)&pbPool, pbSrc, NULL, &lExtra); DETOUR_TRACE((" DetourCopyInstruction() = %p (%d bytes)\n", pbSrc, (int)(pbSrc - pbOp))); pbTrampoline += (pbSrc - pbOp) + lExtra; cbTarget = (LONG)(pbSrc - pbTarget); pTrampoline->rAlign[nAlign].obTarget = cbTarget; pTrampoline->rAlign[nAlign].obTrampoline = pbTrampoline - pTrampoline->rbCode; if (detour_does_code_end_function(pbOp)) { break; } } // Consume, but don't duplicate padding if it is needed and available. while (cbTarget < cbJump) { LONG cFiller = detour_is_code_filler(pbSrc); if (cFiller == 0) { break; } pbSrc += cFiller; cbTarget = (LONG)(pbSrc - pbTarget); } #if DETOUR_DEBUG { DETOUR_TRACE((" detours: rAlign [")); LONG n = 0; for (n = 0; n < ARRAYSIZE(pTrampoline->rAlign); n++) { if (pTrampoline->rAlign[n].obTarget == 0 && pTrampoline->rAlign[n].obTrampoline == 0) { break; } DETOUR_TRACE((" %d/%d", pTrampoline->rAlign[n].obTarget, pTrampoline->rAlign[n].obTrampoline )); } DETOUR_TRACE((" ]\n")); } #endif if (cbTarget < cbJump || nAlign > ARRAYSIZE(pTrampoline->rAlign)) { // Too few instructions. error = ERROR_INVALID_BLOCK; if (s_fIgnoreTooSmall) { goto stop; } else { DETOUR_BREAK(); goto fail; } } if (pbTrampoline > pbPool) { __debugbreak(); } #if 0 // [GalenH] if (cbTarget < pbTrampoline - pTrampoline->rbCode) { __debugbreak(); } #endif pTrampoline->cbCode = (BYTE)(pbTrampoline - pTrampoline->rbCode); pTrampoline->cbRestore = (BYTE)cbTarget; CopyMemory(pTrampoline->rbRestore, pbTarget, cbTarget); #if !defined(DETOURS_IA64) if (cbTarget > sizeof(pTrampoline->rbCode) - cbJump) { // Too many instructions. error = ERROR_INVALID_HANDLE; DETOUR_BREAK(); goto fail; } #endif // !DETOURS_IA64 pTrampoline->pbRemain = pbTarget + cbTarget; pTrampoline->pbDetour = (PBYTE)pDetour; #ifdef DETOURS_IA64 #error Feature not supported in this release. #endif // DETOURS_IA64 pbTrampoline = pTrampoline->rbCode + pTrampoline->cbCode; #ifdef DETOURS_X64 #error Feature not supported in this release. #endif // DETOURS_X64 #ifdef DETOURS_X86 pbTrampoline = detour_gen_jmp_immediate(pbTrampoline, pTrampoline->pbRemain); pbTrampoline = detour_gen_brk(pbTrampoline, pbPool); #endif // DETOURS_X86 #ifdef DETOURS_ARM #error Feature not supported in this release. #endif // DETOURS_ARM DWORD dwOld = 0; if (!VirtualProtect(pbTarget, cbTarget, PAGE_EXECUTE_READWRITE, &dwOld)) { error = GetLastError(); DETOUR_BREAK(); goto fail; } DETOUR_TRACE(("detours: pbTarget=%p: " "%02x %02x %02x %02x " "%02x %02x %02x %02x " "%02x %02x %02x %02x\n", pbTarget, pbTarget[0], pbTarget[1], pbTarget[2], pbTarget[3], pbTarget[4], pbTarget[5], pbTarget[6], pbTarget[7], pbTarget[8], pbTarget[9], pbTarget[10], pbTarget[11])); DETOUR_TRACE(("detours: pbTramp =%p: " "%02x %02x %02x %02x " "%02x %02x %02x %02x " "%02x %02x %02x %02x\n", pTrampoline, pTrampoline->rbCode[0], pTrampoline->rbCode[1], pTrampoline->rbCode[2], pTrampoline->rbCode[3], pTrampoline->rbCode[4], pTrampoline->rbCode[5], pTrampoline->rbCode[6], pTrampoline->rbCode[7], pTrampoline->rbCode[8], pTrampoline->rbCode[9], pTrampoline->rbCode[10], pTrampoline->rbCode[11])); o->fIsRemove = FALSE; o->ppbPointer = (PBYTE*)ppPointer; o->pTrampoline = pTrampoline; o->pbTarget = pbTarget; o->dwPerm = dwOld; o->pNext = s_pPendingOperations; s_pPendingOperations = o; return NO_ERROR; }
//----------------------------------------------------------------------------- // Name: CWaveFile::Read() // Desc: Reads section of data from a wave file into pBuffer and returns // how much read in pdwSizeRead, reading not more than dwSizeToRead. // This uses m_ck to determine where to start reading from. So // subsequent calls will be continue where the last left off unless // Reset() is called. //----------------------------------------------------------------------------- HRESULT CPCMFile::Read( BYTE* pBuffer, DWORD dwSizeToRead, DWORD* pdwSizeRead ) { if( m_bIsReadingFromMemory ) { if( m_pbDataCur == NULL ) return CO_E_NOTINITIALIZED; if( pdwSizeRead != NULL ) *pdwSizeRead = 0; if( (BYTE*)(m_pbDataCur + dwSizeToRead) > (BYTE*)(m_pbData + m_ulDataSize) ) { dwSizeToRead = m_ulDataSize - (DWORD)(m_pbDataCur - m_pbData); } CopyMemory( pBuffer, m_pbDataCur, dwSizeToRead ); if( pdwSizeRead != NULL ) *pdwSizeRead = dwSizeToRead; return S_OK; } else { MMIOINFO mmioinfoIn; // current status of m_hmmio if( m_hmmio == NULL ) return CO_E_NOTINITIALIZED; if( pBuffer == NULL || pdwSizeRead == NULL ) return E_INVALIDARG; if( pdwSizeRead != NULL ) *pdwSizeRead = 0; if( 0 != mmioGetInfo( m_hmmio, &mmioinfoIn, 0 ) ) return DXTRACE_ERR( TEXT("mmioGetInfo"), E_FAIL ); UINT cbDataIn = dwSizeToRead; if( cbDataIn > m_ck.cksize ) cbDataIn = m_ck.cksize; m_ck.cksize -= cbDataIn; for( DWORD cT = 0; cT < cbDataIn; cT++ ) { // Copy the bytes from the io to the buffer. if( mmioinfoIn.pchNext == mmioinfoIn.pchEndRead ) { if( 0 != mmioAdvance( m_hmmio, &mmioinfoIn, MMIO_READ ) ) return DXTRACE_ERR( TEXT("mmioAdvance"), E_FAIL ); //if( mmioinfoIn.pchNext == mmioinfoIn.pchEndRead ) // return DXTRACE_ERR( TEXT("mmioinfoIn.pchNext"), E_FAIL ); } // Actual copy. *((BYTE*)pBuffer+cT) = *((BYTE*)mmioinfoIn.pchNext); mmioinfoIn.pchNext++; } if( 0 != mmioSetInfo( m_hmmio, &mmioinfoIn, 0 ) ) return DXTRACE_ERR( TEXT("mmioSetInfo"), E_FAIL ); if( pdwSizeRead != NULL ) *pdwSizeRead = cbDataIn; return S_OK; } }
LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wp, LPARAM lp){ //tab controls INITCOMMONCONTROLSEX ic; static RECT rcDisp; //trackbar static HWND hTrack = NULL; // buttons and edit(read-only) handles static HWND hOpen = NULL; static HWND hPlay = NULL; static HWND hPause = NULL; static HWND hStop = NULL; static HWND hLoop = NULL; static HWND hDown = NULL; static HWND hUp = NULL; static HWND hExit = NULL; static HDC hdc; PAINTSTRUCT ps; DWORD dw; int i, ia; short s; static LPDWORD lpPixel; static BITMAPINFO bmpInfo; static int iWidth, iHeight; static LPDWORD lpPixelCursor; static BITMAPINFO bmpInfoCursor; static int iWidthCursor, iHeightCursor, iTimeCursor; static int iPixel = 0; HBITMAP hBmp; static HDC hdc_mem; // file static OPENFILENAME ofn; static char szFile[MAX_PATH]; static char szFileTitle[MAX_PATH]; //wav file static HWAVEOUT hWaveOut; static WAVEFORMATEX wfe; static WAVEHDR whdr; const RECT rcWave = {10, 10, 1225, 447};//10, 20, 1235, 550 //10, 10, 631, 381 const RECT rcBar = {10, 390, 631, 401}; static RECT rcInfo[] = {{1, 1060, 900, 20}, {2000, 1060, 110, 20}, {2220, 1060, 110, 20}, {2335, 1060, 108, 20}}; static RECT rcMove = rcInfo[0]; static MMTIME mmTime; static DWORD maxTime; DWORD dwOffset; // wave static POINT ptWaveL[1226], ptWaveR[1226];//621 static WORD wHalfMaxAmp; static HPEN hPenL, hPenR; static int hueL, hueR, hueLR; // volume static DWORD dwVolStart; static WORD wVolNow; DWORD dwVolTemp; // font static HFONT hFont[3]; static BYTE rr = 0, gg = 128, bb = 128; // open, pause, exit static BYTE r = 0, g = 128, b = 128; // play static BYTE rs = 0, gs = 128, bs = 128; // stop static BYTE vr1 = 0, vg1 = 128, vb1 = 128; // volume-down static BYTE vr2 = 0, vg2 = 128, vb2 = 128; // volume-up static BYTE rLoop = 0, gLoop = 128, bLoop = 128; // loop //text static char strFile[1024]; static char strTime[32]; static char strVol[16]; static char strState[16]; static SIZE sizeFile; static BOOL open = FALSE; static BOOL play = FALSE; static BOOL pause = FALSE; static BOOL loop = FALSE; switch( msg ){ case WM_CREATE: DragAcceptFiles(hwnd, TRUE); // background bmp lpPixel = bmptoDIB("480127.bmp", &bmpInfo); iWidth = bmpInfo.bmiHeader.biWidth; iHeight = bmpInfo.bmiHeader.biHeight; // get Window's device context handle hdc = GetDC( hwnd ); hBmp = CreateCompatibleBitmap(hdc, iWidth, iHeight); // make memory device context hdc_mem = CreateCompatibleDC(hdc); // select bitmap which is loaded SelectObject( hdc_mem, hBmp ); DeleteObject(hBmp); ReleaseDC(hwnd, hdc); // initialize OPENFILENAME ofn.lStructSize = sizeof(OPENFILENAME); ofn.hwndOwner = hwnd; ofn.lpstrFilter = "WAVE_FORMAT_PCM(*.wav)\0*.wav\0"; ofn.lpstrFile = szFile; ofn.nMaxFile = MAX_PATH; ofn.lpstrFileTitle = szFileTitle; ofn.nMaxFileTitle = MAX_PATH; ofn.Flags = OFN_FILEMUSTEXIST; ofn.lpstrDefExt = "wav"; ofn.lpstrTitle = "Select PCM type of Wav file"; // create pen hPenL = CreatePen(PS_SOLID, 1, RGB(255,255,0)); // hPenR = CreatePen(PS_SOLID, 1, RGB(0,255,255)); // // initialize a coordinate for wave for(i = 0; i< sizeof(ptWaveL)/sizeof(ptWaveL[0]); i++) { ptWaveL[i].x = 10+i; ptWaveL[i].y = -10; ptWaveR[i].x = 10+i; ptWaveR[i].y = -10; } // change background mode SetBkMode(hdc_mem, TRANSPARENT); hFont[0] = CreateFont(18, 0, 0, 0, FW_BOLD, TRUE, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, VARIABLE_PITCH | FF_DONTCARE, "Times New Roman"); hFont[1] = CreateFont(24, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, VARIABLE_PITCH | FF_DONTCARE, "Arial Black"); hFont[2] = CreateFont(12, 0, 0, 0, FW_DONTCARE, FALSE, FALSE, FALSE, ANSI_CHARSET, OUT_DEFAULT_PRECIS, CLIP_DEFAULT_PRECIS, DEFAULT_QUALITY, VARIABLE_PITCH | FF_DONTCARE, "Times New Roman"); // initialize MMTIME mmTime.wType = TIME_BYTES; // store an initial value for volume and show the volume waveOutGetVolume(hWaveOut, &dwVolStart); wVolNow = LOWORD(dwVolStart); wsprintf(strVol, "%03d/128", (wVolNow +1)/512); // show state wsprintf(strState, "NoData"); //button hOpen = CreateWindowEx(0, TEXT("BUTTON"), TEXT("Open") , WS_CHILD | WS_VISIBLE , 15, 620 , 70 , 30 , hwnd , (HMENU)ID_OPEN, ((LPCREATESTRUCT)(lp))->hInstance , NULL); hPlay = CreateWindowEx(0, TEXT("BUTTON"), TEXT("Play") , WS_CHILD | WS_VISIBLE , 90, 620 , 70 , 30 , hwnd , (HMENU)ID_PLAY, ((LPCREATESTRUCT)(lp))->hInstance , NULL); hPause = CreateWindowEx(0, TEXT("BUTTON"), TEXT("Pause") , WS_CHILD | WS_VISIBLE , 165 , 620 , 70 , 30 , hwnd , (HMENU)ID_PAUSE, ((LPCREATESTRUCT)(lp))->hInstance , NULL); hStop = CreateWindowEx(0, TEXT("BUTTON"), TEXT("Stop") , WS_CHILD | WS_VISIBLE , 240 , 620 , 70 , 30 , hwnd , (HMENU)ID_STOP, ((LPCREATESTRUCT)(lp))->hInstance , NULL); hLoop = CreateWindowEx(0, TEXT("BUTTON"), TEXT("Loop") , WS_CHILD | WS_VISIBLE , 900 , 620 , 70 , 30 , hwnd , (HMENU)ID_LOOP, ((LPCREATESTRUCT)(lp))->hInstance , NULL); hDown = CreateWindowEx(0, TEXT("BUTTON"), TEXT("-") , WS_CHILD | WS_VISIBLE , 1000 , 620 , 40 , 30 , hwnd , (HMENU)ID_DOWN, ((LPCREATESTRUCT)(lp))->hInstance, NULL); hUp = CreateWindowEx(0, TEXT("BUTTON"), TEXT("+") , WS_CHILD | WS_VISIBLE , 1050 , 620 , 40 , 30 , hwnd , (HMENU)ID_UP, ((LPCREATESTRUCT)(lp))->hInstance , NULL); hExit = CreateWindowEx(0, TEXT("BUTTON"), TEXT("Exit") , WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_TABSTOP, 1160, 620 , 70 , 30 , hwnd , (HMENU)ID_EXITT, ((LPCREATESTRUCT)(lp))->hInstance, NULL); //track bar ic.dwSize = sizeof(INITCOMMONCONTROLSEX); ic.dwICC = ICC_BAR_CLASSES; InitCommonControlsEx(&ic); hTrack = CreateWindowEx(0, TRACKBAR_CLASS, "", WS_CHILD | WS_VISIBLE | TBS_HORZ | TBS_AUTOTICKS, 10, 580, 1230, 25, hwnd, (HMENU)IDC_TRACKBAR, ((LPCREATESTRUCT)(lp))->hInstance, NULL); // TrackProc = (WNDPROC)GetWindowLong(hTrack, GWL_WNDPROC); //SetWindowLong(hTrack, GWL_WNDPROC, (LONG)TrackProc); // SendMessage(hTrack, TBM_SETRANGE, (WPARAM)TRUE, (LPARAM)MAKELPARAM(0, 100)); return 0; case WM_SIZE: return 0; /*case WM_NOTIFY: switch (((NMHDR *)lp)->code){ case TCN_SELCHANGE: if (TabCtrl_GetCurSel(hTab) == 0){ InvalidateRect(hTab, &rcDisp, FALSE); InvalidateRect(hStatic, NULL, FALSE); }else if(TabCtrl_GetCurSel(hTab) == 1){ InvalidateRect(hStatic, NULL, FALSE); }else{ } break; case TCN_SELCHANGING: return FALSE; } return 0; */ case WM_COMMAND: switch(LOWORD(wp)) { case ID_TAB: break; case ID_OPTIONS_DOWNLOADMUSIC: //////////////////////// CREATE UDP SOCKET FROM MENU !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! break; case ID_OPTIONS_MICROPHONE: ///////////////////// CREATE MICROPHONE FROM MENU !!!!!!!!!!!!!!!!!!!! break; case ID_DIRECTX_MULTIPLAYER: hTab = MakeTabCtrl(hwnd); // PostMessage(hStatic, ID_STATIC, (WPARAM)0, (LPARAM)0); break; case ID_DIRECTX_TABCLOSEFORMULTIPLAYER: break; case ID_OPEN: // when "Open" is pushed if(GetOpenFileName(&ofn)) { if(open) { play=FALSE; pause=FALSE; KillTimer(hwnd, 1); rcMove.left = rcInfo[0].left; iTimeCursor = 0; waveOutReset(hWaveOut); waveOutUnprepareHeader(hWaveOut, &whdr, sizeof(WAVEHDR)); waveOutClose(hWaveOut); HeapFree(GetProcessHeap(), 0, whdr.lpData); } if(waveIn(ofn.lpstrFile, &hWaveOut, &wfe, &whdr)) { for(i=0;i<sizeof(ptWaveL)/sizeof(ptWaveL[0]);i++) { ptWaveL[i].y = -10; //default value ptWaveR[i].y = -10; //default value } strFile[0] = NULL; strTime[0] = NULL; wsprintf(strState, "NoData"); InvalidateRect(hwnd, &rcWave, FALSE); InvalidateRect(hwnd, &rcInfo[0], FALSE); InvalidateRect(hwnd, &rcInfo[1], FALSE); InvalidateRect(hwnd, &rcInfo[3], FALSE); return 0; } waveOutOpen(&hWaveOut, WAVE_MAPPER, &wfe, (DWORD)hwnd, 0, CALLBACK_WINDOW); waveOutPrepareHeader(hWaveOut, &whdr, sizeof(WAVEHDR)); wHalfMaxAmp = pow(2, wfe.wBitsPerSample-1); //half of the max amplitud for(i=0;i<sizeof(ptWaveL)/sizeof(ptWaveL[0]);i++) ptWaveL[i].y=250; //screen center for wave if(wfe.nChannels == 2) { for(i = 0 ; i < sizeof(ptWaveR)/sizeof(ptWaveR[0]) ; i++) ptWaveR[i].y = 250; //screen center for wave } else { for(i = 0 ; i < sizeof(ptWaveR)/sizeof(ptWaveR[0]) ; i++) ptWaveR[i].y = -10; //default value } wsprintf(strFile,"%s :- %d bits / %s / %d Hz", ofn.lpstrFileTitle,wfe.wBitsPerSample, (wfe.nChannels==2)?"stereo":"mono",wfe.nSamplesPerSec); SelectObject(hdc_mem,hFont[2]); GetTextExtentPoint32(hdc_mem,strFile,(int)strlen(strFile),&sizeFile); maxTime=100*whdr.dwBufferLength/wfe.nAvgBytesPerSec; wsprintf(strTime,"00:00:00/%02d:%02d:%02d", (maxTime/100)/60,(maxTime/100)%60,maxTime%100); //total time open=TRUE; wsprintf(strState,"ready"); InvalidateRect(hwnd,&rcWave,FALSE); InvalidateRect(hwnd,&rcInfo[0],FALSE); InvalidateRect(hwnd,&rcInfo[1],FALSE); InvalidateRect(hwnd,&rcInfo[3],FALSE); } return 0; case ID_PLAY: // when "Play" is pressed if(!open || play) return 0; //file is open but not playing play=TRUE; wsprintf(strState,"playing"); InvalidateRect(hwnd,&rcInfo[3],FALSE); if(pause) { pause=FALSE; waveOutRestart(hWaveOut); } else { iTimeCursor=0; waveOutWrite(hWaveOut,&whdr,sizeof(WAVEHDR)); } SetTimer(hwnd,1,50,NULL); break; case ID_PAUSE: // when "Pause" button is pushed if(!play && !pause) return 0; //playing or pause if(pause) { pause=FALSE; play=TRUE; wsprintf(strState,"playing"); waveOutRestart(hWaveOut); SetTimer(hwnd,1,50,NULL); } else { pause=TRUE; play=FALSE; wsprintf(strState,"pause"); waveOutPause(hWaveOut); KillTimer(hwnd,1); } InvalidateRect(hwnd,&rcInfo[3],FALSE); break; case ID_STOP: // when "Stop" button is pressed if(!open) return 0; if(play) { //pushed during playing play=FALSE; pause=FALSE; iTimeCursor=0; waveOutReset(hWaveOut); //MM_WOM_DONE message is sent } else { for(i=0;i<sizeof(ptWaveL)/sizeof(ptWaveL[0]);i++) ptWaveL[i].y=250; //center for wave drawn if(wfe.nChannels==2) for(i=0;i<sizeof(ptWaveR)/sizeof(ptWaveR[0]);i++) ptWaveR[i].y=250; //center for wave drawn if(pause) { //pushed during pause play=FALSE; pause=FALSE; waveOutReset(hWaveOut); rcMove.left=rcInfo[0].left; wsprintf(strState,"ready"); InvalidateRect(hwnd,&rcWave,FALSE); InvalidateRect(hwnd,&rcInfo[0],FALSE); InvalidateRect(hwnd,&rcInfo[3],FALSE); } //pushed again after pause iTimeCursor=0; wsprintf(strTime,"00:00:00/%02d:%02d:%02d", (maxTime/100)/60,(maxTime/100)%60,maxTime%100); //total time InvalidateRect(GetTopWindow(hwnd),&rcInfo[1],FALSE); } break; case ID_LOOP: if(loop) { loop=FALSE; } else { loop=TRUE; } break; case ID_DOWN://- waveOutGetVolume(hWaveOut,&dwVolTemp); ia=LOWORD(dwVolTemp); // store in wVolNow after mute cancellation ia-=512; wVolNow=(ia<0)?0:ia; waveOutSetVolume(hWaveOut,MAKELONG(wVolNow,wVolNow)); wsprintf(strVol,"%03d/128",(wVolNow+1)/512); InvalidateRect(hwnd,&rcInfo[2],FALSE); break; case ID_UP: waveOutGetVolume(hWaveOut,&dwVolTemp); ia=LOWORD(dwVolTemp); // store in wVolNow after mute cancellation ia+=512; wVolNow=(ia>0xFFFF)?0xFFFF:ia; waveOutSetVolume(hWaveOut,MAKELONG(wVolNow,wVolNow)); wsprintf(strVol,"%03d/128",(wVolNow+1)/512); InvalidateRect(hwnd,&rcInfo[2],FALSE); break; case ID_EXITT: case ID_EXIT_EXIT: KillTimer(hwnd,1); // SetWindowLong(hTrack, GWL_WNDPROC, (LONG)TrackProc); // DestroyWindow(hTrack); ExitProcess(-1); DestroyWindow(hwnd); break; } return 0; /*case WM_HSCROLL: if( (HWND)lp == GetDlgItem( hwnd, IDC_SLIDER ) ){ pos = SendMessage( (HWND)lp, TBM_GETPOS, 0, 0 ); } return 0;*/ case WM_DROPFILES: //drag and drop for file DragQueryFile((HDROP)wp, 0, strFile, sizeof(strFile)); DragFinish((HDROP)wp); //when open button is pushed if(open) { play = FALSE; pause = FALSE; KillTimer(hwnd, 1); rcMove.left = rcInfo[0].left; iTimeCursor = 0; waveOutReset(hWaveOut); waveOutUnprepareHeader(hWaveOut, &whdr, sizeof(WAVEHDR)); waveOutClose(hWaveOut); HeapFree(GetProcessHeap(), 0, whdr.lpData); } if(waveIn(strFile, &hWaveOut, &wfe, &whdr)) { //finished abnormaly for(i = 0 ; i < sizeof(ptWaveL)/sizeof(ptWaveL[0]) ; i++) { ptWaveL[i].y = -10; //default value ptWaveR[i].y = -10; //default value } strFile[0] = NULL; strTime[0] = NULL; wsprintf(strState, "NoData"); InvalidateRect(hwnd, &rcWave, FALSE); InvalidateRect(hwnd, &rcInfo[0], FALSE); InvalidateRect(hwnd, &rcInfo[1], FALSE); InvalidateRect(hwnd, &rcInfo[3], FALSE); return 0; } waveOutOpen(&hWaveOut, WAVE_MAPPER, &wfe, (DWORD)hwnd, 0, CALLBACK_WINDOW); waveOutPrepareHeader(hWaveOut, &whdr, sizeof(WAVEHDR)); wHalfMaxAmp=pow(2, wfe.wBitsPerSample - 1); //half of the max amplitud for(i=0;i<sizeof(ptWaveL)/sizeof(ptWaveL[0]);i++) ptWaveL[i].y=250; //screen center for wave if(wfe.nChannels == 2) { for(i = 0 ; i < sizeof(ptWaveR)/sizeof(ptWaveR[0]) ; i++) ptWaveR[i].y = 250; //screen center for wave } else { for(i = 0 ; i < sizeof(ptWaveR)/sizeof(ptWaveR[0]) ; i++) ptWaveR[i].y = -10; //default value } wsprintf(strFile, "%s :- %d bits / %s / %d Hz", PathFindFileName(strFile), wfe.wBitsPerSample, (wfe.nChannels==2)?"stereo":"mono", wfe.nSamplesPerSec); SelectObject(hdc_mem, hFont[2]); GetTextExtentPoint32(hdc_mem, strFile, (int)strlen(strFile), &sizeFile); maxTime = 100*whdr.dwBufferLength/wfe.nAvgBytesPerSec; wsprintf(strTime,"00:00:00/%02d:%02d:%02d", (maxTime/100)/60,(maxTime/100)%60,maxTime%100); //total time open=TRUE; wsprintf(strState, "ready"); InvalidateRect(hwnd, &rcWave, FALSE); InvalidateRect(hwnd, &rcInfo[0], FALSE); InvalidateRect(hwnd, &rcInfo[1], FALSE); InvalidateRect(hwnd, &rcInfo[3], FALSE); return 0; case MM_WOM_DONE: pause = FALSE; waveOutReset(hWaveOut); if(loop && play) { iTimeCursor = 0; waveOutWrite(hWaveOut, &whdr, sizeof(WAVEHDR)); return 0; } if(play) { //play completed iTimeCursor = 600; wsprintf(strTime,"%02d:%02d:%02d/%02d:%02d:%02d", (maxTime/100)/60,(maxTime/100)%60,maxTime%100, //current time (maxTime/100)/60,(maxTime/100)%60,maxTime%100); //total time } for(i = 0 ; i < sizeof(ptWaveL)/sizeof(ptWaveL[0]) ; i++) ptWaveL[i].y=250; //center for wave drawn 195 if(wfe.nChannels == 2) for(i=0 ; i<sizeof(ptWaveR)/sizeof(ptWaveR[0]) ; i++) ptWaveR[i].y=250; //center for wave drawn 195 play = FALSE; rcMove.left = rcInfo[0].left; wsprintf(strState, "ready"); KillTimer(hwnd, 1); InvalidateRect(hwnd, &rcWave, FALSE); InvalidateRect(hwnd, &rcInfo[0], FALSE); InvalidateRect(hwnd, &rcInfo[1], FALSE); InvalidateRect(hwnd, &rcInfo[3], FALSE); return 0; case WM_TIMER: rcMove.left-= 1; if(rcMove.left<-sizeFile.cx) rcMove.left = rcInfo[0].right; waveOutGetPosition(hWaveOut, &mmTime, sizeof(MMTIME)); dwOffset = mmTime.u.cb; iTimeCursor = (double)dwOffset/whdr.dwBufferLength*600; //change Cursor coordinate for(i = -612 ; i <= 612 ; i++) //-310 310 { //left s = 0; dw = dwOffset + i*wfe.nBlockAlign; if(0 <= dw && dw < whdr.dwBufferLength) { CopyMemory(&s, whdr.lpData+dw, wfe.wBitsPerSample/8); if(wfe.wBitsPerSample == 8) s-= 128; // shift no volume(128) to 0 } ptWaveL[i+612].y = 185*(-s)/wHalfMaxAmp + 250; //ptWaveL[i+310].y + 195; } if(wfe.nChannels == 2) { //stereo for(i = -612 ; i <= 612 ; i++)//-310 310 { //right s = 0; dw = dwOffset + i*wfe.nBlockAlign + wfe.wBitsPerSample/8; if(0 <= dw && dw < whdr.dwBufferLength) { CopyMemory(&s, whdr.lpData + dw, wfe.wBitsPerSample/8); if(wfe.wBitsPerSample == 8) s-=128; //shift no volume(128) to 0 } ptWaveR[i+612].y = 185*(-s)/wHalfMaxAmp + 250; //ptWaveR[i+310].y +195 } } dw = (double)dwOffset/wfe.nAvgBytesPerSec*100; wsprintf(strTime, "%02d:%02d:%02d/%02d:%02d:%02d", (dw/100)/60,(dw/100)%60,dw%100, //current time (maxTime/100)/60,(maxTime/100)%60,maxTime%100); //total time InvalidateRect(hwnd, &rcWave, FALSE); InvalidateRect(hwnd, &rcInfo[0], FALSE); InvalidateRect(hwnd, &rcInfo[1], FALSE); return 0; case WM_PAINT: hdc = BeginPaint(hwnd, &ps); StretchDIBits(hdc_mem, 0, 0, iWidth, iHeight, 0, 0, iWidth, iHeight, lpPixel, &bmpInfo, DIB_RGB_COLORS, SRCCOPY); ///////////////////////////////////////// SelectObject(hdc_mem, hFont[2]); SetTextColor(hdc_mem, RGB(255, 255, 0)); DrawText(hdc_mem, strFile, (int)strlen(strFile), &rcMove, DT_SINGLELINE | DT_VCENTER); DrawText(hdc_mem,strTime, (int)strlen(strTime), &rcInfo[1], DT_SINGLELINE | DT_CENTER | DT_VCENTER); DrawText(hdc_mem, strVol, (int)strlen(strVol), &rcInfo[2], DT_SINGLELINE | DT_CENTER | DT_VCENTER); DrawText(hdc_mem, strState, (int)strlen(strState), &rcInfo[3], DT_SINGLELINE | DT_CENTER | DT_VCENTER); SelectObject(hdc_mem, hPenR); Polyline(hdc_mem, ptWaveR, sizeof(ptWaveR)/sizeof(ptWaveR[0])); SelectObject(hdc_mem, hPenL); Polyline(hdc_mem, ptWaveL, sizeof(ptWaveL)/sizeof(ptWaveL[0])); // measure when strFile is over limitation StretchDIBits(hdc_mem, 0, 450, 20, 20, 0, 10, 20, 20, lpPixel, &bmpInfo, DIB_RGB_COLORS, SRCCOPY); ////////////////////////////////////////////////////// BitBlt(hdc, 0, 0, iWidth, iHeight, hdc_mem, 0, 0, SRCCOPY); EndPaint(hwnd, &ps); return 0; case WM_DESTROY: SetWindowLong(hTrack, GWL_WNDPROC, (LONG)TrackProc); DestroyWindow(hTrack); PostQuitMessage(0); return 0; default: return DefWindowProc(hwnd, msg, wp, lp); } return 0; }
LPDWORD bmptoDIB(TCHAR *fileName, LPBITMAPINFO lpbiInfo) { HANDLE fhBMP; int iFileSize; LPBYTE lpBMP; DWORD dwReadSize; LPBITMAPFILEHEADER lpbmpfh; LPBITMAPINFO lpbiBMPInfo; LPBYTE lpBMPPixel; LPDWORD dwColors; int iwidth,iheight; LPDWORD lpPixel; int bitCount; int iLength,x,y; TCHAR err[20]; fhBMP = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(fhBMP == INVALID_HANDLE_VALUE) { CloseHandle(fhBMP); wsprintf(err, TEXT("cannot open a file %d"), GetLastError()); MessageBox(NULL, err, fileName, MB_OK); return NULL; } iFileSize=GetFileSize(fhBMP,NULL); lpBMP=(LPBYTE)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,iFileSize); ReadFile(fhBMP,lpBMP,iFileSize,&dwReadSize,NULL); CloseHandle(fhBMP); lpbmpfh=(LPBITMAPFILEHEADER)(lpBMP); lpbiBMPInfo=(LPBITMAPINFO)(lpBMP+sizeof(BITMAPFILEHEADER)); bitCount = lpbiBMPInfo->bmiHeader.biBitCount; if(lpbmpfh->bfType!=('M'<<8)+'B' || bitCount != 8 && bitCount != 24) { HeapFree(GetProcessHeap(),0,lpBMP); MessageBox(NULL,TEXT("Can read only 8 or 24 bit files"),fileName,MB_OK); return NULL; } lpBMPPixel=lpBMP+(lpbmpfh->bfOffBits); dwColors=(LPDWORD)(lpbiBMPInfo->bmiColors); iwidth=lpbiBMPInfo->bmiHeader.biWidth; iheight=lpbiBMPInfo->bmiHeader.biHeight; lpPixel=(LPDWORD)HeapAlloc(GetProcessHeap(),HEAP_ZERO_MEMORY,iwidth*iheight*4); lpbiInfo->bmiHeader.biSize=sizeof(BITMAPINFOHEADER); lpbiInfo->bmiHeader.biWidth=iwidth; lpbiInfo->bmiHeader.biHeight=iheight; lpbiInfo->bmiHeader.biPlanes=1; lpbiInfo->bmiHeader.biBitCount=32; lpbiInfo->bmiHeader.biCompression=BI_RGB; if(iwidth*(bitCount/8)%4) iLength=iwidth*(bitCount/8)+(4-iwidth*(bitCount/8)%4); else iLength=iwidth*(bitCount/8); switch(bitCount) { case 8: for(y=0;y<iheight;y++) for(x=0;x<iwidth;x++) CopyMemory(lpPixel+x+y*iwidth,dwColors+lpBMPPixel[x+y*iLength],3); case 24: for(y=0;y<iheight;y++) for(x=0;x<iwidth;x++) CopyMemory(lpPixel+x+y*iwidth,lpBMPPixel+x*3+y*iLength,3); break; } HeapFree(GetProcessHeap(),0,lpBMP); return lpPixel; }
CDialogTemplate::CDialogTemplate(BYTE* pbData, unsigned int uCodePage) { m_uCodePage = uCodePage; m_szClass = 0; m_szFont = 0; m_szMenu = 0; m_szTitle = 0; WORD wItems = 0; if (*(DWORD*)pbData == 0xFFFF0001) { // Extended dialog template signature m_bExtended = true; DLGTEMPLATEEX* dTemplateEx = (DLGTEMPLATEEX*)pbData; m_dwHelpId = dTemplateEx->helpID; m_dwStyle = dTemplateEx->style; m_dwExtStyle = dTemplateEx->exStyle; m_sX = dTemplateEx->x; m_sY = dTemplateEx->y; m_sWidth = dTemplateEx->cx; m_sHeight = dTemplateEx->cy; wItems = dTemplateEx->cDlgItems; } else { m_bExtended = false; DLGTEMPLATE* dTemplate = (DLGTEMPLATE*)pbData; m_dwStyle = dTemplate->style; m_dwExtStyle = dTemplate->dwExtendedStyle; m_sX = dTemplate->x; m_sY = dTemplate->y; m_sWidth = dTemplate->cx; m_sHeight = dTemplate->cy; wItems = dTemplate->cdit; } BYTE* seeker = pbData + (m_bExtended ? sizeof(DLGTEMPLATEEX) : sizeof(DLGTEMPLATE)); // Read menu variant length array ReadVarLenArr(seeker, m_szMenu, m_uCodePage); // Read class variant length array ReadVarLenArr(seeker, m_szClass, m_uCodePage); // Read title variant length array ReadVarLenArr(seeker, m_szTitle, m_uCodePage); // Read font size and variant length array (only if style DS_SETFONT is used!) if (m_dwStyle & DS_SETFONT) { m_sFontSize = *(short*)seeker; seeker += sizeof(short); if (m_bExtended) { m_sFontWeight = *(short*)seeker; seeker += sizeof(short); m_bItalic = *(BYTE*)seeker; seeker += sizeof(BYTE); m_bCharset = *(BYTE*)seeker; seeker += sizeof(BYTE); } ReadVarLenArr(seeker, m_szFont, m_uCodePage); } // Read items for (int i = 0; i < wItems; i++) { // DLGITEMTEMPLATE[EX]s must be aligned on DWORD boundry if (DWORD(seeker - pbData) % sizeof(DWORD)) seeker += sizeof(WORD); DialogItemTemplate* item = new DialogItemTemplate; ZeroMemory(item, sizeof(DialogItemTemplate)); if (m_bExtended) { DLGITEMTEMPLATEEX* rawItem = (DLGITEMTEMPLATEEX*)seeker; item->dwHelpId = rawItem->helpID; item->dwStyle = rawItem->style; item->dwExtStyle = rawItem->exStyle; item->sX = rawItem->x; item->sY = rawItem->y; item->sWidth = rawItem->cx; item->sHeight = rawItem->cy; item->wId = rawItem->id; seeker += sizeof(DLGITEMTEMPLATEEX); } else { DLGITEMTEMPLATE* rawItem = (DLGITEMTEMPLATE*)seeker; item->dwStyle = rawItem->style; item->dwExtStyle = rawItem->dwExtendedStyle; item->sX = rawItem->x; item->sY = rawItem->y; item->sWidth = rawItem->cx; item->sHeight = rawItem->cy; item->wId = rawItem->id; seeker += sizeof(DLGITEMTEMPLATE); } // Read class variant length array ReadVarLenArr(seeker, item->szClass, m_uCodePage); // Read title variant length array ReadVarLenArr(seeker, item->szTitle, m_uCodePage); // Read creation data variant length array // First read the size of the array (no null termination) item->wCreateDataSize = *(WORD*)seeker; seeker += sizeof(WORD); // Then read the array it self (if size is not 0) if (item->wCreateDataSize) { item->wCreateDataSize -= sizeof(WORD); // Size includes size field itself... item->szCreationData = new char[item->wCreateDataSize]; CopyMemory(item->szCreationData, seeker, item->wCreateDataSize); seeker += item->wCreateDataSize; } // Add the item to the vector m_vItems.push_back(item); } }
/************************************************************************************* * FlushBuffer: pushes the buffer onto main array * **************************************************************************************/ BOOL cCombH::FlushBuffer() { //4 steps: //0. check that there is data to flush. //a. if socheck that regions are sequential and unique //b. wham the regionBuffer onto each of the combos in the buffer //c. copy the buffer to the main buffer //d. clean out the buffer memory BOOL bRetCode = false; LPCOMBINATION pCMNew = NULL; LPCOMBINATION p = NULL; LPCOMBINATION q = NULL; //0. check that there is data to flush. if (!(0 < m_lComboBufferCount)) {goto SAFE_EXIT;} if (!(0 < m_lRegionBufferCount)) {goto SAFE_EXIT;} //a. if socheck that regions are sequential and unique if (!CheckRegionsAreSequentialAndUnique()) {goto SAFE_EXIT;} //b. wham the regionBuffer onto each of the combos in the buffer for(q = m_pCMComboBuffer; q<m_pCMComboBuffer+m_lComboBufferCount;q++) { q->lRegionCount = m_lRegionBufferCount; LPULONG pl = new ULONG[m_lRegionBufferCount]; CopyMemory(pl,m_plRegionBuffer,m_lRegionBufferCount*sizeof(ULONG)); q->plDisjointRegions = pl; pl = NULL; } //c. copy the buffer to the main buffer //initialize a new buffer with additional combo members pCMNew = new COMBINATION[m_lCombinationCount + m_lComboBufferCount]; //copy the existing array into a new array if (0 < m_lCombinationCount) { CopyMemory(pCMNew,m_pCMCombinations,m_lCombinationCount*sizeof(COMBINATION)); delete [] m_pCMCombinations; } m_pCMCombinations = pCMNew; //get a pointer to the last elements of the combination array p = m_pCMCombinations+m_lCombinationCount; //copy the combo buffer over to the main array CopyMemory(p,m_pCMComboBuffer,m_lComboBufferCount*sizeof(COMBINATION)); //increment total number of combinations m_lCombinationCount += m_lComboBufferCount; bRetCode = true; SAFE_EXIT: //d. clean out the buffer memory delete[] m_pCMComboBuffer; m_pCMComboBuffer = NULL; m_lComboBufferCount = 0; delete [] m_plRegionBuffer; m_plRegionBuffer = NULL; m_lRegionBufferCount = 0; return bRetCode; }
//$--HrFindExchangeGlobalAddressList------------------------------------------------- // Returns the entry ID of the global address list container in the address // book. // ----------------------------------------------------------------------------- HRESULT HrFindExchangeGlobalAddressList( // RETURNS: return code IN LPADRBOOK lpAdrBook, // address book pointer OUT ULONG *lpcbeid, // pointer to count of bytes in entry ID OUT LPENTRYID *lppeid) // pointer to entry ID pointer { HRESULT hr = NOERROR; ULONG ulObjType = 0; ULONG i = 0; LPMAPIPROP lpRootContainer = NULL; LPMAPIPROP lpContainer = NULL; LPMAPITABLE lpContainerTable = NULL; LPSRowSet lpRows = NULL; ULONG cbContainerEntryId = 0; LPENTRYID lpContainerEntryId = NULL; LPSPropValue lpCurrProp = NULL; SRestriction SRestrictAnd[2] = {0}; SRestriction SRestrictGAL = {0}; SPropValue SPropID = {0}; SPropValue SPropProvider = {0}; BYTE muid[] = MUIDEMSAB; SizedSPropTagArray(1, rgPropTags) = { 1, { PR_ENTRYID, } }; DEBUGPUBLIC("HrFindExchangeGlobalAddressList()"); hr = CHK_HrFindExchangeGlobalAddressList( lpAdrBook, lpcbeid, lppeid); if(FAILED(hr)) RETURN(hr); *lpcbeid = 0; *lppeid = NULL; // Open the root container of the address book hr = MAPICALL(lpAdrBook)->OpenEntry( /*lpAdrBook,*/ 0, NULL, NULL, MAPI_DEFERRED_ERRORS, &ulObjType, (LPUNKNOWN FAR *)&lpRootContainer); if(FAILED(hr)) { goto cleanup; } if(ulObjType != MAPI_ABCONT) { hr = HR_LOG(E_FAIL); goto cleanup; } // Get the hierarchy table of the root container hr = MAPICALL(((LPABCONT)lpRootContainer))->GetHierarchyTable( /*(LPABCONT)lpRootContainer,*/ MAPI_DEFERRED_ERRORS|CONVENIENT_DEPTH, &lpContainerTable); if(FAILED(hr)) { goto cleanup; } // Restrict the table to the global address list (GAL) // --------------------------------------------------- // Initialize provider restriction to only Exchange providers SRestrictAnd[0].rt = RES_PROPERTY; SRestrictAnd[0].res.resProperty.relop = RELOP_EQ; SRestrictAnd[0].res.resProperty.ulPropTag = PR_AB_PROVIDER_ID; SPropProvider.ulPropTag = PR_AB_PROVIDER_ID; SPropProvider.Value.bin.cb = 16; SPropProvider.Value.bin.lpb = (LPBYTE)muid; SRestrictAnd[0].res.resProperty.lpProp = &SPropProvider; // Initialize container ID restriction to only GAL container SRestrictAnd[1].rt = RES_PROPERTY; SRestrictAnd[1].res.resProperty.relop = RELOP_EQ; SRestrictAnd[1].res.resProperty.ulPropTag = PR_EMS_AB_CONTAINERID; SPropID.ulPropTag = PR_EMS_AB_CONTAINERID; SPropID.Value.l = 0; SRestrictAnd[1].res.resProperty.lpProp = &SPropID; // Initialize AND restriction SRestrictGAL.rt = RES_AND; SRestrictGAL.res.resAnd.cRes = 2; SRestrictGAL.res.resAnd.lpRes = &SRestrictAnd[0]; // Restrict the table to the GAL - only a single row should remain // Get the row corresponding to the GAL // // Query all the rows // hr = HrQueryAllRows( lpContainerTable, (LPSPropTagArray)&rgPropTags, &SRestrictGAL, NULL, 0, &lpRows); if(FAILED(hr) || (lpRows == NULL) || (lpRows->cRows != 1)) { hr = HR_LOG(E_FAIL); goto cleanup; } // Get the entry ID for the GAL lpCurrProp = &(lpRows->aRow[0].lpProps[0]); if(lpCurrProp->ulPropTag == PR_ENTRYID) { cbContainerEntryId = lpCurrProp->Value.bin.cb; lpContainerEntryId = (LPENTRYID)lpCurrProp->Value.bin.lpb; } else { hr = HR_LOG(EDK_E_NOT_FOUND); goto cleanup; } hr = MAPIAllocateBuffer(cbContainerEntryId, (LPVOID *)lppeid); if(FAILED(hr)) { *lpcbeid = 0; *lppeid = NULL; } else { CopyMemory( *lppeid, lpContainerEntryId, cbContainerEntryId); *lpcbeid = cbContainerEntryId; } cleanup: ULRELEASE(lpRootContainer); ULRELEASE(lpContainerTable); ULRELEASE(lpContainer); FREEPROWS(lpRows); if(FAILED(hr)) { MAPIFREEBUFFER(*lppeid); *lpcbeid = 0; *lppeid = NULL; } RETURN(hr); }
/*! \brief Moves the packets from the ring buffer to a given buffer. \param pWanAdapter Pointer to WAN_ADAPTER structure associated with this instance. \param Buffer Pointer to the destination, user allocated, buffer. \param BuffSize Size of the buffer. \return It returns the number of bytes correctly written to the destination buffer */ DWORD WanPacketRemovePacketsFromRingBuffer(PWAN_ADAPTER pWanAdapter, PUCHAR Buffer, DWORD BuffSize) { DWORD Copied; struct bpf_hdr *Header; Copied = 0; DWORD ToCopy; DWORD Increment; ResetEvent(pWanAdapter->hReadEvent); while (BuffSize > Copied) { if ( pWanAdapter->Free < pWanAdapter->Size ) { //there are some packets in the selected (aka LocalData) buffer Header = (struct bpf_hdr*)(pWanAdapter->Buffer + pWanAdapter->C); if (Header->bh_caplen + sizeof (struct bpf_hdr) > BuffSize - Copied) { //if the packet does not fit into the user buffer, we've ended copying packets return Copied; } *((struct bpf_hdr*)(Buffer + Copied)) = *Header; Copied += sizeof(struct bpf_hdr); pWanAdapter->C += sizeof(struct bpf_hdr); if ( pWanAdapter->C == pWanAdapter->Size ) pWanAdapter->C = 0; if ( pWanAdapter->Size - pWanAdapter->C < (DWORD)Header->bh_caplen ) { //the packet is fragmented in the buffer (i.e. it skips the buffer boundary) ToCopy = pWanAdapter->Size - pWanAdapter->C; CopyMemory(Buffer + Copied,pWanAdapter->Buffer + pWanAdapter->C, ToCopy); CopyMemory(Buffer + Copied + ToCopy, pWanAdapter->Buffer + 0, Header->bh_caplen - ToCopy); pWanAdapter->C = Header->bh_caplen - ToCopy; } else { //the packet is not fragmented CopyMemory(Buffer + Copied ,pWanAdapter->Buffer + pWanAdapter->C ,Header->bh_caplen); pWanAdapter->C += Header->bh_caplen; // if (c==size) inutile, contemplato nell "header atomico" // c=0; } Copied += ALIGN_TO_WORD(Header->bh_caplen); Increment = Header->bh_caplen + sizeof(struct bpf_hdr); if ( pWanAdapter->Size - pWanAdapter->C < sizeof(struct bpf_hdr) ) { //the next packet would be saved at the end of the buffer, but the NewHeader struct would be fragmented //so the producer (--> the consumer) skips to the beginning of the buffer Increment += pWanAdapter->Size - pWanAdapter->C; pWanAdapter->C = 0; } pWanAdapter->Free += Increment; } else return Copied; } return Copied; }
SIZE_T WSAAPI CopyProtoentToBuffer(IN PCHAR Buffer, IN INT BufferLength, IN PPROTOENT Protoent) { SIZE_T BufferSize, CurrentSize, NameSize; PCHAR p = Buffer; DWORD Aliases = 0; DWORD i; PPROTOENT ReturnedProtoent = (PPROTOENT)Buffer; /* Determine the buffer size required */ BufferSize = BytesInProtoent(Protoent); /* Check which size to use */ if ((DWORD)BufferLength > BufferSize) { /* Zero the buffer */ ZeroMemory(Buffer, BufferSize); } else { /* Zero the buffer */ ZeroMemory(Buffer, BufferLength); } /* Start with the raw servent */ CurrentSize = sizeof(PROTOENT); /* Return the size needed now */ if (CurrentSize > (DWORD)BufferLength) return BufferSize; /* Copy the servent and initialize it */ CopyMemory(p, Protoent, sizeof(PROTOENT)); p = Buffer + CurrentSize; ReturnedProtoent->p_name = NULL; ReturnedProtoent->p_aliases = NULL; /* Find out how many aliases there are */ while (Protoent->p_aliases[Aliases]) { /* Increase the alias count */ Aliases++; } /* Add the aliases to the size, and validate it */ CurrentSize += (Aliases + 1) * sizeof(ULONG_PTR); if (CurrentSize > (DWORD)BufferLength) { /* Clear the aliases and return */ Protoent->p_aliases = NULL; return BufferSize; } /* Write the aliases, update the pointer */ ReturnedProtoent->p_aliases = (PCHAR*)p; p = Buffer + CurrentSize; /* Add the service name to the size, and validate it */ NameSize = strlen(Protoent->p_name) + sizeof(CHAR); CurrentSize += NameSize; if (CurrentSize > (DWORD)BufferLength) return BufferSize; /* Write the service name and update the pointer */ ReturnedProtoent->p_name = p; CopyMemory(p, Protoent->p_name, NameSize); p = Buffer + CurrentSize; /* Now add the aliases */ for (i = 0; i < Aliases; i++) { /* Update size and validate */ NameSize = strlen(Protoent->p_aliases[i]) + sizeof(CHAR); CurrentSize += NameSize; if (CurrentSize > (DWORD)BufferLength) return BufferSize; /* Write pointer and copy */ ReturnedProtoent->p_aliases[i] = p; CopyMemory(p, Protoent->p_aliases[i], NameSize); /* Update pointer */ p = Buffer + CurrentSize; } /* Finalize the list and return */ ReturnedProtoent->p_aliases[i] = NULL; return BufferSize; }
void CShellContextMenu::SetPath(const tstring& strPath) { // free all allocated datas if(m_psfFolder && bDelete) m_psfFolder->Release(); m_psfFolder = NULL; FreePIDLArray(m_pidlArray); m_pidlArray = NULL; // get IShellFolder interface of Desktop(root of shell namespace) IShellFolder* psfDesktop = NULL; SHGetDesktopFolder(&psfDesktop); // ParseDisplayName creates a PIDL from a file system path relative to the IShellFolder interface // but since we use the Desktop as our interface and the Desktop is the namespace root // that means that it's a fully qualified PIDL, which is what we need LPITEMIDLIST pidl = NULL; psfDesktop->ParseDisplayName(NULL, 0, (LPOLESTR)const_cast<TCHAR*>(strPath.c_str()), NULL, &pidl, NULL); // now we need the parent IShellFolder interface of pidl, and the relative PIDL to that interface typedef HRESULT (CALLBACK* LPFUNC)(LPCITEMIDLIST pidl, REFIID riid, void **ppv, LPCITEMIDLIST *ppidlLast); LPFUNC MySHBindToParent = (LPFUNC)GetProcAddress(LoadLibrary(_T("shell32")), "SHBindToParent"); if(MySHBindToParent == NULL) return; MySHBindToParent(pidl, IID_IShellFolder, (LPVOID*)&m_psfFolder, NULL); // get interface to IMalloc (need to free the PIDLs allocated by the shell functions) LPMALLOC lpMalloc = NULL; SHGetMalloc(&lpMalloc); lpMalloc->Free(pidl); // now we need the relative pidl IShellFolder* psfFolder = NULL; HRESULT res = psfDesktop->ParseDisplayName (NULL, 0, (LPOLESTR)const_cast<TCHAR*>(strPath.c_str()), NULL, &pidl, NULL); if(res != S_OK) return; LPITEMIDLIST pidlItem = NULL; SHBindToParent(pidl, IID_IShellFolder, (LPVOID*)&psfFolder, (LPCITEMIDLIST*)&pidlItem); // copy pidlItem to m_pidlArray m_pidlArray = (LPITEMIDLIST *) realloc(m_pidlArray, sizeof (LPITEMIDLIST)); int nSize = 0; LPITEMIDLIST pidlTemp = pidlItem; if(pidlTemp) //[+]PPA http://iceberg.leschat.net/forum/index.php?s=&showtopic=265&view=findpost&p=26331 while(pidlTemp->mkid.cb) { nSize += pidlTemp->mkid.cb; pidlTemp = (LPITEMIDLIST) (((LPBYTE) pidlTemp) + pidlTemp->mkid.cb); } LPITEMIDLIST pidlRet = (LPITEMIDLIST) calloc(nSize + sizeof (USHORT), sizeof (BYTE)); CopyMemory(pidlRet, pidlItem, nSize); m_pidlArray[0] = pidlRet; //free(pidlItem); lpMalloc->Free(pidl); lpMalloc->Release(); if(psfFolder) //[+]PPA http://iceberg.leschat.net/forum/index.php?showtopic=265&st=2320&# psfFolder->Release(); psfDesktop->Release(); bDelete = true; // indicates that m_psfFolder should be deleted by CShellContextMenu }
//用户通知 bool CClientKernel::OnIPCUser(const IPC_Head * pHead, const void * pIPCBuffer, WORD wDataSize, HWND hWndSend) { switch (pHead->wSubCmdID) { case IPC_SUB_USER_COME: //用户消息 { //效验参数 if (wDataSize<sizeof(tagUserInfoHead)) return false; //读取基本信息 tagUserData *pUserData = new tagUserData; tagUserInfoHead * pUserInfoHead=(tagUserInfoHead *)pIPCBuffer; pUserData->wFaceID=pUserInfoHead->wFaceID; //pUserData->dwCustomFaceVer=pUserInfoHead->dwCustomFaceVer; pUserData->wTableID=pUserInfoHead->wTableID; pUserData->wChairID=pUserInfoHead->wChairID; pUserData->cbGender=pUserInfoHead->cbGender; pUserData->cbUserStatus=pUserInfoHead->cbUserStatus; pUserData->cbMemberOrder=pUserInfoHead->cbMemberOrder; pUserData->cbMasterOrder=pUserInfoHead->cbMasterOrder; pUserData->dwUserID=pUserInfoHead->dwUserID; pUserData->dwGameID=pUserInfoHead->dwGameID; pUserData->dwGroupID=pUserInfoHead->dwGroupID; pUserData->dwUserRight=pUserInfoHead->dwUserRight; //pUserData->dwLoveliness=pUserInfoHead->dwLoveliness; pUserData->dwMasterRight=pUserInfoHead->dwMasterRight; pUserData->lScore=pUserInfoHead->UserScoreInfo.lScore; //pUserData->lGameGold=pUserInfoHead->UserScoreInfo.lGameGold; //pUserData->lInsureScore=pUserInfoHead->UserScoreInfo.lInsureScore; pUserData->lWinCount=pUserInfoHead->UserScoreInfo.lWinCount; pUserData->lLostCount=pUserInfoHead->UserScoreInfo.lLostCount; pUserData->lDrawCount=pUserInfoHead->UserScoreInfo.lDrawCount; pUserData->lFleeCount=pUserInfoHead->UserScoreInfo.lFleeCount; pUserData->lExperience=pUserInfoHead->UserScoreInfo.lExperience; //for ( WORD wPropID = 0; wPropID < PROPERTY_COUNT; ++wPropID ) //{ //pUserData->dwPropResidualTime[wPropID] = pUserInfoHead->dwPropResidualTime[wPropID]; //} //读取扩展信息 void * pDataBuffer=NULL; tagDataDescribe DataDescribe; CRecvPacketHelper RecvPacket(pUserInfoHead+1,wDataSize-sizeof(tagUserInfoHead)); while (true) { pDataBuffer=RecvPacket.GetData(DataDescribe); if (DataDescribe.wDataDescribe==DTP_NULL) break; switch (DataDescribe.wDataDescribe) { case DTP_USER_ACCOUNTS: //用户帐户 { if (DataDescribe.wDataSize<=sizeof(pUserData->szName)) { CopyMemory(&pUserData->szName,pDataBuffer,DataDescribe.wDataSize); //pUserData->szName[sizeof(pUserData->czNickName)-1]=0; } break; } case DTP_UNDER_WRITE: //个性签名 { if (DataDescribe.wDataSize<=sizeof(pUserData->szUnderWrite)) { CopyMemory(&pUserData->szUnderWrite,pDataBuffer,DataDescribe.wDataSize); //pUserData->szUnderWrite[CountArray(UserData.szUnderWrite)-1]=0; } break; } case DTP_USER_GROUP_NAME: //用户社团 { if (DataDescribe.wDataSize<=sizeof(pUserData->szGroupName)) { CopyMemory(&pUserData->szGroupName,pDataBuffer,DataDescribe.wDataSize); //pUserData->szGroupName[CountArray(UserData.szGroupName)-1]=0; } break; } case DTP_USER_COMPANION: //用户关系 { if (DataDescribe.wDataSize<=sizeof(pUserData->cbCompanion)) { CopyMemory(&pUserData->cbCompanion,pDataBuffer,DataDescribe.wDataSize); } break; } //case DTP_USER_NICKNAME: //用户昵称 // { // if (DataDescribe.wDataSize<=sizeof(pUserData->czNickName)) // { // CopyMemory(&pUserData->szNickName,pDataBuffer,DataDescribe.wDataSize); // } // break; // } } } //增加用户 ActiveUserItem(pUserData); return true; } case IPC_SUB_USER_STATUS: //用户状态 { //效验参数 if (wDataSize<sizeof(IPC_UserStatus)) return false; //消息处理 IPC_UserStatus * pUserStatus=(IPC_UserStatus *)pIPCBuffer; if (pUserStatus->cbUserStatus<US_SIT) { if (pUserStatus->dwUserID==m_dwUserID) { ResetClientKernel(); return true; } else DeleteUserItem(pUserStatus->dwUserID); } else UpdateUserItem(pUserStatus->dwUserID,pUserStatus->cbUserStatus,pUserStatus->wNetDelay); return true; } case IPC_SUB_USER_SCORE: //用户积分 { //效验参数 if (wDataSize<sizeof(IPC_UserScore)) return false; //消息处理 IPC_UserScore * pUserScore=(IPC_UserScore *)pIPCBuffer; //tagUserData *pUserData = SearchUserItem(pUserScore->dwUserID); //pUserData->dwLoveliness = pUserScore->UserScore->dwLoveliness; UpdateUserItem(pUserScore->dwUserID,&pUserScore->UserScore); return true; } //case IPC_SUB_MEMBERORDER: //会员等级 // { // //效验参数 // if (wDataSize<sizeof(IPC_MemberOrder)) return false; // //消息处理 // IPC_MemberOrder * pMemberOrder=(IPC_MemberOrder *)pIPCBuffer; // tagUserData *pUserData = SearchUserItem(pMemberOrder->dwUserID); // pUserData->cbMemberOrder = pMemberOrder->cbMember; // //更新界面 // m_pIClientKernelSink->OnEventUserMemberOrder(pUserData,pUserData->wChairID,false); // return true; // } case IPC_SUB_GAME_START: //游戏开始 { //设置用户 for (WORD i=0;i<m_ServerAttribute.wChairCount;i++) { if (m_pUserItem[i]!=NULL) { m_pUserItem[i]->cbUserStatus=US_PLAY; m_pIClientKernelSink->OnEventUserStatus(m_pUserItem[i],m_pUserItem[i]->wChairID,false); } } return true; } case IPC_SUB_GAME_FINISH: //游戏结束 { //设置用户 for (WORD i=0;i<m_ServerAttribute.wChairCount;i++) { if (m_pUserItem[i]!=NULL) { m_pUserItem[i]->cbUserStatus=US_SIT; m_pIClientKernelSink->OnEventUserStatus(m_pUserItem[i],m_pUserItem[i]->wChairID,false); } } return true; } //case IPC_SUB_UPDATE_FACE: //更新头像 // { // return true; // } } return false; }
void _TIFFmemcpy(void* d, const tdata_t s, tsize_t c) { CopyMemory(d, s, c); }
BOOL CTwiBootProgDoc::LoadIntelHex(CString FilePath) { ASSERT (m_pBuffer == NULL); ASSERT(m_BufferLength == 0); try { CStdioFile File(FilePath, CFile::modeRead|CFile::typeText); CIntelHexRec Rec; CString str; ULONG len = 0, Addr = 0; if (!CalcIntelHexSize(&File, &len)) throw erInvalidHexFormat; m_BufferLength = len; m_pBuffer = new BYTE[len]; FillMemory(m_pBuffer, m_BufferLength, 0xFF); File.SeekToBegin(); while(File.ReadString(str)) { if (!Rec.InitFromString(str)) throw erInvalidHexFormat; switch(Rec.m_Type) { case cHexTypeData: Addr &= 0xFFFF0000; Addr |= Rec.m_Addr; CopyMemory(m_pBuffer + Addr, Rec.m_Data, Rec.m_Size); break; case cHexTypeEndOfData: break; case cHexTypeExtLinearAddr: Addr = Rec.GetExtAddr(); break; default: ASSERT(FALSE); throw erInvalidHexFormat; } } File.Close(); return TRUE; } catch (CFileException* ex) { CString strErr; strErr.Format(IDS_OPEN_FAILED_WITH_ERRNO, ex->m_cause); AfxMessageBox(strErr); ex->Delete(); return FALSE; } catch (int Err) { switch (Err) { case erInvalidHexFormat: AfxMessageBox(IDS_INVALID_HEX_FORMAT); break; default: ASSERT(FALSE); AfxMessageBox(IDS_OPEN_FAILED); break; } return FALSE; } }
//Make destination an identical copy of source HRESULT CColourExFilter::Copy(IMediaSample *pSource, IMediaSample *pDest) { CheckPointer(pSource,E_POINTER); CheckPointer(pDest,E_POINTER); HRESULT hr = E_FAIL; // Copy the sample data BYTE *pSourceBuffer = NULL, *pDestBuffer = NULL; long lSourceSize = pSource->GetActualDataLength(); #ifdef _DEBUG long lDestSize = pDest->GetSize(); ASSERT(lDestSize >= lSourceSize); #endif DX_VERIFY(pSource->GetPointer(&pSourceBuffer)); DX_VERIFY(pDest->GetPointer(&pDestBuffer)); CopyMemory( (PVOID) pDestBuffer,(PVOID) pSourceBuffer, lSourceSize); // Copy the sample times REFERENCE_TIME TimeStart, TimeEnd; DX_VERIFY(pSource->GetTime(&TimeStart, &TimeEnd)); if (NOERROR == hr) { DX_VERIFY(pDest->SetTime(&TimeStart, &TimeEnd)); } LONGLONG MediaStart, MediaEnd; DX_VERIFY(pSource->GetMediaTime(&MediaStart,&MediaEnd)); if(NOERROR == hr){ DX_VERIFY(pDest->SetMediaTime(&MediaStart,&MediaEnd)); } // Copy the Sync point property DX_VERIFY_EXCEPT1(pSource->IsSyncPoint(), S_FALSE); if (hr == S_OK) { pDest->SetSyncPoint(TRUE); } else if (hr == S_FALSE) { pDest->SetSyncPoint(FALSE); } else { // an unexpected error has occured... return E_UNEXPECTED; } // Copy the media type AM_MEDIA_TYPE *pMediaType = NULL; DX_VERIFY(pSource->GetMediaType(&pMediaType)); DX_VERIFY(pDest->SetMediaType(pMediaType)); DeleteMediaType(pMediaType); // Copy the preroll property DX_VERIFY_EXCEPT1(pSource->IsPreroll(), S_FALSE); if (hr == S_OK) { pDest->SetPreroll(TRUE); } else if (hr == S_FALSE) { pDest->SetPreroll(FALSE); } else { // an unexpected error has occured... DX_VERIFY(hr); return E_UNEXPECTED; } // Copy the discontinuity property DX_VERIFY_EXCEPT1(pSource->IsDiscontinuity(), S_FALSE); if (hr == S_OK) { pDest->SetDiscontinuity(TRUE); } else if (hr == S_FALSE) { pDest->SetDiscontinuity(FALSE); } else { // an unexpected error has occured... return E_UNEXPECTED; } // Copy the actual data length long lDataLength = pSource->GetActualDataLength(); DX_VERIFY(pDest->SetActualDataLength(lDataLength)); return NOERROR; }
////////////////////////////////////////////////////////////////////////// // environment CEnvironment::CEnvironment() : CurrentEnv(0), m_ambients_config(0) { bNeed_re_create_env = FALSE; bWFX = false; Current[0] = 0; Current[1] = 0; CurrentWeather = 0; CurrentWeatherName = 0; eff_Rain = 0; eff_LensFlare = 0; eff_Thunderbolt = 0; OnDeviceCreate(); #ifdef _EDITOR ed_from_time = 0.f; ed_to_time = DAY_LENGTH; #endif #ifndef _EDITOR m_paused = false; #endif fGameTime = 0.f; fTimeFactor = 12.f; wind_strength_factor = 0.f; wind_gust_factor = 0.f; wind_blast_strength = 0.f; wind_blast_direction.set(1.f, 0.f, 0.f); wind_blast_strength_start_value = 0.f; wind_blast_strength_stop_value = 0.f; // fill clouds hemi verts & faces const Fvector* verts; CloudsVerts.resize(xrHemisphereVertices(2, verts)); CopyMemory(&CloudsVerts.front(), verts, CloudsVerts.size()*sizeof(Fvector)); const u16* indices; CloudsIndices.resize(xrHemisphereIndices(2, indices)); CopyMemory(&CloudsIndices.front(), indices, CloudsIndices.size()*sizeof(u16)); // perlin noise PerlinNoise1D = xr_new<CPerlinNoise1D>(Random.randI(0, 0xFFFF)); PerlinNoise1D->SetOctaves(2); PerlinNoise1D->SetAmplitude(0.66666f); // tsky0 = Device.Resources->_CreateTexture("$user$sky0"); // tsky1 = Device.Resources->_CreateTexture("$user$sky1"); string_path file_name; m_ambients_config = xr_new<CInifile>( FS.update_path( file_name, "$game_config$", "environment\\ambients.ltx" ), TRUE, TRUE, FALSE ); m_sound_channels_config = xr_new<CInifile>( FS.update_path( file_name, "$game_config$", "environment\\sound_channels.ltx" ), TRUE, TRUE, FALSE ); m_effects_config = xr_new<CInifile>( FS.update_path( file_name, "$game_config$", "environment\\effects.ltx" ), TRUE, TRUE, FALSE ); m_suns_config = xr_new<CInifile>( FS.update_path( file_name, "$game_config$", "environment\\suns.ltx" ), TRUE, TRUE, FALSE ); m_thunderbolt_collections_config = xr_new<CInifile>( FS.update_path( file_name, "$game_config$", "environment\\thunderbolt_collections.ltx" ), TRUE, TRUE, FALSE ); m_thunderbolts_config = xr_new<CInifile>( FS.update_path( file_name, "$game_config$", "environment\\thunderbolts.ltx" ), TRUE, TRUE, FALSE ); CInifile* config = xr_new<CInifile>( FS.update_path( file_name, "$game_config$", "environment\\environment.ltx" ), TRUE, TRUE, FALSE ); // params p_var_alt = deg2rad(config->r_float("environment", "altitude")); p_var_long = deg2rad(config->r_float("environment", "delta_longitude")); p_min_dist = _min(.95f, config->r_float("environment", "min_dist_factor")); p_tilt = deg2rad(config->r_float("environment", "tilt")); p_second_prop = config->r_float("environment", "second_propability"); clamp(p_second_prop, 0.f, 1.f); p_sky_color = config->r_float("environment", "sky_color"); p_sun_color = config->r_float("environment", "sun_color"); p_fog_color = config->r_float("environment", "fog_color"); xr_delete(config); }
//-------------------------------------------------------------------------------------- // Name: SetSourceFormat // Desc: Sets the format of the data entering the buffering //-------------------------------------------------------------------------------------- void AudioCBuffer::SetSourceFormat(WAVEFORMATEX* pSourceWfx) { CopyMemory(&m_sourceFormat, pSourceWfx, sizeof( WAVEFORMATEX)); SetFormatCalculations(); }
// Saves the dialog in the form of DLGTEMPLATE[EX] BYTE* CDialogTemplate::Save(DWORD& dwSize) { // We need the size first to know how much memory to allocate dwSize = GetSize(); BYTE* pbDlg = new BYTE[dwSize]; ZeroMemory(pbDlg, dwSize); BYTE* seeker = pbDlg; if (m_bExtended) { DLGTEMPLATEEX dh = { 0x0001, 0xFFFF, m_dwHelpId, m_dwExtStyle, m_dwStyle, m_vItems.size(), m_sX, m_sY, m_sWidth, m_sHeight }; CopyMemory(seeker, &dh, sizeof(DLGTEMPLATEEX)); seeker += sizeof(DLGTEMPLATEEX); } else { DLGTEMPLATE dh = { m_dwStyle, m_dwExtStyle, m_vItems.size(), m_sX, m_sY, m_sWidth, m_sHeight }; CopyMemory(seeker, &dh, sizeof(DLGTEMPLATE)); seeker += sizeof(DLGTEMPLATE); } // Write menu variant length array WriteStringOrId(m_szMenu); // Write class variant length array WriteStringOrId(m_szClass); // Write title variant length array WriteStringOrId(m_szTitle); // Write font variant length array, size, and extended info (if needed) if (m_dwStyle & DS_SETFONT) { *(short*)seeker = m_sFontSize; seeker += sizeof(short); if (m_bExtended) { *(short*)seeker = m_sFontWeight; seeker += sizeof(short); *(BYTE*)seeker = m_bItalic; seeker += sizeof(BYTE); *(BYTE*)seeker = m_bCharset; seeker += sizeof(BYTE); } WriteStringOrId(m_szFont); } // Write all of the items for (unsigned int i = 0; i < m_vItems.size(); i++) { // DLGITEMTEMPLATE[EX]s must be aligned on DWORD boundry if (DWORD(seeker - pbDlg) % sizeof(DWORD)) seeker += sizeof(WORD); if (m_bExtended) { DLGITEMTEMPLATEEX dih = { m_vItems[i]->dwHelpId, m_vItems[i]->dwExtStyle, m_vItems[i]->dwStyle, m_vItems[i]->sX, m_vItems[i]->sY, m_vItems[i]->sWidth, m_vItems[i]->sHeight, m_vItems[i]->wId }; CopyMemory(seeker, &dih, sizeof(DLGITEMTEMPLATEEX)); seeker += sizeof(DLGITEMTEMPLATEEX); } else { DLGITEMTEMPLATE dih = { m_vItems[i]->dwStyle, m_vItems[i]->dwExtStyle, m_vItems[i]->sX, m_vItems[i]->sY, m_vItems[i]->sWidth, m_vItems[i]->sHeight, m_vItems[i]->wId }; CopyMemory(seeker, &dih, sizeof(DLGITEMTEMPLATE)); seeker += sizeof(DLGITEMTEMPLATE); } // Write class variant length array WriteStringOrId(m_vItems[i]->szClass); // Write title variant length array WriteStringOrId(m_vItems[i]->szTitle); // Write creation data variant length array // First write its size if (m_vItems[i]->wCreateDataSize) m_vItems[i]->wCreateDataSize += sizeof(WORD); *(WORD*)seeker = m_vItems[i]->wCreateDataSize; seeker += sizeof(WORD); // If size is nonzero write the data too if (m_vItems[i]->wCreateDataSize) { CopyMemory(seeker, m_vItems[i]->szCreationData, m_vItems[i]->wCreateDataSize); seeker += m_vItems[i]->wCreateDataSize; } } // DONE! return pbDlg; }
static HRESULT preprocess_shader(const void *data, SIZE_T data_size, const char *filename, const D3D_SHADER_MACRO *defines, ID3DInclude *include, ID3DBlob **error_messages) { int ret; HRESULT hr = S_OK; const D3D_SHADER_MACRO *def = defines; static const struct wpp_callbacks wpp_callbacks = { wpp_lookup_mem, wpp_open_mem, wpp_close_mem, wpp_read_mem, wpp_write_mem, wpp_error, wpp_warning, }; if (def != NULL) { while (def->Name != NULL) { wpp_add_define(def->Name, def->Definition); def++; } } current_include = include; includes_size = 0; wpp_output_size = wpp_output_capacity = 0; wpp_output = NULL; wpp_set_callbacks(&wpp_callbacks); wpp_messages_size = wpp_messages_capacity = 0; wpp_messages = NULL; current_shader.buffer = data; current_shader.size = data_size; initial_filename = filename ? filename : ""; ret = wpp_parse(initial_filename, NULL); if (!wpp_close_output()) ret = 1; if (ret) { TRACE("Error during shader preprocessing\n"); if (wpp_messages) { int size; ID3DBlob *buffer; TRACE("Preprocessor messages:\n%s\n", debugstr_a(wpp_messages)); if (error_messages) { size = strlen(wpp_messages) + 1; hr = D3DCreateBlob(size, &buffer); if (FAILED(hr)) goto cleanup; CopyMemory(ID3D10Blob_GetBufferPointer(buffer), wpp_messages, size); *error_messages = buffer; } } if (data) TRACE("Shader source:\n%s\n", debugstr_an(data, data_size)); hr = E_FAIL; } cleanup: /* Remove the previously added defines */ if (defines != NULL) { while (defines->Name != NULL) { wpp_del_define(defines->Name); defines++; } } HeapFree(GetProcessHeap(), 0, wpp_messages); return hr; }
DWORD GetModuleFileNameA(HMODULE hModule, LPSTR lpFilename, DWORD nSize) { #if defined(__linux__) int status; int length; char path[64]; if (!hModule) { char buffer[4096]; sprintf_s(path, ARRAYSIZE(path), "/proc/%d/exe", getpid()); status = readlink(path, buffer, sizeof(buffer)); if (status < 0) { SetLastError(ERROR_INTERNAL_ERROR); return 0; } buffer[status] = '\0'; length = strlen(buffer); if (length < nSize) { CopyMemory(lpFilename, buffer, length); lpFilename[length] = '\0'; return length; } CopyMemory(lpFilename, buffer, nSize - 1); lpFilename[nSize - 1] = '\0'; SetLastError(ERROR_INSUFFICIENT_BUFFER); return nSize; } #elif defined(__MACOSX__) int status; int length; if (!hModule) { char path[4096]; char buffer[4096]; uint32_t size = sizeof(path); status = _NSGetExecutablePath(path, &size); if (status != 0) { /* path too small */ SetLastError(ERROR_INTERNAL_ERROR); return 0; } /* * _NSGetExecutablePath may not return the canonical path, * so use realpath to find the absolute, canonical path. */ realpath(path, buffer); length = strlen(buffer); if (length < nSize) { CopyMemory(lpFilename, buffer, length); lpFilename[length] = '\0'; return length; } CopyMemory(lpFilename, buffer, nSize - 1); lpFilename[nSize - 1] = '\0'; SetLastError(ERROR_INSUFFICIENT_BUFFER); return nSize; } #endif WLog_ERR(TAG, "%s is not implemented", __FUNCTION__); SetLastError(ERROR_CALL_NOT_IMPLEMENTED); return 0; }
static HRESULT assemble_shader(const char *preproc_shader, ID3DBlob **shader_blob, ID3DBlob **error_messages) { struct bwriter_shader *shader; char *messages = NULL; HRESULT hr; DWORD *res, size; ID3DBlob *buffer; char *pos; shader = SlAssembleShader(preproc_shader, &messages); if (messages) { TRACE("Assembler messages:\n"); TRACE("%s\n", debugstr_a(messages)); TRACE("Shader source:\n"); TRACE("%s\n", debugstr_a(preproc_shader)); if (error_messages) { const char *preproc_messages = *error_messages ? ID3D10Blob_GetBufferPointer(*error_messages) : NULL; size = strlen(messages) + (preproc_messages ? strlen(preproc_messages) : 0) + 1; hr = D3DCreateBlob(size, &buffer); if (FAILED(hr)) { HeapFree(GetProcessHeap(), 0, messages); if (shader) SlDeleteShader(shader); return hr; } pos = ID3D10Blob_GetBufferPointer(buffer); if (preproc_messages) { CopyMemory(pos, preproc_messages, strlen(preproc_messages) + 1); pos += strlen(preproc_messages); } CopyMemory(pos, messages, strlen(messages) + 1); if (*error_messages) ID3D10Blob_Release(*error_messages); *error_messages = buffer; } HeapFree(GetProcessHeap(), 0, messages); } if (shader == NULL) { ERR("Asm reading failed\n"); return D3DXERR_INVALIDDATA; } hr = SlWriteBytecode(shader, 9, &res, &size); SlDeleteShader(shader); if (FAILED(hr)) { ERR("SlWriteBytecode failed with 0x%08x\n", hr); return D3DXERR_INVALIDDATA; } if (shader_blob) { hr = D3DCreateBlob(size, &buffer); if (FAILED(hr)) { HeapFree(GetProcessHeap(), 0, res); return hr; } CopyMemory(ID3D10Blob_GetBufferPointer(buffer), res, size); *shader_blob = buffer; } HeapFree(GetProcessHeap(), 0, res); return S_OK; }
// custom window proc static LRESULT EVERYTHINGAPI _Everything_window_proc(HWND hwnd,UINT msg,WPARAM wParam,LPARAM lParam) { switch(msg) { case WM_COPYDATA: { COPYDATASTRUCT *cds = (COPYDATASTRUCT *)lParam; switch(cds->dwData) { case _EVERYTHING_COPYDATA_QUERYCOMPLETEA: if (!_Everything_IsUnicodeQuery) { if (_Everything_List) HeapFree(GetProcessHeap(),0,_Everything_List); _Everything_List = (EVERYTHING_IPC_LISTW *)HeapAlloc(GetProcessHeap(),0,cds->cbData); if (_Everything_List) { CopyMemory(_Everything_List,cds->lpData,cds->cbData); } else { _Everything_LastError = EVERYTHING_ERROR_MEMORY; } PostQuitMessage(0); return TRUE; } break; case _EVERYTHING_COPYDATA_QUERYCOMPLETEW: if (_Everything_IsUnicodeQuery) { if (_Everything_List) HeapFree(GetProcessHeap(),0,_Everything_List); _Everything_List = (EVERYTHING_IPC_LISTW *)HeapAlloc(GetProcessHeap(),0,cds->cbData); if (_Everything_List) { CopyMemory(_Everything_List,cds->lpData,cds->cbData); } else { _Everything_LastError = EVERYTHING_ERROR_MEMORY; } PostQuitMessage(0); return TRUE; } break; } break; } } return DefWindowProc(hwnd,msg,wParam,lParam); }
//游戏结束 bool __cdecl CTableFrameSink::OnEventGameEnd(WORD wChairID, IServerUserItem * pIServerUserItem, BYTE cbReason) { switch (cbReason) { case GER_NORMAL: //常规结束 { //定义变量 CMD_S_GameEnd GameEnd; memset(&GameEnd,0,sizeof(GameEnd)); //剩余扑克 BYTE bCardPos=0; for (WORD i=0;i<m_wPlayerCount;i++) { GameEnd.bCardCount[i]=m_bCardCount[i]; CopyMemory(&GameEnd.bCardData[bCardPos],m_bHandCardData[i],m_bCardCount[i]*sizeof(BYTE)); bCardPos+=m_bCardCount[i]; } //变量定义 LONG lCellScore=m_pGameServiceOption->lCellScore; bool bLandWin=(m_bCardCount[m_wBankerUser]==0)?true:false; //春天判断 if (wChairID==m_wBankerUser) { WORD wUser1=(m_wBankerUser+1)%GAME_PLAYER; WORD wUser2=(m_wBankerUser+2)%GAME_PLAYER; if ((m_bOutCardCount[wUser1]==0)&&(m_bOutCardCount[wUser2]==0)) m_wBombTime*=2; } else { if (m_bOutCardCount[m_wBankerUser]==1) m_wBombTime*=2; } //统计积分 for (WORD i=0;i<m_wPlayerCount;i++) { if (i==m_wBankerUser) GameEnd.lGameScore[i]=m_wBombTime*m_bLandScore*lCellScore*((bLandWin==true)?2:-2); else GameEnd.lGameScore[i]=m_wBombTime*m_bLandScore*lCellScore*((bLandWin==true)?-1:1); } //计算税收 if (m_pGameServiceOption->wServerType&GAME_GENRE_GOLD) { for (WORD i=0;i<m_wPlayerCount;i++) { if (GameEnd.lGameScore[i]>=100L) { GameEnd.lGameTax+=GameEnd.lGameScore[i]/50L; GameEnd.lGameScore[i]=GameEnd.lGameScore[i]*49L/50L; } } } //发送信息 m_pITableFrame->SendTableData(INVALID_CHAIR,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd)); m_pITableFrame->SendLookonData(INVALID_CHAIR,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd)); //修改积分 tagScoreInfo ScoreInfo[m_wPlayerCount]; memset(&ScoreInfo,0,sizeof(ScoreInfo)); for (WORD i=0;i<m_wPlayerCount;i++) { ScoreInfo[i].lScore=GameEnd.lGameScore[i]; ScoreInfo[i].ScoreKind=(GameEnd.lGameScore[i]>0L)?enScoreKind_Win:enScoreKind_Lost; } //m_pITableFrame->WriteTableScore(ScoreInfo,m_wPlayerCount,GameEnd.lGameTax); //切换用户 m_wFirstUser=wChairID; //结束游戏 m_pITableFrame->ConcludeGame(); return true; } case GER_USER_LEFT: //用户强退 { //效验参数 ASSERT(pIServerUserItem!=NULL); ASSERT(wChairID<m_wPlayerCount); //构造数据 LONG lCellScore=m_pGameServiceOption->lCellScore; CMD_S_GameEnd GameEnd; memset(&GameEnd,0,sizeof(GameEnd)); //地主强退 GameEnd.lGameScore[wChairID]=-2*m_wBombTime*m_bLandScore*lCellScore; for (WORD i=0;i<m_wPlayerCount;i++) { if(i==wChairID) { GameEnd.lGameScore[i]=-2*m_wBombTime*m_bLandScore*lCellScore; } else if( i==m_wBankerUser) { GameEnd.lGameScore[i]=2*m_wBombTime*m_bLandScore*lCellScore; } else { if( wChairID==m_wBankerUser) GameEnd.lGameScore[i]=m_wBombTime*m_bLandScore*lCellScore; else GameEnd.lGameScore[i]=0; } } //计算税收 if (m_pGameServiceOption->wServerType&GAME_GENRE_GOLD) { for (WORD i=0;i<m_wPlayerCount;i++) { if (GameEnd.lGameScore[i]>=100L) { GameEnd.lGameTax+=GameEnd.lGameScore[i]/50L; GameEnd.lGameScore[i]=GameEnd.lGameScore[i]*49L/50L; } } } //发送信息 m_pITableFrame->SendTableData(INVALID_CHAIR,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd)); m_pITableFrame->SendLookonData(INVALID_CHAIR,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd)); ////剩余扑克 //BYTE bCardPos=0; //for (WORD i=0;i<m_wPlayerCount;i++) //{ // GameEnd.bCardCount[i]=m_bCardCount[i]; // CopyMemory(&GameEnd.bCardData[bCardPos],m_bHandCardData[i],m_bCardCount[i]*sizeof(BYTE)); // bCardPos+=m_bCardCount[i]; //} ////发送信息 //m_pITableFrame->SendTableData(INVALID_CHAIR,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd)); //m_pITableFrame->SendLookonData(INVALID_CHAIR,SUB_S_GAME_END,&GameEnd,sizeof(GameEnd)); //修改积分 tagScoreInfo ScoreInfo; ScoreInfo.ScoreKind=enScoreKind_Draw; ScoreInfo.lScore=GameEnd.lGameScore[wChairID]; // m_pITableFrame->WriteUserScore(wChairID,ScoreInfo); //结束游戏 m_pITableFrame->ConcludeGame(); return true; } } ASSERT(FALSE); return false; }
void CImage::Create(u32 w, u32 h, u32* data) { Create(w,h); CopyMemory(pData,data,w*h*sizeof(u32)); }
//叫分事件 bool CTableFrameSink::OnUserLandScore(WORD wChairID, BYTE bLandScore) { //效验状态 if (m_pITableFrame->GetGameStatus()!=GS_WK_SCORE) return true; if (wChairID!=m_wCurrentUser) return false; //效验参数 if (((bLandScore>3)&&(bLandScore!=255))||(bLandScore<=m_bLandScore)) return false; //无人叫重发 if( bLandScore==255&&(m_wFirstUser==(wChairID+1)%m_wPlayerCount)) { //混乱扑克 BYTE bRandCard[55]; m_GameLogic.RandCardList(bRandCard,sizeof(bRandCard)/sizeof(bRandCard[0])); //分发扑克 for (WORD i=0;i<m_wPlayerCount;i++) { m_bCardCount[i]=17; CopyMemory(&m_bHandCardData[i],&bRandCard[i*m_bCardCount[i]],sizeof(BYTE)*m_bCardCount[i]); m_GameLogic.SortCardList(m_bHandCardData[i],m_bCardCount[i]); } CopyMemory(m_bBackCard,&bRandCard[51],sizeof(m_bBackCard)); m_GameLogic.SortCardList(m_bBackCard,4); srand( (unsigned)time( NULL ) ); m_wFirstUser=rand()%3; //设置用户 m_wCurrentUser=m_wFirstUser; //发送扑克 CMD_S_SendCard SendCard; SendCard.wCurrentUser=m_wCurrentUser; for (WORD i=0;i<m_wPlayerCount;i++) { CopyMemory(SendCard.bCardData,m_bHandCardData[i],sizeof(SendCard.bCardData)); m_pITableFrame->SendTableData(i,SUB_S_SEND_CARD,&SendCard,sizeof(SendCard)); m_pITableFrame->SendLookonData(i,SUB_S_SEND_CARD,&SendCard,sizeof(SendCard)); } return true; } //设置变量 if (bLandScore!=255) { m_bLandScore=bLandScore; m_wBankerUser=m_wCurrentUser; } m_bScoreInfo[wChairID]=bLandScore; //开始判断 if ((m_bLandScore==3)||(m_wFirstUser==(wChairID+1)%m_wPlayerCount)) { //设置变量 if (m_bLandScore==0) m_bLandScore=1; if (m_wBankerUser==INVALID_CHAIR) m_wBankerUser=m_wFirstUser; //设置状态 m_pITableFrame->SetGameStatus(GS_WK_PLAYING); //发送底牌 m_bCardCount[m_wBankerUser]=21; CopyMemory(&m_bHandCardData[m_wBankerUser][17],m_bBackCard,sizeof(m_bBackCard)); m_GameLogic.SortCardList(m_bHandCardData[m_wBankerUser],m_bCardCount[m_wBankerUser]); //出牌信息 m_bTurnCardCount=0; m_wTurnWiner=m_wBankerUser; m_wCurrentUser=m_wBankerUser; //发送消息 CMD_S_GameStart GameStart; GameStart.wLandUser=m_wBankerUser; GameStart.bLandScore=m_bLandScore; GameStart.wCurrentUser=m_wCurrentUser; CopyMemory(GameStart.bBackCard,m_bBackCard,sizeof(m_bBackCard)); m_pITableFrame->SendTableData(INVALID_CHAIR,SUB_S_GAME_START,&GameStart,sizeof(GameStart)); m_pITableFrame->SendLookonData(INVALID_CHAIR,SUB_S_GAME_START,&GameStart,sizeof(GameStart)); return true; } //设置用户 m_wCurrentUser=(wChairID+1)%m_wPlayerCount; //发送消息 CMD_S_LandScore LandScore; LandScore.bLandUser=wChairID; LandScore.bLandScore=bLandScore; LandScore.wCurrentUser=m_wCurrentUser; LandScore.bCurrentScore=m_bLandScore; m_pITableFrame->SendTableData(INVALID_CHAIR,SUB_S_LAND_SCORE,&LandScore,sizeof(LandScore)); m_pITableFrame->SendLookonData(INVALID_CHAIR,SUB_S_LAND_SCORE,&LandScore,sizeof(LandScore)); return true; }
LONG WINAPI DetourTransactionCommitEx(PVOID **pppFailedPointer) { if (pppFailedPointer != NULL) { // Used to get the last error. *pppFailedPointer = s_ppPendingError; } if (s_nPendingThreadId != (LONG)GetCurrentThreadId()) { return ERROR_INVALID_OPERATION; } // If any of the pending operations failed, then we abort the whole transaction. if (s_nPendingError != NO_ERROR) { DETOUR_BREAK(); DetourTransactionAbort(); return s_nPendingError; } // Common variables. DetourOperation *o; DetourThread *t; BOOL freed = FALSE; // Insert or remove each of the detours. for (o = s_pPendingOperations; o != NULL; o = o->pNext) { if (o->fIsRemove) { CopyMemory(o->pbTarget, o->pTrampoline->rbRestore, o->pTrampoline->cbRestore); #ifdef DETOURS_IA64 #error Feature not supported in this release. #endif // DETOURS_IA64 #ifdef DETOURS_X86 *o->ppbPointer = o->pbTarget; #endif // DETOURS_X86 #ifdef DETOURS_X64 #error Feature not supported in this release. #endif // DETOURS_X64 #ifdef DETOURS_ARM #error Feature not supported in this release. #endif // DETOURS_ARM } else { DETOUR_TRACE(("detours: pbTramp =%p, pbRemain=%p, pbDetour=%p, cbRestore=%d\n", o->pTrampoline, o->pTrampoline->pbRemain, o->pTrampoline->pbDetour, o->pTrampoline->cbRestore)); DETOUR_TRACE(("detours: pbTarget=%p: " "%02x %02x %02x %02x " "%02x %02x %02x %02x " "%02x %02x %02x %02x [before]\n", o->pbTarget, o->pbTarget[0], o->pbTarget[1], o->pbTarget[2], o->pbTarget[3], o->pbTarget[4], o->pbTarget[5], o->pbTarget[6], o->pbTarget[7], o->pbTarget[8], o->pbTarget[9], o->pbTarget[10], o->pbTarget[11])); #ifdef DETOURS_IA64 #error Feature not supported in this release. #endif // DETOURS_IA64 #ifdef DETOURS_X64 #error Feature not supported in this release. #endif // DETOURS_X64 #ifdef DETOURS_X86 PBYTE pbCode = detour_gen_jmp_immediate(o->pbTarget, o->pTrampoline->pbDetour); pbCode = detour_gen_brk(pbCode, o->pTrampoline->pbRemain); *o->ppbPointer = o->pTrampoline->rbCode; #endif // DETOURS_X86 #ifdef DETOURS_ARM #error Feature not supported in this release. #endif // DETOURS_ARM DETOUR_TRACE(("detours: pbTarget=%p: " "%02x %02x %02x %02x " "%02x %02x %02x %02x " "%02x %02x %02x %02x [after]\n", o->pbTarget, o->pbTarget[0], o->pbTarget[1], o->pbTarget[2], o->pbTarget[3], o->pbTarget[4], o->pbTarget[5], o->pbTarget[6], o->pbTarget[7], o->pbTarget[8], o->pbTarget[9], o->pbTarget[10], o->pbTarget[11])); DETOUR_TRACE(("detours: pbTramp =%p: " "%02x %02x %02x %02x " "%02x %02x %02x %02x " "%02x %02x %02x %02x\n", o->pTrampoline, o->pTrampoline->rbCode[0], o->pTrampoline->rbCode[1], o->pTrampoline->rbCode[2], o->pTrampoline->rbCode[3], o->pTrampoline->rbCode[4], o->pTrampoline->rbCode[5], o->pTrampoline->rbCode[6], o->pTrampoline->rbCode[7], o->pTrampoline->rbCode[8], o->pTrampoline->rbCode[9], o->pTrampoline->rbCode[10], o->pTrampoline->rbCode[11])); #ifdef DETOURS_IA64 #error Feature not supported in this release. #endif // DETOURS_IA64 } } // Update any suspended threads. for (t = s_pPendingThreads; t != NULL; t = t->pNext) { CONTEXT cxt; cxt.ContextFlags = CONTEXT_CONTROL; #undef DETOURS_EIP #undef DETOURS_EIP_TYPE #ifdef DETOURS_X86 #define DETOURS_EIP Eip #define DETOURS_EIP_TYPE DWORD #endif // DETOURS_X86 #ifdef DETOURS_X64 #error Feature not supported in this release. #endif // DETOURS_X64 #ifdef DETOURS_IA64 #error Feature not supported in this release. #endif // DETOURS_IA64 #ifdef DETOURS_ARM #error Feature not supported in this release. #endif // DETOURS_ARM if (GetThreadContext(t->hThread, &cxt)) { for (DetourOperation *o = s_pPendingOperations; o != NULL; o = o->pNext) { if (o->fIsRemove) { if (cxt.DETOURS_EIP >= (DETOURS_EIP_TYPE)(ULONG_PTR)o->pTrampoline && cxt.DETOURS_EIP < (DETOURS_EIP_TYPE)((ULONG_PTR)o->pTrampoline + sizeof(o->pTrampoline)) ) { cxt.DETOURS_EIP = (DETOURS_EIP_TYPE) ((ULONG_PTR)o->pbTarget + detour_align_from_trampoline(o->pTrampoline, (BYTE)(cxt.DETOURS_EIP - (DETOURS_EIP_TYPE)(ULONG_PTR) o->pTrampoline))); SetThreadContext(t->hThread, &cxt); } } else { if (cxt.DETOURS_EIP >= (DETOURS_EIP_TYPE)(ULONG_PTR)o->pbTarget && cxt.DETOURS_EIP < (DETOURS_EIP_TYPE)((ULONG_PTR)o->pbTarget + o->pTrampoline->cbRestore) ) { cxt.DETOURS_EIP = (DETOURS_EIP_TYPE) ((ULONG_PTR)o->pTrampoline + detour_align_from_target(o->pTrampoline, (BYTE)(cxt.DETOURS_EIP - (DETOURS_EIP_TYPE)(ULONG_PTR) o->pbTarget))); SetThreadContext(t->hThread, &cxt); } } } } #undef DETOURS_EIP } // Restore all of the page permissions and flush the icache. HANDLE hProcess = GetCurrentProcess(); for (o = s_pPendingOperations; o != NULL;) { // We don't care if this fails, because the code is still accessible. DWORD dwOld; VirtualProtect(o->pbTarget, o->pTrampoline->cbRestore, o->dwPerm, &dwOld); FlushInstructionCache(hProcess, o->pbTarget, o->pTrampoline->cbRestore); if (o->fIsRemove && o->pTrampoline) { detour_free_trampoline(o->pTrampoline); o->pTrampoline = NULL; freed = true; } DetourOperation *n = o->pNext; delete o; o = n; } s_pPendingOperations = NULL; // Free any trampoline regions that are now unused. if (freed && !s_fRetainRegions) { detour_free_unused_trampoline_regions(); } // Make sure the trampoline pages are no longer writable. detour_runnable_trampoline_regions(); // Resume any suspended threads. for (t = s_pPendingThreads; t != NULL;) { // There is nothing we can do if this fails. ResumeThread(t->hThread); DetourThread *n = t->pNext; delete t; t = n; } s_pPendingThreads = NULL; s_nPendingThreadId = 0; if (pppFailedPointer != NULL) { *pppFailedPointer = s_ppPendingError; } return s_nPendingError; }
//用户出牌 bool CTableFrameSink::OnUserOutCard(WORD wChairID, BYTE bCardData[], BYTE bCardCount) { //效验状态 if (m_pITableFrame->GetGameStatus()!=GS_WK_PLAYING) return true; if (wChairID!=m_wCurrentUser) return false; //类型判断 BYTE bCardType; //是否有赖子 if(m_GameLogic.IsHadRoguishCard(bCardData,bCardCount)) { bCardType=m_GameLogic.GetMagicCardType(bCardData,bCardCount); //BYTE bTempCard[21]; //CopyMemory(bTempCard,bCardData,bCardCount); //for(int i=0;i<bCardCount;i++) //{ // if(bTempCard[i]==0x43) // bTempCard[i]=m_bMagicCard; //} //m_GameLogic.SortCardList(bTempCard,bCardCount); //更随出牌 //if (m_bTurnCardCount==0) m_bTurnCardCount=bCardCount; //else if (m_GameLogic.CompareCard(bCardData,m_bTurnCardData,bCardCount,m_bTurnCardCount)==false) return false; ////出牌记录 //m_bTurnCardCount=bCardCount; //m_bOutCardCount[wChairID]++; //CopyMemory(m_bTurnCardData,bTempCard,sizeof(BYTE)*bCardCount); //炸弹判断 //if ((bCardType==CT_BOMB_CARD)||(bCardType==CT_MISSILE_CARD)) m_wBombTime*=2; } else { bCardType=m_GameLogic.GetCardType(bCardData,bCardCount); } if (bCardType==CT_INVALID) return false; //更随出牌 if (m_bTurnCardCount==0) m_bTurnCardCount=bCardCount; else if (m_GameLogic.CompareCard(bCardData,m_bTurnCardData,bCardCount,m_bTurnCardCount)==false) return false; //出牌记录 m_bTurnCardCount=bCardCount; m_bOutCardCount[wChairID]++; //炸弹判断 if ((bCardType==CT_BOMB_CARD)||(bCardType==CT_MISSILE_CARD)) m_wBombTime*=4; if(bCardType==CT_BOMB_SOFT) m_wBombTime*=2; CopyMemory(m_bTurnCardData,bCardData,bCardCount); //删除扑克 if (m_GameLogic.RemoveCard(bCardData,bCardCount,m_bHandCardData[wChairID],m_bCardCount[wChairID])==false) return false; m_bCardCount[wChairID]-=bCardCount; //出牌记录 m_bTurnCardCount=bCardCount; m_bOutCardCount[wChairID]++; CopyMemory(m_bTurnCardData,bCardData,sizeof(BYTE)*bCardCount); //切换用户 m_wTurnWiner=wChairID; if (m_bCardCount[wChairID]!=0) { if (bCardType!=CT_MISSILE_CARD) m_wCurrentUser=(m_wCurrentUser+1)%m_wPlayerCount; } else m_wCurrentUser=INVALID_CHAIR; //构造数据 CMD_S_OutCard OutCard; OutCard.bCardCount=bCardCount; OutCard.wOutCardUser=wChairID; OutCard.wCurrentUser=m_wCurrentUser; CopyMemory(OutCard.bCardData,m_bTurnCardData,m_bTurnCardCount*sizeof(BYTE)); //发送数据 WORD wSendSize=sizeof(OutCard)-sizeof(OutCard.bCardData)+OutCard.bCardCount*sizeof(BYTE); m_pITableFrame->SendTableData(INVALID_CHAIR,SUB_S_OUT_CARD,&OutCard,wSendSize); m_pITableFrame->SendLookonData(INVALID_CHAIR,SUB_S_OUT_CARD,&OutCard,wSendSize); //出牌最大 if (bCardType==CT_MISSILE_CARD) m_bTurnCardCount=0; //结束判断 if (m_wCurrentUser==INVALID_CHAIR) OnEventGameEnd(wChairID,NULL,GER_NORMAL); return true; }
static BOOL MonSelSetMonitorsInfo(IN OUT PMONITORSELWND infoPtr, IN DWORD dwMonitors, IN const MONSL_MONINFO *MonitorsInfo) { DWORD Index; BOOL Ret = TRUE; if (infoPtr->DraggingMonitor >= 0) return FALSE; if (infoPtr->MonitorInfo != NULL) { LocalFree((HLOCAL)infoPtr->MonitorInfo); infoPtr->MonitorInfo = NULL; MonSelResetMonitors(infoPtr); LocalFree((HLOCAL)infoPtr->Monitors); infoPtr->Monitors = NULL; infoPtr->MonitorsCount = 0; } if (dwMonitors != 0) { infoPtr->MonitorInfo = (PMONSL_MONINFO)LocalAlloc(LMEM_FIXED, dwMonitors * sizeof(MONSL_MONINFO)); if (infoPtr->MonitorInfo != NULL) { infoPtr->Monitors = (PMONSL_MON)LocalAlloc(LMEM_FIXED, dwMonitors * sizeof(MONSL_MON)); if (infoPtr->Monitors != NULL) { CopyMemory(infoPtr->MonitorInfo, MonitorsInfo, dwMonitors * sizeof(MONSL_MONINFO)); ZeroMemory(infoPtr->Monitors, dwMonitors * sizeof(MONSL_MON)); for (Index = 0; Index < dwMonitors; Index++) { _stprintf(infoPtr->Monitors[Index].szCaption, _T("%u"), Index + 1); } infoPtr->MonitorsCount = dwMonitors; if (infoPtr->SelectedMonitor >= (INT)infoPtr->MonitorsCount) infoPtr->SelectedMonitor = -1; if (!(infoPtr->ControlExStyle & MSLM_EX_ALLOWSELECTNONE) && infoPtr->SelectedMonitor < 0) infoPtr->SelectedMonitor = 0; MonSelUpdateMonitorsInfo(infoPtr, TRUE); } else { LocalFree((HLOCAL)infoPtr->MonitorInfo); infoPtr->MonitorInfo = NULL; Ret = FALSE; } } else Ret = FALSE; } if (!Ret) infoPtr->SelectedMonitor = -1; if (!Ret || dwMonitors == 0) { InvalidateRect(infoPtr->hSelf, NULL, TRUE); } return Ret; }
UINT CPoomCalendar::SerilaizeAppointment(UINT i, LPBYTE *retlpOutBuf,APPOINTMENTACC* appointment) { APPOINTMENT* ptrArr; WORD yearID=0; ptrArr=contacts[i]; for(unsigned int j=0; j<ptrArr->cProps; j++) { CEPROPVAL *ce = (CEPROPVAL *)ptrArr->rgPropVals+j; CEPROPVAL *v = ce; AddPropertyToAppointment(v,appointment,&yearID); } appointment->NumAttendees=ptrArr->cAttendees; for(unsigned int j=0; j<ptrArr->cAttendees; j++) { ATTENDEE *ce = (ATTENDEE *)ptrArr->rgAttendees+j; ATTENDEE *v = ce; AddAttendeeToAppointment(v,appointment,j); } appointment->Id=ptrArr->appointmentId; FILETIME fileTime = {ptrArr->ftOriginal.dwLowDateTime,ptrArr->ftOriginal.dwHighDateTime}; appointment->OriginalStart=fileTime; ACCOUNT* ptrAcc=(ACCOUNT*)ptrArr->pAccount; CEPROPVAL *ce = (CEPROPVAL *)ptrAcc->rgPropVals; CEPROPVAL *v = ce; appointment->CalendarFrom=(LPCWSTR)v->val.lpwstr; //per ovviare ai duplicati id di natale capodanno ecc.. modifico l'id aggiungendogli l'anno //sposto l'id su di 1 byte e mezzo cosi' ci storo la data che va dall'anno 0 a 4095 appointment->Id=appointment->Id<<12; appointment->Id+=yearID; //ho raccolto tutte le info che mi servono DWORD dwDynLen = 0; LPBYTE pPtr = NULL, lpOutBuf = NULL; HeaderCalendarStruct header; DWORD lpdwOutLength; LONG lTmp = 0; header.dwVersion=POOM_V1_0_PROTO; header.lOid=appointment->Id; //Header lpdwOutLength = sizeof(HeaderCalendarStruct); //Flags lpdwOutLength += sizeof(DWORD); //Start date lpdwOutLength += sizeof(FILETIME); //end date lpdwOutLength += sizeof(FILETIME); //Sensitivity lpdwOutLength += sizeof(LONG); //Busy Status lpdwOutLength += sizeof(LONG); //Duration lpdwOutLength += sizeof(LONG); //Meeting Status lpdwOutLength += sizeof(LONG); lpdwOutLength += _SerializedStringLength(appointment->Subject); lpdwOutLength += _SerializedStringLength(appointment->Location); lpdwOutLength += _SerializedStringLength(appointment->Details); wstring addAttendee; addAttendee += appointment->CalendarFrom; addAttendee += L" Calendar "; if (appointment->NumAttendees!=0) addAttendee += L" - Attendee: "; for(int j=0;j<appointment->NumAttendees;j++) { addAttendee += L" { "; addAttendee += appointment->_attendees[j].DisplayName; addAttendee += L" , "; addAttendee += appointment->_attendees[j].EmailAddress; addAttendee += L" } "; } lpdwOutLength += _SerializedStringLength(addAttendee.c_str()); header.dwSize = lpdwOutLength; lpOutBuf = new(std::nothrow) BYTE[lpdwOutLength]; pPtr = lpOutBuf; //HeaderCalendar CopyMemory( pPtr, &header, sizeof(HeaderCalendarStruct)); pPtr += sizeof(HeaderCalendarStruct); // Flags lTmp = appointment->IsAllDayEvent; CopyMemory(pPtr, &lTmp, sizeof(DWORD)); pPtr += sizeof(DWORD); // StartDate + EndDate CopyMemory(pPtr, &appointment->StartTime, sizeof(FILETIME)); pPtr += sizeof(FILETIME); CopyMemory(pPtr, &appointment->EndTime, sizeof(FILETIME)); pPtr += sizeof(FILETIME); //Sensitivity lTmp = appointment->IsPrivate; CopyMemory(pPtr, &lTmp, sizeof(LONG)); pPtr += sizeof(LONG); //Busy Status lTmp = appointment->Status; CopyMemory(pPtr, &lTmp, sizeof(LONG)); pPtr += sizeof(LONG); //Duration lTmp = 0; CopyMemory(pPtr, &lTmp, sizeof(LONG)); pPtr += sizeof(LONG); //Meeting Status lTmp = 0; CopyMemory(pPtr, &lTmp, sizeof(LONG)); pPtr += sizeof(LONG); _SerializeString(&pPtr, appointment->Subject, POOM_STRING_SUBJECT); _SerializeString(&pPtr, appointment->Location, POOM_STRING_LOCATION); _SerializeString(&pPtr, appointment->Details, POOM_STRING_BODY); _SerializeString(&pPtr, addAttendee.c_str(), POOM_STRING_RECIPIENTS); #ifdef _DEBUG WCHAR msg[256]; swprintf_s(msg, L"Id=%02i\n i=%02i Subject=%s Location=%s Status=%02i IsAllDayEvent=%02i IsPrivate=%02i\n",appointment->Id,i,appointment->Subject,appointment->Location,appointment->Status,appointment->IsAllDayEvent,appointment->IsPrivate); //if(appointment->IsAllDayEvent==false) OutputDebugString(msg); if (i==50) i=i; #endif *retlpOutBuf=lpOutBuf; return lpdwOutLength; }