bool RenderContextWGL::Create(void* osWnd) { window = static_cast<HWND>(osWnd); int glmajor = 3; int glminor = 3; int colorBits = 32; int depthBits = 24; int stencilBits = 0; int samples = 0; InitGLEW(); int attrs[] = { WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_SAMPLE_BUFFERS_ARB, samples > 0 ? GL_TRUE : GL_FALSE, WGL_SAMPLES_ARB, samples, WGL_COLOR_BITS_ARB, colorBits, WGL_DEPTH_BITS_ARB, depthBits, WGL_STENCIL_BITS_ARB, stencilBits, WGL_ALPHA_BITS_ARB, colorBits == 32 ? 8 : 0, 0 }; int pixelFormat; unsigned numFormats = 0; gdiDc = GetDC(window); int result = wglChoosePixelFormatARB(gdiDc, attrs, nullptr, 1, &pixelFormat, &numFormats); if (result == 0 || numFormats == 0) { Log::E("wglChoosePixelFormatARB failed"); } // info PIXELFORMATDESCRIPTOR pfd; DescribePixelFormat(gdiDc, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd); Log::V() << "Pixel format:\tcColorBits " << (int)pfd.cColorBits << ", cDepthBits " << (int)pfd.cDepthBits << "\n\t\t\tcAlphaBits " << (int)pfd.cAlphaBits << ", cStencilBits " << (int)pfd.cStencilBits; if (!SetPixelFormat(gdiDc, pixelFormat, &pfd)) { Log::E("SetPixelFormat"); } int contextAttrs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, glmajor, // OpenGL 3.3 provides full compatibility with OpenGL ES 3.0. WGL_CONTEXT_MINOR_VERSION_ARB, glminor, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, // WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB // WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, // WGL_CONTEXT_DEBUG_BIT_ARB // WGL_CONTEXT_LAYER_PLANE_ARB, 0, 0 }; wglContext = wglCreateContextAttribsARB(gdiDc, 0, contextAttrs); if (!wglContext) { Log::E("wglContext"); } if (!wglMakeCurrent(gdiDc, wglContext)) { Log::E("wglMakeCurrent"); wglDeleteContext(wglContext); ReleaseDC(window, gdiDc); wglContext = nullptr; return false; } RECT rect; GetClientRect(window, &rect); mWidth = rect.right - rect.left; mHeight = rect.bottom - rect.top; return true; }
void SkOSWindow::detachGL() { wglMakeCurrent(GetDC((HWND)fHWND), 0); wglDeleteContext((HGLRC)fHGLRC); fHGLRC = NULL; }
LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; switch (message) { case WM_COMMAND: wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_CONNECT: DialogBox(g_hInst, (LPCTSTR)IDD_NATNET, hWnd, (DLGPROC)NatNetDlgProc); break; case IDM_EXIT: DestroyWindow(hWnd); break; default: return DefWindowProc(hWnd, message, wParam, lParam); } break; case WM_PAINT: hdc = BeginPaint(hWnd, &ps); wglMakeCurrent(hdc, g_hRenderContext); Render(); SwapBuffers(hdc); wglMakeCurrent(0, 0); EndPaint(hWnd, &ps); break; case WM_SIZE: { int cx = LOWORD(lParam), cy = HIWORD(lParam); if(cx==0 || cy ==0 || hWnd==NULL) break; GLfloat fFovy = 40.0f; // Field-of-view GLfloat fZNear = 1.0f; // Near clipping plane GLfloat fZFar = 10000.0f; // Far clipping plane HDC hDC = GetDC(hWnd); wglMakeCurrent(hDC, g_hRenderContext); // Calculate viewport aspect RECT rv; GetClientRect(hWnd, &rv); GLfloat fAspect = (GLfloat)(rv.right-rv.left) / (GLfloat)(rv.bottom-rv.top); // Define viewport glMatrixMode(GL_PROJECTION); glLoadIdentity(); gluPerspective(fFovy, fAspect, fZNear, fZFar); glViewport(rv.left, rv.top, rv.right-rv.left, rv.bottom-rv.top); glMatrixMode(GL_MODELVIEW); wglMakeCurrent(0, 0); ReleaseDC(hWnd, hDC); } break; case WM_DESTROY: { HDC hDC = GetDC(hWnd); wglMakeCurrent(hDC, g_hRenderContext); natnetClient.Uninitialize(); wglMakeCurrent(0, 0); wglDeleteContext(g_hRenderContext); ReleaseDC(hWnd, hDC); PostQuitMessage(0); } break; default: return DefWindowProc(hWnd, message, wParam, lParam); } return 0; }
GLboolean fgSetupPixelFormat( SFG_Window* window, GLboolean checkOnly, unsigned char layer_type ) { #if defined(_WIN32_WCE) return GL_TRUE; #else PIXELFORMATDESCRIPTOR pfd; PIXELFORMATDESCRIPTOR* ppfd = &pfd; int pixelformat; HDC current_hDC; GLboolean success; if (checkOnly) current_hDC = CreateDC(TEXT("DISPLAY"), NULL ,NULL ,NULL); else current_hDC = window->Window.pContext.Device; fghFillPFD( ppfd, current_hDC, layer_type ); pixelformat = ChoosePixelFormat( current_hDC, ppfd ); /* windows hack for multismapling/sRGB */ if ( ( fgState.DisplayMode & GLUT_MULTISAMPLE ) || ( fgState.DisplayMode & GLUT_SRGB ) ) { HGLRC rc, rc_before=wglGetCurrentContext(); HWND hWnd; HDC hDC, hDC_before=wglGetCurrentDC(); WNDCLASS wndCls; /* create a dummy window */ ZeroMemory(&wndCls, sizeof(wndCls)); wndCls.lpfnWndProc = DefWindowProc; wndCls.hInstance = fgDisplay.pDisplay.Instance; wndCls.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; wndCls.lpszClassName = _T("FREEGLUT_dummy"); RegisterClass( &wndCls ); hWnd=CreateWindow(_T("FREEGLUT_dummy"), _T(""), WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_OVERLAPPEDWINDOW , 0,0,0,0, 0, 0, fgDisplay.pDisplay.Instance, 0 ); hDC=GetDC(hWnd); SetPixelFormat( hDC, pixelformat, ppfd ); rc = wglCreateContext( hDC ); wglMakeCurrent(hDC, rc); if ( fghIsExtensionSupported( hDC, "WGL_ARB_multisample" ) ) { PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARBProc = (PFNWGLCHOOSEPIXELFORMATARBPROC) wglGetProcAddress("wglChoosePixelFormatARB"); if ( wglChoosePixelFormatARBProc ) { int attributes[100]; int iPixelFormat; BOOL bValid; float fAttributes[] = { 0, 0 }; UINT numFormats; fghFillPixelFormatAttributes( attributes, ppfd ); bValid = wglChoosePixelFormatARBProc(hDC, attributes, fAttributes, 1, &iPixelFormat, &numFormats); if ( bValid && numFormats > 0 ) { pixelformat = iPixelFormat; } } } wglMakeCurrent( hDC_before, rc_before); wglDeleteContext(rc); ReleaseDC(hWnd, hDC); DestroyWindow(hWnd); UnregisterClass(_T("FREEGLUT_dummy"), fgDisplay.pDisplay.Instance); } success = ( pixelformat != 0 ) && ( checkOnly || SetPixelFormat( current_hDC, pixelformat, ppfd ) ); if (checkOnly) DeleteDC(current_hDC); return success; #endif /* defined(_WIN32_WCE) */ }
void VDOpenGLBinding::Detach() { if (mhglrc) { wglDeleteContext(mhglrc); mhglrc = NULL; } }
void destroy_gl_context(HGLRC hglrc) { wglMakeCurrent(NULL,NULL); wglDeleteContext(hglrc); }
bool OGL4RenderWindow::Create(void* wnd, int w, int h, G_FORMAT color_format, G_FORMAT depth_format) { if(wnd == nullptr) { return false; } m_hWnd = (HWND)wnd; AdjustWindow(w, h); CenterWindow(); m_hDC = ::GetDC(m_hWnd); PIXELFORMATDESCRIPTOR pfd; memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 32; pfd.iLayerType = PFD_MAIN_PLANE; int nPixelFormat = ChoosePixelFormat(m_hDC, &pfd); if (nPixelFormat == 0) return false; bool bResult = (SetPixelFormat(m_hDC, nPixelFormat, &pfd) != FALSE); if (!bResult) return false; HGLRC tempOpenGLContext = wglCreateContext(m_hDC); wglMakeCurrent(m_hDC, tempOpenGLContext); int attributes[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 3, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | WGL_CONTEXT_DEBUG_BIT_ARB, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0 }; PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); if(wglCreateContextAttribsARB == nullptr) { m_hRC = tempOpenGLContext; return true; } m_hRC = wglCreateContextAttribsARB(m_hDC, NULL, attributes); if(m_hRC == nullptr) { m_hRC = tempOpenGLContext; return true; } MakeCurrent(); wglDeleteContext(tempOpenGLContext); m_width = w; m_height = h; return true; }
OpenGLWindowRenderTarget::~OpenGLWindowRenderTarget(void) { wglDeleteContext(mHGLRenderContext); }
void CGLDevice::Destroy() { wglMakeCurrent(m_hDC, 0); // Remove the rendering context from our device context wglDeleteContext(m_hRC); // Delete our rendering context }
HGLRC RenderContext::createContext( HDC hdc, HGLRC shareContext ) { HGLRC currentContext = wglGetCurrentContext(); HDC currentDC = wglGetCurrentDC(); HGLRC context = wglCreateContext( hdc ); wglMakeCurrent( hdc, context ); PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB"); if ( context && wglGetExtensionsStringARB ) { bool arbCreateContextSupported = false; std::istringstream is( wglGetExtensionsStringARB( hdc ) ); while ( !is.eof() && !arbCreateContextSupported ) { std::string extension; is >> extension; arbCreateContextSupported = extension == "WGL_ARB_create_context"; } if ( arbCreateContextSupported ) { #ifndef GLAPIENTRY # if (_MSC_VER >= 800) || defined(_STDCALL_SUPPORTED) /* Mimic <wglext.h> */ # define GLAPIENTRY __stdcall # else # define GLAPIENTRY # endif #endif typedef HGLRC (GLAPIENTRY *PFNWGLCREATECONTEXTATTRIBSARB)(HDC hDC, HGLRC hShareContext, const int *attribList); PFNWGLCREATECONTEXTATTRIBSARB wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARB)wglGetProcAddress("wglCreateContextAttribsARB"); DP_ASSERT( wglCreateContextAttribsARB ); #if defined(NDEBUG) int attribs[] = { //WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 }; #else int attribs[] = { //WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB | WGL_CONTEXT_DEBUG_BIT_ARB, // WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB not running on AMD WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_DEBUG_BIT_ARB, 0 }; #endif HGLRC hglrcNew = wglCreateContextAttribsARB( hdc, shareContext, attribs ); wglMakeCurrent( NULL, NULL ); wglDeleteContext( context ); context = hglrcNew; DP_ASSERT( context ); if ( shareContext ) { #if 0 nvgl::WGLNotifyShareLists( shareContext, context ); #endif } } else { DP_ASSERT( false ); #if 0 nvgl::WGLAttachContext( hdc, context ); // context construction failed if ( context && shareContext && !nvgl::WGLShareLists( shareContext, context) ) { // Sharelists failed. Delete context and set return value to 0. nvgl::WGLDeleteContext( context ); context = 0; } #endif } }
void QEW_StopGL( HWND hWnd, HGLRC hGLRC, HDC hDC ) { wglMakeCurrent( NULL, NULL ); wglDeleteContext( hGLRC ); ReleaseDC( hWnd, hDC ); }
internal void Win32LoadWGLExtensions() { WNDCLASSA WindowClass = {0}; WindowClass.lpfnWndProc = DefWindowProcA; WindowClass.hInstance = GetModuleHandle(0); WindowClass.lpszClassName = "LudusWGLLoader"; if(RegisterClassA(&WindowClass)) { HWND Window = CreateWindowExA(0, WindowClass.lpszClassName, "Ludus WGL Loader", 0, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, 0, 0, WindowClass.hInstance, 0); if(Window) { HDC WindowDC = GetDC(Window); Win32SetPixelFormat(WindowDC); HGLRC OpenGLRC = wglCreateContext(WindowDC); if(wglMakeCurrent(WindowDC, OpenGLRC)) { wglSwapInterval = (wgl_swap_interval_ext*)wglGetProcAddress("wglSwapIntervalEXT"); if(!wglSwapInterval) { Win32Log("Couldnt get wglSwapInternalEXT extension"); } wglChoosePixelFormatARB = (wgl_choose_pixel_format_arb*)wglGetProcAddress("wglChoosePixelFormatARB"); if(!wglChoosePixelFormatARB) { Win32Log("Couldnt get wglChoosePixelFormatARB extension"); } wglCreateContextAttribsARB = (wgl_create_context_attribs_arb*)wglGetProcAddress("wglCreateContextAttribsARB"); if(!wglCreateContextAttribsARB) { Win32Log("Couldnt get wglCreateContextAttribsARB extension"); } wglMakeCurrent(0, 0); } wglDeleteContext(OpenGLRC); ReleaseDC(Window, WindowDC); DestroyWindow(Window); } else { Win32Log("Couldnt create WGL Loader Window"); LOG_FORMATTED_ERROR(4096); } } else { Win32Log("Couldnt register class for WGL Loader Window"); LOG_FORMATTED_ERROR(4096); } }
/* Функция инициализации анимации. * АРГУМЕНТЫ: * - дескриптор окна: * HWND hWnd; * ВОЗВРАЩАЕМОЕ ЗНАЧЕНИЕ: Нет. */ BOOL OK2_AnimInit( HWND hWnd ) { LARGE_INTEGER li; INT i; /* Init window parametrs */ OK2_Anim.hDC = GetDC(hWnd); OK2_Anim.hWnd = hWnd; OK2_Anim.W = 30; OK2_Anim.H = 30; OK2_Anim.NumOfUnits = 0; /*** Инициализация OpenGL ***/ /* описываем формат точки */ pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_SUPPORT_GDI | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; i = ChoosePixelFormat(OK2_Anim.hDC, &pfd); DescribePixelFormat(OK2_Anim.hDC, i, sizeof(pfd), &pfd); SetPixelFormat(OK2_Anim.hDC, i, &pfd); /* создаем контекст построения */ OK2_Anim.hRC = wglCreateContext(OK2_Anim.hDC); /* делаем текущими контексты */ wglMakeCurrent(OK2_Anim.hDC, OK2_Anim.hRC); /* инициализируем расширения */ if (glewInit() != GLEW_OK || !(GLEW_ARB_vertex_shader && GLEW_ARB_fragment_shader)) { wglMakeCurrent(NULL, NULL); wglDeleteContext(OK2_Anim.hRC); ReleaseDC(OK2_Anim.hWnd, OK2_Anim.hDC); memset(&OK2_Anim, 0, sizeof(ok2ANIM)); return FALSE; } /* параметры OpenGL по-умолчанию */ /* инициализируем таймер */ QueryPerformanceFrequency(&li); TimeFreq = li.QuadPart; QueryPerformanceCounter(&li); TimeStart = TimeOld = TimeFPS = li.QuadPart; TimePause = 0; FrameCounter = 0; /* инициализируем захват сообщений от мыши */ SetWindowsHookEx(WH_MOUSE_LL, OK2_MouseHook, GetModuleHandle(NULL), 0); /* Параметры проецирования */ OK2_Anim.Wp = 4.0, OK2_Anim.Hp = 3.0, /* размеры обрасти проецирования */ OK2_Anim.ProjDist = 1.0, /* расстояние до плоскости проекции */ OK2_Anim.FarClip = 1000.0, OK2_Anim.ProjSize = 1.0; OK2_Anim.MatrWorld = /* матрица преобразования мировой СК */ OK2_Anim.MatrView = /* матрица преобразования видовой СК */ OK2_Anim.MatrProjection = MatrIdenity(); /* матрица проекции */ glEnable(GL_DEPTH_TEST); glEnable(GL_ALPHA_TEST); //glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); return TRUE; } /* End of 'OK2_AnimInit' function */
//WinMain -- Main Window int WINAPI WinMain ( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow ) { MSG msg; msg.message = WM_CREATE; WNDCLASS wc; wc.style = CS_HREDRAW|CS_VREDRAW; wc.lpfnWndProc = WindowProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(GetModuleHandle(NULL), IDI_APPLICATION); wc.hCursor = LoadCursor (NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH) (COLOR_WINDOW+1); wc.lpszMenuName = NULL; wc.lpszClassName = "chockngt"; RegisterClass (&wc); // Create the window //mainWnd = CreateWindow (szAppName,szAppName,WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX|WS_MAXIMIZEBOX,CW_USEDEFAULT,CW_USEDEFAULT,1024,600,0,0,hInstance,0); //mainWnd = CreateWindow("epic","epic",WS_POPUP|WS_VISIBLE|WS_MAXIMIZE,0,0,0,0,0,0,hInstance,0); hWnd = CreateWindow( "static",0,WS_POPUP|WS_VISIBLE|WS_MAXIMIZE,0,0,0,0,0,0,0,0); HDC hDC = GetDC(hWnd); // initalize opengl if( !SetPixelFormat(hDC,ChoosePixelFormat(hDC,&pfd),&pfd) ) return -1; HGLRC hRC = wglCreateContext(hDC); wglMakeCurrent(hDC,hRC); glInit(); ShowWindow(hWnd,SW_SHOW); UpdateWindow(hWnd); long startTime = timeGetTime(); long lastTime = 0; // start music playback /* setup output - default device, 44100hz, stereo, 16 bits */ BASSMOD_Init(-1,44100,BASS_DEVICE_NOSYNC); BASSMOD_MusicLoad(FALSE,"dalezy - trollmannen_s krypt..mod",0,0,BASS_MUSIC_LOOP); BASSMOD_MusicPlay(); float fCurTime; GetAsyncKeyState(VK_ESCAPE); do { while (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { if (!IsDialogMessage(hWnd, &msg)) { TranslateMessage (&msg); DispatchMessage (&msg); } } if (msg.message == WM_QUIT) break; // early exit on quit SetCursor(FALSE); // update timer long curTime = timeGetTime() - startTime; fCurTime = (float)curTime * 0.001f; long deltaTime = curTime - lastTime; float fDeltaTime = (float) deltaTime * 0.001f; lastTime = curTime; // render wglMakeCurrent(hDC,hRC); glClearColor(0.0f, 0.7f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); // write your rendering code here! glMatrixMode(GL_MODELVIEW); parameterMatrix[0] = fCurTime; // time parameterMatrix[1] = 0.0f; // no font mode glLoadMatrixf(parameterMatrix); // draw offscreen glBindTexture(GL_TEXTURE_3D, noiseTexture); glGetIntegerv(GL_VIEWPORT, viewport); glViewport(0, 0, OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT); glUseProgram(shaderPrograms[0]); glRectf(-1.0, -1.0, 1.0, 1.0); //// copy to front glViewport(0, 0, viewport[2], viewport[3]); glEnable(GL_TEXTURE_2D); // Enable Texture Mapping glBindTexture(GL_TEXTURE_2D, offscreenTexture); glCopyTexSubImage2D(GL_TEXTURE_2D, 0, 0, 0, 0, 0, OFFSCREEN_WIDTH, OFFSCREEN_HEIGHT); //Copy back buffer to texture glUseProgram(shaderPrograms[1]); glRectf(-1.0, -1.0, 1.0, 1.0); glDisable(GL_TEXTURE_2D); // Enable Texture Mapping // draw font parameterMatrix[1] = 1.0f; // font mode glLoadMatrixf(parameterMatrix); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); glBindTexture(GL_TEXTURE_2D, fontTexture); glBegin(GL_QUADS); for (int i = 0; i < sizeof(scroller)-1; i++) { float pos = 15.0f - fCurTime * 10.0f; int ch = scroller[i]; float xp = (fontX[ch] * 48.0f + 1.0f) / fontWidth; float yp = (fontY[ch] * 48.0f + 1.0f) / fontHeight; float w = 45.5f / fontWidth; float h = 45.5f / fontHeight; // repeat scroller while (pos < -1.0f * sizeof(scroller)) pos += 1.0f * sizeof(scroller); glTexCoord2f(xp, yp + h); glVertex3f((pos + i*1.0f)*0.2f/1920.0f*1080.0f, 0.7f, 0.5f); glTexCoord2f(xp, yp); glVertex3f((pos + i*1.0f)*0.2f/1920.0f*1080.0f, 0.9f, 0.5f); glTexCoord2f(xp+w, yp); glVertex3f((pos + i*1.0f+1.0f)*0.2f/1920.0f*1080.0f, 0.9f, 0.5f); glTexCoord2f(xp+w, yp + h); glVertex3f((pos + i*1.0f+1.0f)*0.2f/1920.0f*1080.0f, 0.7f, 0.5f); } glEnd(); glDisable(GL_BLEND); // swap buffers wglSwapLayerBuffers(hDC, WGL_SWAP_MAIN_PLANE); //Sleep(5); } while (msg.message != WM_QUIT && fCurTime < 230.0f && !GetAsyncKeyState(VK_ESCAPE)); // music uninit BASSMOD_MusicStop(); BASSMOD_MusicFree(); // free the current mod wglDeleteContext(hRC); ReleaseDC(hWnd, hDC); glUnInit(); return msg.wParam; }
LRESULT APIENTRY WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_CREATE: /* initialize OpenGL rendering */ hDC = GetDC(hWnd); setupPixelFormat(hDC); setupPalette(hDC); hGLRC = wglCreateContext(hDC); wglMakeCurrent(hDC, hGLRC); init(); return 0; case WM_DESTROY: /* finish OpenGL rendering */ if (hGLRC) { wglMakeCurrent(NULL, NULL); wglDeleteContext(hGLRC); } if (hPalette) { DeleteObject(hPalette); } ReleaseDC(hWnd, hDC); PostQuitMessage(0); return 0; case WM_SIZE: /* track window size changes */ if (hGLRC) { winWidth = (int) LOWORD(lParam); winHeight = (int) HIWORD(lParam); resize(); return 0; } case WM_PALETTECHANGED: /* realize palette if this is *not* the current window */ if (hGLRC && hPalette && (HWND) wParam != hWnd) { UnrealizeObject(hPalette); SelectPalette(hDC, hPalette, FALSE); RealizePalette(hDC); redraw(); break; } break; case WM_QUERYNEWPALETTE: /* realize palette if this is the current window */ if (hGLRC && hPalette) { UnrealizeObject(hPalette); SelectPalette(hDC, hPalette, FALSE); RealizePalette(hDC); redraw(); return TRUE; } break; case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(hWnd, &ps); if (hGLRC) { redraw(); } EndPaint(hWnd, &ps); return 0; } break; case WM_CHAR: /* handle keyboard input */ switch ((int)wParam) { case VK_ESCAPE: DestroyWindow(hWnd); return 0; default: break; } break; default: break; } return DefWindowProc(hWnd, message, wParam, lParam); }
bool CGLDevice::Create30Context( const tInitStruct& initData ) { // store some variables m_hWnd = initData.hwnd; m_hDC = GetDC(m_hWnd); // choose PixelFormat PIXELFORMATDESCRIPTOR pfd; // Create a new PIXELFORMATDESCRIPTOR (PFD) memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); // Clear our PFD pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); // Set the size of the PFD to the size of the class pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; // Enable double buffering, opengl support and drawing to a window pfd.iPixelType = PFD_TYPE_RGBA; // Set our application to use RGBA pixels pfd.cColorBits = 32; // Give us 32 bits of color information (the higher, the more colors) pfd.cDepthBits = 32; // Give us 32 bits of depth information (the higher, the more depth levels) pfd.iLayerType = PFD_MAIN_PLANE; // Set the layer of the PFD int nPixelFormat = ChoosePixelFormat(m_hDC, &pfd); // Check if our PFD is valid and get a pixel format back if (nPixelFormat == 0) // If it fails return false; BOOL bResult = SetPixelFormat(m_hDC, nPixelFormat, &pfd); // Try and set the pixel format based on our PFD if (bResult == 0) // If it fails return false; HGLRC tempOpenGLContext = wglCreateContext(m_hDC); // Create an OpenGL 2.1 context for our device context wglMakeCurrent(m_hDC, tempOpenGLContext); // Make the OpenGL 2.1 context current and active // init GLEW (Have to be done after create a default Context) GLenum error = glewInit(); // Enable GLEW if (error != GLEW_OK) // If GLEW fails return false; // get OpenGL version int32_t major, minor; GetGLVersion(major, minor); // *note* highly suggested to use CORE_PROFILE instead of COMPATIBLE_PROFILE uint32_t context_flags = WGL_CONTEXT_DEBUG_BIT_ARB //| WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB // Set our OpenGL context to be forward compatible ; int attributes[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, major, // Set the MAJOR version of OpenGL to 4 WGL_CONTEXT_MINOR_VERSION_ARB, minor, // Set the MINOR version of OpenGL to 2 // *note* highly suggested to use CORE_PROFILE instead of COMPATIBLE_PROFILE WGL_CONTEXT_FLAGS_ARB, context_flags, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0 }; if (wglewIsSupported("WGL_ARB_create_context") == 1) { // If the OpenGL 3.x context creation extension is available m_hRC = wglCreateContextAttribsARB(m_hDC, NULL, attributes); // Create and OpenGL 3.x context based on the given attributes wglMakeCurrent(NULL, NULL); // Remove the temporary context from being active wglDeleteContext(tempOpenGLContext); // Delete the temporary OpenGL 2.1 context wglMakeCurrent(m_hDC, m_hRC); // Make our OpenGL 3.0 context current } else { m_hRC = tempOpenGLContext; // If we didn't have support for OpenGL 3.x and up, use the OpenGL 2.1 context } int glVersion[2] = {-1, -1}; // Set some default values for the version glGetIntegerv(GL_MAJOR_VERSION, &glVersion[0]); // Get back the OpenGL MAJOR version we are using glGetIntegerv(GL_MINOR_VERSION, &glVersion[1]); // Get back the OpenGL MAJOR version we are using Debug::Print((boost::wformat(TEXT("Using OpenGL: %1%.%2%")) % glVersion[0] % glVersion[1])); // Output which version of OpenGL we are using // setup debug context if (context_flags & WGL_CONTEXT_DEBUG_BIT_ARB) { if (glDebugMessageCallback) { auto func = &CGLDevice::GLDebugCallback; glDebugMessageCallback(func, nullptr); } } // get window info glm::vec2 vp_size = BackBufferSize(); glViewport(0,0,(int32_t)vp_size.x, (int32_t)vp_size.y); // setup v-sync // http://www.3dbuzz.com/forum/threads/188320-Enable-or-Disable-VSync-in-OpenGL if(wglSwapIntervalEXT) { if(initData.bWaitForVSync) { wglSwapIntervalEXT(1); } else { wglSwapIntervalEXT(0); } } return true; }
void DisableOpenGL (HWND hwnd, HDC hDC, HGLRC hRC) { wglMakeCurrent(NULL, NULL); wglDeleteContext(hRC); ReleaseDC(hwnd, hDC); }
GHL_API int GHL_CALL GHL_StartApplication( GHL::Application* app,int argc, char** argv) { (void)argc; (void)argv; OSVERSIONINFO os_ver; SYSTEMTIME tm; MEMORYSTATUS mem_st; GetLocalTime(&tm); char buf[256]; sprintf(buf,"Date: %02d.%02d.%d, %02d:%02d:%02d",tm.wDay, tm.wMonth, tm.wYear, tm.wHour, tm.wMinute, tm.wSecond); LOG_INFO( buf ); os_ver.dwOSVersionInfoSize=sizeof(os_ver); GetVersionEx(&os_ver); sprintf(buf,"OS: Windows %ld.%ld.%ld",os_ver.dwMajorVersion,os_ver.dwMinorVersion,os_ver.dwBuildNumber); LOG_INFO( buf ); GlobalMemoryStatus(&mem_st); sprintf(buf,"Memory: %ldK total, %ldK free",mem_st.dwTotalPhys/1024L,mem_st.dwAvailPhys/1024L); LOG_INFO( buf ); GHL::VFSWin32Impl vfs; app->SetVFS(&vfs); GHL::ImageDecoderImpl image; app->SetImageDecoder(&image); HINSTANCE hInstance = GetModuleHandle(0); WNDCLASS winclass; { winclass.style = CS_DBLCLKS | CS_OWNDC | CS_HREDRAW | CS_VREDRAW; winclass.lpfnWndProc = &WindowProc; winclass.cbClsExtra = 0; winclass.cbWndExtra = 0; winclass.hInstance = hInstance; winclass.hCursor = LoadCursor(NULL, IDC_ARROW); winclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); winclass.lpszMenuName = NULL; winclass.lpszClassName = WINDOW_CLASS_NAME; winclass.hIcon = LoadIcon(NULL, IDI_APPLICATION); if (!RegisterClass(&winclass)) { LOG_ERROR( "Can't register window class" ); return 1; } } GHL::Settings settings; settings.width = 800; settings.height = 600; settings.fullscreen = false; app->FillSettings(&settings); RECT rect_w; rect_w.left = GetSystemMetrics(SM_CXSCREEN)/2 - settings.width/2; rect_w.top = GetSystemMetrics(SM_CYSCREEN)/2 - settings.height/2; rect_w.right = rect_w.left + settings.width; rect_w.bottom = rect_w.top + settings.height; DWORD style_w = WS_POPUP|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX|WS_VISIBLE; //WS_OVERLAPPED | WS_SYSMENU | WS_MINIMIZEBOX; AdjustWindowRect(&rect_w,style_w,false); /*m_rect_fs.left=0; m_rect_fs.top=0; m_rect_fs.right=m_width; m_rect_fs.bottom=m_height; m_style_fs=WS_POPUP|WS_VISIBLE; */ HWND hwndParent = 0; /// @todo HWND hwnd = 0; //if(!settings.fullscreen) hwnd = CreateWindowEx(0, WINDOW_CLASS_NAME, TEXT("Test"), style_w, rect_w.left, rect_w.top, rect_w.right-rect_w.left, rect_w.bottom-rect_w.top, hwndParent, NULL, hInstance, NULL); /*else m_hwnd = CreateWindowExA(WS_EX_TOPMOST, WINDOW_CLASS_NAME, "Test", m_style_fs, 0, 0, 0, 0, NULL, NULL, hInstance, NULL);*/ if (!hwnd) { LOG_ERROR( "Can't create window" ); return 1; } #ifndef GHL_NO_SOUND GHL::SoundDSound sound(8); if (!sound.SoundInit(hwnd)) { LOG_ERROR( "Can't init sound" ); return 1; } app->SetSound(&sound); #endif Win32System sys(hwnd); app->SetSystem(&sys); g_proxy.Register(); app->SetPlatformProxy(&g_proxy); HDC hDC = GetDC (hwnd); if (!hDC) { DestroyWindow(hwnd); return 1; } PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be { sizeof (PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format 32, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 24, // 16Bit Z-Buffer (Depth Buffer) 8, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; int PixelFormat = ChoosePixelFormat (hDC, &pfd); // Find A Compatible if (PixelFormat == 0) // Did We Find A Compatible Format? { // Failed ReleaseDC (hwnd, hDC); // Release Our Device Context hDC = 0; // Zero The Device Context DestroyWindow (hwnd); // Destroy The Window hwnd = 0; // Zero The Window Handle return 1; // Return False } if (SetPixelFormat (hDC, PixelFormat, &pfd) == FALSE) // Try To Set The Pixel Format { // Failed ReleaseDC (hwnd, hDC); // Release Our Device Context hDC = 0; // Zero The Device Context DestroyWindow (hwnd); // Destroy The Window hwnd = 0; // Zero The Window Handle return 1; // Return False } HGLRC hRC = wglCreateContext(hDC); if (hRC == 0) // Did We Get A Rendering Context? { // Failed ReleaseDC (hwnd, hDC); // Release Our Device Context hDC = 0; // Zero The Device Context DestroyWindow (hwnd); // Destroy The Window hwnd = 0; // Zero The Window Handle return 1; // Return False } SetWindowLongPtr(hwnd,GWLP_USERDATA,(LONG_PTR)app); if (wglMakeCurrent (hDC, hRC) == FALSE) { // Failed wglDeleteContext (hRC); // Delete The Rendering Context hRC = 0; // Zero The Rendering Context ReleaseDC (hwnd, hDC); // Release Our Device Context hDC = 0; // Zero The Device Context DestroyWindow (hwnd); // Destroy The Window hwnd = 0; // Zero The Window Handle return 1; // Return False } ShowWindow(hwnd, SW_SHOW); wglMakeCurrent (hDC, hRC); GHL::RenderOpenGL render(settings.width,settings.height); render.RenderInit(); app->SetRender(&render); app->Initialize(); //GHL_DispatchPlatformEvent(&g_proxy, "platform:app_init_done", 0); if (!app->Load()) return 1; bool done = false; timeBeginPeriod(1); DWORD ms = timeGetTime(); while (!done) { /* if (m_input) m_input->Update(); */ #ifndef GHL_NO_SOUND sound.Process(); #endif MSG msg; while (PeekMessage(&msg,hwnd,0,0,PM_REMOVE) && !done) { if (msg.message == WM_QUIT) { done = true; if (app) { app->Release(); app = 0; } render.RenderDone(); #ifndef GHL_NO_SOUND sound.SoundDone(); #endif LOG_INFO( "Done" ); break; } else DispatchMessage(&msg); } if (app) { wglMakeCurrent (hDC, hRC); DWORD now = timeGetTime(); DWORD dt = now - ms; ms = now; //if (dt>1000) // dt = 1000; app->OnFrame(dt); SwapBuffers (hDC); Sleep(1); } } timeEndPeriod(1); return 0; }
bool window_create(const char *caption,int width,int height) { HINSTANCE hInstance=GetModuleHandle(0); if(!register_class_win32("app",hInstance,WndProc)) { return false; } if(!create_window_win32("app",caption,width,height, hInstance,&windowData.hWnd)) { //todo unregister class return false; } if(!rawinput_init_win32(NULL)) { //todo unregister class //todo destroy window return false; } windowData.hdc=GetDC(windowData.hWnd); // if(!set_gl_pixel_format(windowData.hdc)) { //todo unregister class //todo destroy window return false; } // HGLRC hglrcTemp=wglCreateContext(windowData.hdc); wglMakeCurrent(windowData.hdc,hglrcTemp); // PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB; wglCreateContextAttribsARB=(PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB"); if(!wglCreateContextAttribsARB) { fprintf(stderr,"wglCreateContextAttribsARB failed to retrieve.\n"); //todo destroy temp gl context //todo unregister class //todo destroy window return false; } // wglMakeCurrent(NULL,NULL); wglDeleteContext(hglrcTemp); // windowData.hglrc=0; if(!gl_context_win32(windowData.hdc,wglCreateContextAttribsARB, 3,3,false,&windowData.hglrc) && !gl_context_win32(windowData.hdc,wglCreateContextAttribsARB, 3,2,false,&windowData.hglrc) && !gl_context_win32(windowData.hdc,wglCreateContextAttribsARB, 3,1,false,&windowData.hglrc) && !gl_context_win32(windowData.hdc,wglCreateContextAttribsARB, 3,0,false,&windowData.hglrc) && !gl_context_win32(windowData.hdc,wglCreateContextAttribsARB, 2,1,false,&windowData.hglrc) && !gl_context_win32(windowData.hdc,wglCreateContextAttribsARB, 2,0,false,&windowData.hglrc)) { //todo unregister class //todo destroy window return false; } // run_gl_swap_interval(); // int i; // windowData.iconic=false; windowData.restored=false; windowData.sized=false; windowData.clientWidth=-1; windowData.clientHeight=-1; windowData.cursorX=0; windowData.cursorY=0; windowData.mouseX=0; windowData.mouseY=0; windowData.mouseZ=0; windowData.lockCursor=false; windowData.cursorLocked=false; for(i=0;i<INPUTS_SIZE;i++) { windowData.inputs[i]=INPUT_UP; } return true; }
px::ViewOGL* px::ViewOGL::CreateView(void* _wnd) { ViewOGL * viewOGL = new ViewOGL; if(!_wnd) return NULL; HWND hwnd = (HWND)_wnd; HDC hdc = GetDC(hwnd); // Get the device context for our window viewOGL->hwnd = hwnd; viewOGL->hdc = hdc; PIXELFORMATDESCRIPTOR pfd; // Create a new PIXELFORMATDESCRIPTOR (PFD) memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); // Clear our PFD pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); // Set the size of the PFD to the size of the class pfd.dwFlags = PFD_DOUBLEBUFFER | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW; // Enable double buffering, opengl support and drawing to a window pfd.iPixelType = PFD_TYPE_RGBA; // Set our application to use RGBA pixels pfd.cColorBits = 32; // Give us 32 bits of color information (the higher, the more colors) pfd.cDepthBits = 32; // Give us 32 bits of depth information (the higher, the more depth levels) pfd.iLayerType = PFD_MAIN_PLANE; // Set the layer of the PFD int nPixelFormat = ChoosePixelFormat(hdc, &pfd); // Check if our PFD is valid and get a pixel format back if (nPixelFormat == 0) // If it fails return NULL; bool bResult = SetPixelFormat(hdc, nPixelFormat, &pfd); // Try and set the pixel format based on our PFD if (!bResult) // If it fails return NULL; HGLRC glrc = wglCreateContext(hdc); // Create an OpenGL 2.1 context for our device context wglMakeCurrent(hdc, glrc); // Make the OpenGL 2.1 context current and active viewOGL->hrc = (void *)glrc; // init opengl core profile PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT"); if( wglSwapIntervalEXT && wglCreateContextAttribsARB && wglChoosePixelFormatARB) { const int attribList[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 32, WGL_STENCIL_BITS_ARB, 8, 0,//End }; int pixelFormat; UINT numFormats; wglChoosePixelFormatARB(hdc, attribList, NULL, 1, &pixelFormat, &numFormats); static const int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, OGL_MAJOR, WGL_CONTEXT_MINOR_VERSION_ARB, OGL_MINOR, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_DEBUG_BIT_ARB, 0 }; HGLRC core_rc = wglCreateContextAttribsARB(hdc, 0, attribs); wglMakeCurrent(hdc, core_rc); wglDeleteContext( glrc ); } if (gl3wInit()) { fprintf(stderr, "failed to initialize OpenGL\n"); } if (!gl3wIsSupported( OGL_MAJOR, OGL_MINOR )) { fprintf(stderr, "OpenGL %d.%d not supported\n", OGL_MAJOR, OGL_MINOR ); } printf("OpenGL %s, GLSL %s\n", glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)); return viewOGL; }
GLSLChecker::GLSLChecker(GLuint type,const char* regex): type(type),_regex(regex), #ifdef _WIN32 g_hDC(NULL),g_hInstance(NULL),g_hRC(NULL),g_hWnd(NULL) #else glc(NULL),dpy(NULL),vi(NULL) #endif { prologue = "#version 120\n"; Logger& logger = Logger::get_instance(); /* we need context for each thread, but only one per thread */ #ifdef _WIN32 if (wglGetCurrentContext() == NULL) { const unsigned char INPUT_UP = 0, INPUT_DOWN = 1, INPUT_PRESSED = 2; int width = 800; int height = 600; const char* title = "honCheck"; WNDCLASSEX wcx; PIXELFORMATDESCRIPTOR pfd; RECT rect; HGLRC hRCTemp; DWORD style, exStyle; int x, y, format; int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 3, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0 }; g_hInstance = (HINSTANCE)GetModuleHandle(NULL); memset(&wcx, 0, sizeof(wcx)); wcx.cbSize = sizeof(wcx); wcx.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wcx.lpfnWndProc = (WNDPROC)DefWindowProc; wcx.hInstance = g_hInstance; wcx.lpszClassName = GLWINDOW_CLASS_NAME; wcx.hIcon = LoadIcon(NULL, IDI_APPLICATION); wcx.hCursor = LoadCursor(NULL, IDC_ARROW); if (!RegisterClassEx(&wcx) && GetLastError()!=ERROR_CLASS_ALREADY_EXISTS) { #pragma omp critical (log) logger.error(0) << "RegisterClassEx fail " << GetLastError() << logger.end; return; } style = WS_CAPTION | WS_SYSMENU | WS_MINIMIZEBOX; exStyle = WS_EX_APPWINDOW; x = (GetSystemMetrics(SM_CXSCREEN) - width) / 2; y = (GetSystemMetrics(SM_CYSCREEN) - height) / 2; rect.left = x; rect.right = x + width; rect.top = y; rect.bottom = y + height; AdjustWindowRectEx (&rect, style, FALSE, exStyle); g_hWnd = CreateWindowEx(exStyle, GLWINDOW_CLASS_NAME, title, style, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, NULL, NULL, g_hInstance, NULL); if (!g_hWnd) { #pragma omp critical (log) logger.error(0) << "CreateWindowEx fail " << GetLastError() << logger.end; return; } g_hDC = GetDC(g_hWnd); if (!g_hDC) { #pragma omp critical (log) logger.error(0) << "GetDC fail " << GetLastError() << logger.end; return ; } memset(&pfd, 0, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 32; pfd.cDepthBits = 24; format = ChoosePixelFormat(g_hDC, &pfd); if (!format || !SetPixelFormat(g_hDC, format, &pfd)) { #pragma omp critical (log) logger.error(0) << "Setting pixel format fail " << GetLastError() << logger.end; return ; } hRCTemp = wglCreateContext(g_hDC); if (!hRCTemp || !wglMakeCurrent(g_hDC, hRCTemp)) { #pragma omp critical (log) logger.error(0) << "Сreating temp render context fail " << GetLastError() << logger.end; return ; } #pragma omp critical (log) { OPENGL_GET_PROC(PFNGLCREATESHADERPROC, glCreateShader); OPENGL_GET_PROC(PFNGLDELETESHADERPROC, glDeleteShader); OPENGL_GET_PROC(PFNGLSHADERSOURCEPROC, glShaderSource); OPENGL_GET_PROC(PFNGLCOMPILESHADERPROC, glCompileShader); OPENGL_GET_PROC(PFNGLGETSHADERIVPROC, glGetShaderiv); OPENGL_GET_PROC(PFNGLGETSHADERINFOLOGPROC, glGetShaderInfoLog); } #else /* #ifdef _WIN32 */ /* LINUX */ if(glXGetCurrentContext() == NULL) { /* I'm not gonna render anything so minimal context creation using root window */ Window root; GLint attr[] = { GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None }; /* open display */ if ( ! (dpy = XOpenDisplay(NULL)) ) { #pragma omp critical (log) logger.error(0) << "cannot connect to X server" << logger.end; return; } /* get root window */ root = DefaultRootWindow(dpy); /* get visual matching attr */ if( ! (vi = glXChooseVisual(dpy, 0, attr)) ) { #pragma omp critical (log) logger.error(0) << "no appropriate visual found" << logger.end; return; } /* create a context using the root window */ if ( ! (glc = glXCreateContext(dpy, vi, NULL, GL_TRUE)) ){ #pragma omp critical (log) logger.error(0) << "failed to create OpenGL context" << logger.end; return; } glXMakeCurrent(dpy, root, glc); #endif #pragma omp critical (log) logger.verbose(0) << "OpenGL vendor:" << glGetString(GL_VENDOR) << logger.end; } } GLSLChecker::~GLSLChecker() { #ifdef _WIN32 if (g_hRC) { wglMakeCurrent(NULL, NULL); wglDeleteContext(g_hRC); } if (g_hDC) { ReleaseDC(g_hWnd, g_hDC); } if (g_hWnd) { DestroyWindow(g_hWnd); } if (g_hInstance) { UnregisterClass(GLWINDOW_CLASS_NAME, g_hInstance); } #else if(vi) { XFree(vi); } if(glc) { glXDestroyContext(dpy,glc); } if(dpy) { XCloseDisplay(dpy); } #endif } std::string const& GLSLChecker::reString() const { return _regex; } int GLSLChecker::Compile(const char** strings,int stringCount, const char* path) const { #ifdef _WIN32 if (wglGetCurrentContext() == NULL) #else if (glXGetCurrentContext() == NULL) #endif return 1; int res = 0; { GLuint shader = glCreateShader(type); GLint result = GL_TRUE; glShaderSource(shader, stringCount, strings, NULL); glCompileShader(shader); glGetShaderiv(shader, GL_COMPILE_STATUS, &result); if(result == GL_FALSE) { Logger& logger = Logger::get_instance(); glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &result); char* infoLog = new char[result]; glGetShaderInfoLog(shader, result, NULL, infoLog); #pragma omp critical (error) { logger.error(0) << logger.end; logger.error(0) << "Error compiling shader, log: " << logger.end; logger.error(0) << infoLog << logger.end; logger.error(0) << "Defines combination: " << logger.end; for (int i = 0; i < stringCount - 1 ;++i) logger.error(0) << strings[i] << logger.end; logger.error(0) << logger.end; } delete[] infoLog; res = 1; } glDeleteShader(shader); } return res; } IChecker* GLSLChecker::clone() const { return new GLSLChecker(type,_regex.c_str()); }
long FAR PASCAL WindowProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { PAINTSTRUCT ps; RECT rect; switch(message) { case WM_CREATE: ghDC = GetDC(hWnd); if (!bSetupPixelFormat(ghDC)) PostQuitMessage (0); ghRC = wglCreateContext(ghDC); if (!ghRC) { MessageBox(NULL, "Could not initialize GL", "ERROR", MB_OK); PostQuitMessage (0); } if (!wglMakeCurrent(ghDC, ghRC)) { MessageBox(NULL, "wglMakeCurrent failed", "ERROR", MB_OK); PostQuitMessage (0); } GetClientRect(hWnd, &rect); initializeGL(rect.right, rect.bottom); // Other Initialisation should go here initText(); TimeInit(); TerrainInit("hmap.raw"); break; case WM_PAINT: ghDC = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); return TRUE; case WM_SIZE: GetClientRect(hWnd, &rect); resize(rect.right, rect.bottom); break; case WM_CLOSE: if (ghRC) wglDeleteContext(ghRC); if (ghDC) ReleaseDC(hWnd, ghDC); ghRC = 0; ghDC = 0; DestroyWindow (hWnd); break; case WM_DESTROY: if (ghRC) wglDeleteContext(ghRC); if (ghDC) ReleaseDC(hWnd, ghDC); PostQuitMessage (0); break; case WM_KEYDOWN: KeyDown(wParam); break; } return DefWindowProc(hWnd, message, wParam, lParam); }
bool PlatformInitOpenGLContext(int color_bits, int depth_bits, int stencil_bits) { sht::Application * app = sht::Application::GetInstance(); const int kContextMajorVersion = 3; const int kContextMinorVersion = 3; static int msaa_pixel_format = 0; g_window.dc = GetDC(g_window.hwnd); // Grab A Device Context For This Window if (g_window.dc == 0) { return false; } PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format (BYTE)color_bits, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 0, // No Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored (BYTE)depth_bits, // Z-Buffer (Depth Buffer) (BYTE)stencil_bits, // Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; int pixel_format = ChoosePixelFormat(g_window.dc, &pfd); // Find A Compatible Pixel Format if (pixel_format == 0) { ReleaseDC(g_window.hwnd, g_window.dc); g_window.dc = 0; return false; } // Choose MSAA pixel format if needed if (msaa_pixel_format != 0) pixel_format = msaa_pixel_format; if (SetPixelFormat(g_window.dc, pixel_format, &pfd) == FALSE) // Try To Set The Pixel Format { ReleaseDC(g_window.hwnd, g_window.dc); g_window.dc = 0; return false; } HGLRC temp_rc = wglCreateContext(g_window.dc); // Try To Get A Rendering Context if (temp_rc == 0) { ReleaseDC(g_window.hwnd, g_window.dc); g_window.dc = 0; return false; } // Make The Rendering Context Our Current Rendering Context if (wglMakeCurrent(g_window.dc, temp_rc) == FALSE) { // Failed wglDeleteContext(temp_rc); g_window.rc = 0; ReleaseDC(g_window.hwnd, g_window.dc); g_window.dc = 0; return false; } // Initialize GLEW GLenum err = glewInit(); if (GLEW_OK != err) { fprintf(stderr, "glewInit failed: %s\n", glewGetErrorString(err)); wglDeleteContext(temp_rc); g_window.rc = 0; ReleaseDC(g_window.hwnd, g_window.dc); g_window.dc = 0; return false; } // Try to create a MSAA pixel format if (app->IsMultisample() && msaa_pixel_format == 0) { if (GLEW_ARB_multisample && WGLEW_ARB_pixel_format) { int samples = 4; // = msaa_samples while (samples > 0) { UINT num_formats = 0; int attribs[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_COLOR_BITS_ARB, color_bits, WGL_DEPTH_BITS_ARB, depth_bits, WGL_STENCIL_BITS_ARB, stencil_bits, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_SAMPLE_BUFFERS_ARB, GL_TRUE, WGL_SAMPLES_ARB, samples, 0 }; if (wglChoosePixelFormatARB(g_window.dc, attribs, NULL, 1, &msaa_pixel_format, &num_formats) == TRUE && num_formats > 0) { // We cant's set pixel format twice, so we have to recreate a window *?* wglDeleteContext(temp_rc); g_window.rc = 0; ReleaseDC(g_window.hwnd, g_window.dc); g_window.dc = 0; PlatformWindowDestroy(); // Don't forget do dispatch any upcoming messages, such as WM_QUIT MSG msg; while (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } if (PlatformWindowCreate()) { PlatformWindowCenter(); // Call this function again with msaa pixel format already known return PlatformInitOpenGLContext(color_bits, depth_bits, stencil_bits); } else return false; } else msaa_pixel_format = 0; --samples; } fprintf(stderr, "Error: failed to find any compatible MSAA format\n"); } else { fprintf(stderr, "Error: WGL_ARB_multisample isn't supported, using standart context\n"); } } int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, kContextMajorVersion, WGL_CONTEXT_MINOR_VERSION_ARB, kContextMinorVersion, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, 0 }; if ((wglewIsSupported("WGL_ARB_create_context")) && (g_window.rc = wglCreateContextAttribsARB(g_window.dc, 0, attribs)) && (wglMakeCurrent(g_window.dc, g_window.rc))) { // Forward context has been successfully created wglDeleteContext(temp_rc); } else // failed to obtain forward context { // Use old context g_window.rc = temp_rc; } return true; }
// 取消 OpenGL ,在程序结束前调用,释放渲染环境,设备环境以及最终窗口句柄。 void DisableOpenGL() { wglMakeCurrent( NULL, NULL ); wglDeleteContext( ghRC ); ReleaseDC( ghWnd, ghDC ); }
INT WINAPI WinMain(HINSTANCE hInst, HINSTANCE ignoreMe0, LPSTR ignoreMe1, INT ignoreMe2) { LPCSTR szName = "Pez App"; WNDCLASSEXA wc = { sizeof(WNDCLASSEX), CS_CLASSDC, MsgProc, 0L, 0L, GetModuleHandle(0), 0, 0, 0, 0, szName, 0 }; DWORD dwStyle = WS_SYSMENU | WS_VISIBLE | WS_POPUP; DWORD dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; RECT rect; int windowWidth, windowHeight, windowLeft, windowTop; HWND hWnd; PIXELFORMATDESCRIPTOR pfd; HDC hDC; HGLRC hRC; int pixelFormat; GLenum err; MSG msg = {0}; LARGE_INTEGER previousTime; LARGE_INTEGER freqTime; wc.hCursor = LoadCursor(0, IDC_ARROW); RegisterClassExA(&wc); SetRect(&rect, 0, 0, PEZ_VIEWPORT_WIDTH, PEZ_VIEWPORT_HEIGHT); AdjustWindowRectEx(&rect, dwStyle, FALSE, dwExStyle); windowWidth = rect.right - rect.left; windowHeight = rect.bottom - rect.top; windowLeft = GetSystemMetrics(SM_XVIRTUALSCREEN) + GetSystemMetrics(SM_CXSCREEN) / 2 - windowWidth / 2; windowTop = GetSystemMetrics(SM_CYSCREEN) / 2 - windowHeight / 2; hWnd = CreateWindowExA(0, szName, szName, dwStyle, windowLeft, windowTop, windowWidth, windowHeight, 0, 0, 0, 0); // Create the GL context. ZeroMemory(&pfd, sizeof(pfd)); pfd.nSize = sizeof(pfd); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = 24; pfd.cDepthBits = 24; pfd.cStencilBits = 8; pfd.iLayerType = PFD_MAIN_PLANE; hDC = GetDC(hWnd); pixelFormat = ChoosePixelFormat(hDC, &pfd); SetPixelFormat(hDC, pixelFormat, &pfd); hRC = wglCreateContext(hDC); wglMakeCurrent(hDC, hRC); if (PEZ_ENABLE_MULTISAMPLING) { int pixelAttribs[] = { WGL_SAMPLES_ARB, 16, WGL_SAMPLE_BUFFERS_ARB, GL_TRUE, WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, WGL_RED_BITS_ARB, 8, WGL_GREEN_BITS_ARB, 8, WGL_BLUE_BITS_ARB, 8, WGL_ALPHA_BITS_ARB, 8, WGL_DEPTH_BITS_ARB, 24, WGL_STENCIL_BITS_ARB, 8, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, 0 }; int* sampleCount = pixelAttribs + 1; int* useSampleBuffer = pixelAttribs + 3; int pixelFormat = -1; PROC proc = wglGetProcAddress("wglChoosePixelFormatARB"); unsigned int numFormats; PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC) proc; if (!wglChoosePixelFormatARB) { PezFatalError("Could not load function pointer for 'wglChoosePixelFormatARB'. Is your driver properly installed?"); } // Try fewer and fewer samples per pixel till we find one that is supported: while (pixelFormat <= 0 && *sampleCount >= 0) { wglChoosePixelFormatARB(hDC, pixelAttribs, 0, 1, &pixelFormat, &numFormats); (*sampleCount)--; if (*sampleCount <= 1) { *useSampleBuffer = GL_FALSE; } } // Win32 allows the pixel format to be set only once per app, so destroy and re-create the app: DestroyWindow(hWnd); hWnd = CreateWindowExA(0, szName, szName, dwStyle, windowLeft, windowTop, windowWidth, windowHeight, 0, 0, 0, 0); SetWindowPos(hWnd, HWND_TOP, windowLeft, windowTop, windowWidth, windowHeight, 0); hDC = GetDC(hWnd); SetPixelFormat(hDC, pixelFormat, &pfd); hRC = wglCreateContext(hDC); wglMakeCurrent(hDC, hRC); } #define PEZ_TRANSPARENT_WINDOW 0 // For transparency, this doesn't seem to work. I think I'd need to read back from an OpenGL FBO and blit it with GDI. if (PEZ_TRANSPARENT_WINDOW) { long flag = GetWindowLong(hWnd, GWL_EXSTYLE); int opacity = 128; flag |= WS_EX_LAYERED; SetWindowLong(hWnd, GWL_EXSTYLE, flag); SetLayeredWindowAttributes(hWnd, 0, opacity, LWA_ALPHA); } err = glewInit(); if (GLEW_OK != err) { PezFatalError("GLEW Error: %s\n", glewGetErrorString(err)); } PezDebugString("OpenGL Version: %s\n", glGetString(GL_VERSION)); if (!PEZ_VERTICAL_SYNC) { wglSwapIntervalEXT(0); } if (PEZ_FORWARD_COMPATIBLE_GL) { const int contextAttribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB, 0, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 }; HGLRC newRC = wglCreateContextAttribsARB(hDC, 0, contextAttribs); wglMakeCurrent(0, 0); wglDeleteContext(hRC); hRC = newRC; wglMakeCurrent(hDC, hRC); } { const char* szWindowTitle = PezInitialize(PEZ_VIEWPORT_WIDTH, PEZ_VIEWPORT_HEIGHT); SetWindowTextA(hWnd, szWindowTitle); } QueryPerformanceFrequency(&freqTime); QueryPerformanceCounter(&previousTime); // ------------------- // Start the Game Loop // ------------------- while (msg.message != WM_QUIT) { if (PeekMessage(&msg, 0, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { LARGE_INTEGER currentTime; __int64 elapsed; double deltaTime; QueryPerformanceCounter(¤tTime); elapsed = currentTime.QuadPart - previousTime.QuadPart; deltaTime = elapsed * 1000000.0 / freqTime.QuadPart; previousTime = currentTime; PezUpdate((unsigned int) deltaTime); PezRender(0); SwapBuffers(hDC); if (glGetError() != GL_NO_ERROR) { PezFatalError("OpenGL error.\n"); } } } UnregisterClassA(szName, wc.hInstance); return 0; }
static void close(void) { wglMakeCurrent(NULL, NULL); wglDeleteContext(hRC); }
BOOL CreateWindowGL (GL_Window* window) // This Code Creates Our OpenGL Window { DWORD windowStyle = WS_OVERLAPPEDWINDOW; // Define Our Window Style DWORD windowExtendedStyle = WS_EX_APPWINDOW; // Define The Window's Extended Style PIXELFORMATDESCRIPTOR pfd = // pfd Tells Windows How We Want Things To Be { sizeof (PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL PFD_DOUBLEBUFFER, // Must Support Double Buffering PFD_TYPE_RGBA, // Request An RGBA Format window->init.bitsPerPixel, // Select Our Color Depth 0, 0, 0, 0, 0, 0, // Color Bits Ignored 1, // Alpha Buffer 0, // Shift Bit Ignored 0, // No Accumulation Buffer 0, 0, 0, 0, // Accumulation Bits Ignored 16, // 16Bit Z-Buffer (Depth Buffer) 0, // No Stencil Buffer 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; RECT windowRect = {0, 0, window->init.width, window->init.height}; // Define Our Window Coordinates GLuint PixelFormat; // Will Hold The Selected Pixel Format if (window->init.isFullScreen == TRUE) // Fullscreen Requested, Try Changing Video Modes { if (ChangeScreenResolution (window->init.width, window->init.height, window->init.bitsPerPixel) == FALSE) { // Fullscreen Mode Failed. Run In Windowed Mode Instead MessageBox (HWND_DESKTOP, "Mode Switch Failed.\nRunning In Windowed Mode.", "Error", MB_OK | MB_ICONEXCLAMATION); window->init.isFullScreen = FALSE; // Set isFullscreen To False (Windowed Mode) } else // Otherwise (If Fullscreen Mode Was Successful) { ShowCursor (FALSE); // Turn Off The Cursor windowStyle = WS_POPUP; // Set The WindowStyle To WS_POPUP (Popup Window) windowExtendedStyle |= WS_EX_TOPMOST; // Set The Extended Window Style To WS_EX_TOPMOST } // (Top Window Covering Everything Else) } else // If Fullscreen Was Not Selected { // Adjust Window, Account For Window Borders AdjustWindowRectEx (&windowRect, windowStyle, 0, windowExtendedStyle); } // Create The OpenGL Window window->hWnd = CreateWindowEx (windowExtendedStyle, // Extended Style window->init.application->className, // Class Name window->init.title, // Window Title windowStyle, // Window Style 0, 0, // Window X,Y Position windowRect.right - windowRect.left, // Window Width windowRect.bottom - windowRect.top, // Window Height HWND_DESKTOP, // Desktop Is Window's Parent 0, // No Menu window->init.application->hInstance, // Pass The Window Instance window); if (window->hWnd == 0) // Was Window Creation A Success? { return FALSE; // If Not Return False } window->hDC = GetDC (window->hWnd); // Grab A Device Context For This Window if (window->hDC == 0) // Did We Get A Device Context? { // Failed DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } PixelFormat = ChoosePixelFormat (window->hDC, &pfd); // Find A Compatible Pixel Format if (PixelFormat == 0) // Did We Find A Compatible Format? { // Failed ReleaseDC (window->hWnd, window->hDC); // Release Our Device Context window->hDC = 0; // Zero The Device Context DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } if (SetPixelFormat (window->hDC, PixelFormat, &pfd) == FALSE) // Try To Set The Pixel Format { // Failed ReleaseDC (window->hWnd, window->hDC); // Release Our Device Context window->hDC = 0; // Zero The Device Context DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } window->hRC = wglCreateContext (window->hDC); // Try To Get A Rendering Context if (window->hRC == 0) // Did We Get A Rendering Context? { // Failed ReleaseDC (window->hWnd, window->hDC); // Release Our Device Context window->hDC = 0; // Zero The Device Context DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } // Make The Rendering Context Our Current Rendering Context if (wglMakeCurrent (window->hDC, window->hRC) == FALSE) { // Failed wglDeleteContext (window->hRC); // Delete The Rendering Context window->hRC = 0; // Zero The Rendering Context ReleaseDC (window->hWnd, window->hDC); // Release Our Device Context window->hDC = 0; // Zero The Device Context DestroyWindow (window->hWnd); // Destroy The Window window->hWnd = 0; // Zero The Window Handle return FALSE; // Return False } ShowWindow (window->hWnd, SW_NORMAL); // Make The Window Visible window->isVisible = TRUE; // Set isVisible To True ReshapeGL (window->init.width, window->init.height); // Reshape Our GL Window ZeroMemory (window->keys, sizeof (Keys)); // Clear All Keys window->lastTickCount = GetTickCount (); // Get Tick Count return TRUE; // Window Creating Was A Success // Initialization Will Be Done In WM_CREATE }
LRESULT CALLBACK MessageLoop(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { LRESULT result = 0; switch(uMsg) { case WM_CREATE: { PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, //Flags PFD_TYPE_RGBA, //The kind of framebuffer. RGBA or palette. 32, //Colordepth of the framebuffer. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, //24, //Number of bits for the depthbuffer 0, //Number of bits for the stencilbuffer 0, //Number of Aux buffers in the framebuffer. PFD_MAIN_PLANE, 0, 0, 0, 0 }; s_device_context = GetDC(hWnd); int pixel_format = ChoosePixelFormat(s_device_context, &pfd); SetPixelFormat(s_device_context, pixel_format, &pfd); s_gl_context = wglCreateContext(s_device_context); wglMakeCurrent(s_device_context, s_gl_context); }break; case WM_DESTROY: { wglMakeCurrent(s_device_context, NULL); wglDeleteContext(s_gl_context); }break; case WM_CLOSE: { PostQuitMessage(1); }break; case WM_KEYDOWN: { switch (wParam) { case VK_ESCAPE: { PostQuitMessage(1); }break; } }break; case WM_MOUSEMOVE: { result = 0; }break; default: return DefWindowProc(hWnd, uMsg, wParam, lParam); } return result; }
void CPKRender::Release() { //deselect rendering context and delete it wglMakeCurrent( m_hDC , NULL ); wglDeleteContext( m_hglRC ); }
void GFXGLDevice::enumerateAdapters( Vector<GFXAdapter*> &adapterList ) { // GL_ERROR_CHECK(); WNDCLASS windowclass; dMemset( &windowclass, 0, sizeof( WNDCLASS ) ); windowclass.lpszClassName = L"GFX-OpenGL"; windowclass.style = CS_OWNDC; windowclass.lpfnWndProc = DefWindowProc; windowclass.hInstance = winState.appInstance; if( !RegisterClass( &windowclass ) ) AssertFatal( false, "Failed to register the window class for the GL test window." ); // Now create a window HWND hwnd = CreateWindow( L"GFX-OpenGL", L"", WS_POPUP, 0, 0, 640, 480, NULL, NULL, winState.appInstance, NULL ); AssertFatal( hwnd != NULL, "Failed to create the window for the GL test window." ); // Create a device context HDC tempDC = GetDC( hwnd ); AssertFatal( tempDC != NULL, "Failed to create device context" ); // Create pixel format descriptor... PIXELFORMATDESCRIPTOR pfd; CreatePixelFormat( &pfd, 32, 0, 0, false ); if( !SetPixelFormat( tempDC, ChoosePixelFormat( tempDC, &pfd ), &pfd ) ) AssertFatal( false, "I don't know who's responcible for this, but I want caught..." ); // Create a rendering context! HGLRC tempGLRC = wglCreateContext( tempDC ); if( !wglMakeCurrent( tempDC, tempGLRC ) ) AssertFatal( false, "I want them caught and killed." ); // Add the GL renderer loadGLCore(); loadGLExtensions(tempDC); GFXAdapter *toAdd = new GFXAdapter; toAdd->mIndex = 0; const char* renderer = (const char*) glGetString( GL_RENDERER ); AssertFatal( renderer != NULL, "GL_RENDERER returned NULL!" ); if (renderer) { dStrcpy(toAdd->mName, renderer); dStrncat(toAdd->mName, " OpenGL", GFXAdapter::MaxAdapterNameLen); } else dStrcpy(toAdd->mName, "OpenGL"); toAdd->mType = OpenGL; toAdd->mShaderModel = 0.f; toAdd->mCreateDeviceInstanceDelegate = mCreateDeviceInstance; // Enumerate all available resolutions: DEVMODE devMode; U32 modeNum = 0; U32 stillGoing = true; while ( stillGoing ) { dMemset( &devMode, 0, sizeof( devMode ) ); devMode.dmSize = sizeof( devMode ); stillGoing = EnumDisplaySettings( NULL, modeNum++, &devMode ); if (( devMode.dmPelsWidth >= 480) && (devMode.dmPelsHeight >= 360 ) && ( devMode.dmBitsPerPel == 16 || devMode.dmBitsPerPel == 32 )) { GFXVideoMode vmAdd; vmAdd.bitDepth = devMode.dmBitsPerPel; vmAdd.fullScreen = true; vmAdd.refreshRate = devMode.dmDisplayFrequency; vmAdd.resolution.x = devMode.dmPelsWidth; vmAdd.resolution.y = devMode.dmPelsHeight; // Only add this resolution if it is not already in the list: bool alreadyInList = false; for (Vector<GFXVideoMode>::iterator i = toAdd->mAvailableModes.begin(); i != toAdd->mAvailableModes.end(); i++) { if (vmAdd == *i) { alreadyInList = true; break; } } if(alreadyInList) continue; toAdd->mAvailableModes.push_back( vmAdd ); } } // Add to the list of available adapters. adapterList.push_back(toAdd); // Cleanup our window wglMakeCurrent(NULL, NULL); wglDeleteContext(tempGLRC); ReleaseDC(hwnd, tempDC); DestroyWindow(hwnd); UnregisterClass(L"GFX-OpenGL", winState.appInstance); }