Window::Window(HINSTANCE instance,const char* windowName,int width,int height) { //Windowclass, defines template for windows WNDCLASSEX wndClass; wndClass.cbSize = sizeof(WNDCLASSEX); wndClass.style = CS_HREDRAW | CS_VREDRAW; wndClass.lpfnWndProc = wEventsProc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = instance; wndClass.hIcon = NULL; wndClass.hCursor = NULL; wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wndClass.lpszMenuName = NULL; wndClass.lpszClassName = L"windowClass"; wndClass.hIconSm = NULL; //register window class if(!RegisterClassEx(&wndClass)) { //FAIL } //Creates window and return handle to it (a way to access the windows attributes) handle = CreateWindowA("windowClass", windowName, WS_OVERLAPPED, 0, 0, width, height, NULL, NULL, instance, NULL); if (handle == NULL) { //0.o } ShowWindow(handle, SW_SHOWNORMAL); UpdateWindow(handle); //pixel format description, only point worth of notice is if its 32 or 24 bit (alpha or no alpha) PIXELFORMATDESCRIPTOR pixelFormatDesc = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 24, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; //Device Contex handle hdc = GetDC(handle); // Gets the display context if(hdc == NULL) { //0.o } int pixelFormat = ChoosePixelFormat(hdc, &pixelFormatDesc); // Chooses the pixel format if(pixelFormat == 0) { //0.o } // Sets the pixel format if(SetPixelFormat(hdc, pixelFormat, &pixelFormatDesc) == 0) { //return 0; } HGLRC hglrc = wglCreateContext(hdc); // Creates the rendering context if(hglrc == NULL) { //0.o } // Attaches the rendering context if(wglMakeCurrent(hdc, hglrc) == 0) { //return 0; } LoadOpenGLFunctions(); // Loads OpenGL 2.1 functions //glViewport(0, 0, width, height); // Sets up the OpenGL viewport MSG msg ={}; Engine* engine = new Engine(); engine->fixAspectRatio(1024,768,width,height); //1024,768 // Main message loop: while(msg.message != WM_QUIT) { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } else // We've processed all pending Win32 messages, and can now do a rendering update. { } //glClear(GL_COLOR_BUFFER_BIT); engine->Update(); engine->Draw(); SwapBuffers(Window::hdc); // Swaps display buffers } }
window::window(int width, int height, bool fullScreen, std::wstring ptitle) : width (width), height(height), fullScreen(fullScreen), title(ptitle) { windowHandle = 0; deviceContext = 0; renderingContext = 0; WNDCLASSEX windowClass = {0}; windowClass.cbSize = sizeof(windowClass); windowClass.hInstance = GetModuleHandle(0); windowClass.style = CS_OWNDC; windowClass.hIcon = LoadIcon(windowClass.hInstance, MAKEINTRESOURCE(129)); windowClass.lpfnWndProc = wndproc; windowClass.lpszClassName = L"classy class"; ZeroMemory(keyDown, 256*sizeof(bool)); mouseLeft = mouseRight = false; RegisterClassEx(&windowClass); HWND temporaryWindow = CreateWindowEx(WS_EX_APPWINDOW, L"classy class", L"temporary", WS_SYSMENU|WS_BORDER|WS_MINIMIZEBOX, 0, 0, 0, 0, 0, 0, windowClass.hInstance, 0); HDC temporaryDeviceContext = GetDC(temporaryWindow); PIXELFORMATDESCRIPTOR pixelFormat = {0}; pixelFormat.nSize = sizeof(pixelFormat); pixelFormat.nVersion = 1; pixelFormat.dwFlags = PFD_DRAW_TO_WINDOW|PFD_SUPPORT_OPENGL|PFD_DOUBLEBUFFER; pixelFormat.cColorBits = 32; pixelFormat.cDepthBits = 24; SetPixelFormat(temporaryDeviceContext, ChoosePixelFormat(temporaryDeviceContext, &pixelFormat), &pixelFormat); HGLRC temporaryRenderingContext = wglCreateContext(temporaryDeviceContext); wglMakeCurrent(temporaryDeviceContext, temporaryRenderingContext); const int formatAttributes[] = { WGL_DRAW_TO_WINDOW_ARB, 1, WGL_SUPPORT_OPENGL_ARB, 1, WGL_ACCELERATION_ARB, 0x2027, WGL_DOUBLE_BUFFER_ARB, 1, WGL_PIXEL_TYPE_ARB, 0x202B, WGL_COLOR_BITS_ARB, 32, WGL_DEPTH_BITS_ARB, 24, 0 }; const int contextAttributes[] = { WGL_CONTEXT_PROFILE_MASK_ARB, 1, WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 3, 0 }; int format, formatcount; RECT windowArea = {0, 0, width, height}; DWORD displayFlags = WS_POPUP; if(fullScreen) { DEVMODE dev = {0}; dev.dmSize = sizeof(DEVMODE); dev.dmFields = DM_PELSWIDTH|DM_PELSHEIGHT|DM_BITSPERPEL; dev.dmPelsWidth = width; dev.dmPelsHeight = height; dev.dmBitsPerPel = 32; ChangeDisplaySettings(&dev, CDS_FULLSCREEN); } else { displayFlags = WS_SYSMENU|WS_CAPTION|WS_MINIMIZEBOX|WS_BORDER; AdjustWindowRect(&windowArea, displayFlags, 0); windowArea.right -= windowArea.left; windowArea.bottom -= windowArea.top; windowArea.left = (GetSystemMetrics(SM_CXSCREEN)-windowArea.right )/2; windowArea.top = (GetSystemMetrics(SM_CYSCREEN)-windowArea.bottom)/2; } windowHandle = CreateWindowEx(WS_EX_APPWINDOW, L"classy class", title.c_str(), displayFlags, windowArea.left, windowArea.top, windowArea.right, windowArea.bottom, 0, 0, windowClass.hInstance, 0); deviceContext = GetDC(windowHandle); ((PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"))(deviceContext, formatAttributes, 0, 1, &format, (UINT*)&formatcount); SetPixelFormat(deviceContext, format, &pixelFormat); renderingContext = ((PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"))(deviceContext, 0, contextAttributes); wglMakeCurrent(deviceContext, renderingContext); wglDeleteContext(temporaryRenderingContext); ReleaseDC(temporaryWindow, temporaryDeviceContext); DestroyWindow(temporaryWindow); MSG message; while(PeekMessage(&message, 0, 0, 0, PM_REMOVE)); #include "glloading.h" printf("Vendor : %s\nRenderer : %s\nOpenGL version : %s\nGLSL version : %s\n",glGetString(GL_VENDOR), glGetString(GL_RENDERER), glGetString(GL_VERSION), glGetString(GL_SHADING_LANGUAGE_VERSION)); ShowWindow(windowHandle, SW_SHOW); glViewport(0, 0, width, height); glClearColor(.0f,.0f,.0f,.0f); glClear(GL_COLOR_BUFFER_BIT); SwapBuffers(deviceContext); Gdiplus::GdiplusStartupInput gdiInput; ZeroMemory(&gdiInput, sizeof(gdiInput)); gdiInput.GdiplusVersion = 1; Gdiplus::GdiplusStartup((ULONG_PTR*)&gdiToken, &gdiInput, 0); /*int charsize = 64; int fontsize = 16*charsize; Gdiplus::Font f(L"Segoe UI Light", float(charsize)*.7f, Gdiplus::FontStyleItalic, Gdiplus::UnitPixel, 0); Gdiplus::Bitmap canvas(fontsize, fontsize, PixelFormat32bppARGB); Gdiplus::Graphics gfx((Gdiplus::Image*)&canvas); gfx.Clear(Gdiplus::Color(0,0,0)); Gdiplus::SolidBrush brush(Gdiplus::Color(255,255,255)); Gdiplus::Rect r(0,0, fontsize, fontsize); for(int i = 0; i<16; i++) for(int j = 0; j<16; j++) { wchar_t k = i*16+j; Gdiplus::PointF point(float(charsize)*(float(i)+.2f), float(charsize)*(float(j)+.1f)); gfx.DrawString(&k, 1, &f, point, &brush); }*/ startTime = GetTickCount(); frameStartTime = startTime+1000; frameCount = 0; defaultid = 0; }
PRBool nsGLPbufferWGL::Resize(PRInt32 width, PRInt32 height) { if (mWidth == width && mHeight == height) { return PR_TRUE; } Destroy(); nsresult rv; nsCOMPtr<nsIPrefService> prefService = do_GetService(NS_PREFSERVICE_CONTRACTID, &rv); NS_ENSURE_SUCCESS(rv, PR_FALSE); nsCOMPtr<nsIPrefBranch> prefBranch; rv = prefService->GetBranch("extensions.canvas3d.", getter_AddRefs(prefBranch)); NS_ENSURE_SUCCESS(rv, PR_FALSE); PRInt32 prefAntialiasing; rv = prefBranch->GetIntPref("antialiasing", &prefAntialiasing); if (NS_FAILED(rv)) prefAntialiasing = 0; mThebesSurface = CanvasGLThebes::CreateImageSurface(gfxIntSize(width, height), gfxASurface::ImageFormatARGB32); if (mThebesSurface->CairoStatus() != 0) { fprintf (stderr, "image surface failed\n"); return PR_FALSE; } // clear the surface memset (mThebesSurface->Data(), 0, height * mThebesSurface->Stride()); if (!wglMakeCurrent(mGlewDC, (HGLRC) mGlewWglContext)) { fprintf (stderr, "Error: %d\n", GetLastError()); LogMessage(NS_LITERAL_CSTRING("Canvas 3D: wglMakeCurrent failed")); return PR_FALSE; } PRBool ignoreAA = PR_FALSE; int attribs[] = { WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_DRAW_TO_PBUFFER_ARB, GL_TRUE, WGL_DOUBLE_BUFFER_ARB, GL_FALSE, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_COLOR_BITS_ARB, 32, WGL_RED_BITS_ARB, 8, WGL_GREEN_BITS_ARB, 8, WGL_BLUE_BITS_ARB, 8, WGL_ALPHA_BITS_ARB, 8, 0, 0, 0, 0, 0 }; float fattribs[] = { 0.0f }; // ATI's OpenGL impl seems to have a problem with calling // wglChoosePixelFormatARB with NULL/0 to obtain the number of // matching formats; so just allocate room for a lot. #define MAX_NUM_FORMATS 256 UINT numFormats = MAX_NUM_FORMATS; nsAutoArrayPtr<int> formats = new int[numFormats]; //fprintf (stderr, "EXT: %p ARB: %p rest: %s\n", wglewGetContext()->__wglewChoosePixelFormatEXT, wglewGetContext()->__wglewChoosePixelFormatARB, wglGetExtensionsStringARB(mGlewDC)); TRY_FIND_AGAIN: if (ignoreAA) { attribs[18] = 0; } else if (prefAntialiasing > 0) { attribs[18] = WGL_SAMPLE_BUFFERS_ARB; attribs[19] = 1; attribs[20] = WGL_SAMPLES_ARB; attribs[21] = 1 << prefAntialiasing; } if (!gWGLWrap.fChoosePixelFormat(mGlewDC, attribs, NULL, numFormats, formats, &numFormats) || numFormats == 0) { if (!ignoreAA) { ignoreAA = PR_TRUE; goto TRY_FIND_AGAIN; } LogMessage(NS_LITERAL_CSTRING("Canvas 3D: wglChoosePixelFormat failed (or couldn't find any matching formats).")); ReleaseDC(NULL, mGlewDC); return PR_FALSE; } int chosenFormat = -1; int question,answer; for (int priority = 6; priority > 0; priority--) { //fprintf (stderr, "---- priority: %d\n", priority); for (UINT i = 0; i < numFormats; i++) { int fmt = formats[i]; #define CHECK_ATTRIB(q, test) \ question = (q); \ if (!gWGLWrap.fGetPixelFormatAttribiv(mGlewDC, fmt, 0, 1, &question, &answer)) { \ /*fprintf (stderr, "check for %d failed\n", q);*/ \ continue; \ } \ /*fprintf (stderr, #q " -> %d\n", answer);*/ \ if (test) { \ continue; \ } //fprintf (stderr, "Format %d:\n", fmt); switch (priority) { case 6: CHECK_ATTRIB(WGL_ACCUM_BITS_ARB, answer != 0) case 5: CHECK_ATTRIB(WGL_STENCIL_BITS_ARB, answer != 0) // XXX we only pick 2xAA here, should let user choose case 4: CHECK_ATTRIB(WGL_SAMPLE_BUFFERS_ARB, answer != (prefAntialiasing != 0)) case 3: CHECK_ATTRIB(WGL_SAMPLES_ARB, answer != (prefAntialiasing ? (1 << prefAntialiasing) : 0)) case 2: CHECK_ATTRIB(WGL_DEPTH_BITS_ARB, answer < 8) case 1: CHECK_ATTRIB(WGL_COLOR_BITS_ARB, answer != 32) default: chosenFormat = fmt; } #undef CHECK_ATTRIB } if (chosenFormat != -1) break; } if (chosenFormat == -1) { LogMessage(NS_LITERAL_CSTRING("Canvas 3D: Couldn't find a suitable pixel format!")); return PR_FALSE; } // ok, we now have a pixel format fprintf (stderr, "***** Chose pixel format: %d\n", chosenFormat); int pbattribs = 0; mPbuffer = gWGLWrap.fCreatePbuffer(mGlewDC, chosenFormat, width, height, &pbattribs); if (!mPbuffer) { LogMessage(NS_LITERAL_CSTRING("Canvas 3D: Failed to create pbuffer")); return PR_FALSE; } mPbufferDC = gWGLWrap.fGetPbufferDC(mPbuffer); mPbufferContext = wglCreateContext(mPbufferDC); mWindowsSurface = new gfxWindowsSurface(gfxIntSize(width, height), gfxASurface::ImageFormatARGB32); if (mWindowsSurface && mWindowsSurface->CairoStatus() == 0) mThebesSurface = mWindowsSurface->GetImageSurface(); mWidth = width; mHeight = height; fprintf (stderr, "Resize: %d %d\n", width, height); return PR_TRUE; }
static LONG WINAPI WindowFunc(HWND hWnd,UINT msg,WPARAM wp,LPARAM lp) { switch(msg) { case WM_QUERYNEWPALETTE: case WM_PALETTECHANGED: if(NULL!=fsWin32Internal.hPlt) { SelectPalette(fsWin32Internal.hDC,fsWin32Internal.hPlt,FALSE); RealizePalette(fsWin32Internal.hDC); } return DefWindowProc(hWnd,msg,wp,lp); case WM_CREATE: fsWin32Internal.hDC=GetDC(hWnd); YsSetPixelFormat(fsWin32Internal.hDC); fsWin32Internal.hRC=wglCreateContext(fsWin32Internal.hDC); wglMakeCurrent(fsWin32Internal.hDC,fsWin32Internal.hRC); if(0==doubleBuffer) { glDrawBuffer(GL_FRONT); } InitializeOpenGL(hWnd); break; case WM_SIZE: wglMakeCurrent(fsWin32Internal.hDC,fsWin32Internal.hRC); break; case WM_PAINT: wglMakeCurrent(fsWin32Internal.hDC,fsWin32Internal.hRC); exposure=1; return DefWindowProc(hWnd,msg,wp,lp); case WM_COMMAND: break; case WM_DESTROY: exit(1); break; case WM_MOUSEWHEEL: { int step; step=HIWORD(wp); if(step>=0x8000) { step-=0x10000; } step/=WHEEL_DELTA; if(step>0) { while(step>0) { if(nKeyBufUsed<NKEYBUF) { keyBuffer[nKeyBufUsed++]=FSKEY_WHEELUP; } step--; } } else if(step<0) { while(step<0) { if(nKeyBufUsed<NKEYBUF) { keyBuffer[nKeyBufUsed++]=FSKEY_WHEELDOWN; } step++; } } } break; case WM_SYSKEYDOWN: if((lp & (1<<29))!=0 && // Alt (wp==VK_MENU || wp==VK_OEM_1 || wp==VK_OEM_PLUS || wp==VK_OEM_COMMA || wp==VK_OEM_MINUS || wp==VK_OEM_PERIOD || wp==VK_OEM_2 || wp==VK_OEM_3 || wp==VK_OEM_4 || wp==VK_OEM_5 || wp==VK_OEM_6 || wp==VK_OEM_7 || wp==VK_OEM_8 || #ifdef VK_OEM_AX wp==VK_OEM_AX || #endif wp==VK_OEM_102 || wp=='0' || wp=='1' || wp=='2' || wp=='3' || wp=='4' || wp=='5' || wp=='6' || wp=='7' || wp=='8' || wp=='9' || wp=='A' || wp=='B' || wp=='C' || wp=='D' || wp=='E' || wp=='F' || wp=='G' || wp=='H' || wp=='I' || wp=='J' || wp=='K' || wp=='L' || wp=='M' || wp=='N' || wp=='O' || wp=='P' || wp=='Q' || wp=='R' || wp=='S' || wp=='T' || wp=='U' || wp=='V' || wp=='W' || wp=='X' || wp=='Y' || wp=='Z' || wp==VK_ESCAPE || wp==VK_F1 || wp==VK_F2 || wp==VK_F3 || /* wp==VK_F4 || */ wp==VK_F5 || wp==VK_F6 || wp==VK_F7 || wp==VK_F8 || wp==VK_F9 || wp==VK_F10 || wp==VK_F11 || wp==VK_F12 || wp==VK_RETURN || wp==VK_NUMLOCK || wp==VK_NUMPAD0 || wp==VK_NUMPAD1 || wp==VK_NUMPAD2 || wp==VK_NUMPAD3 || wp==VK_NUMPAD4 || wp==VK_NUMPAD5 || wp==VK_NUMPAD6 || wp==VK_NUMPAD7 || wp==VK_NUMPAD8 || wp==VK_NUMPAD9 || wp==VK_DECIMAL || wp==VK_DIVIDE || wp==VK_MULTIPLY || wp==VK_SUBTRACT || wp==VK_ADD)) { int keyCode; keyCode=fsKeyMapper.VkToFsKey(wp); if(keyCode!=0 && nKeyBufUsed<NKEYBUF) { keyBuffer[nKeyBufUsed++]=keyCode; } return 0; } return DefWindowProc(hWnd,msg,wp,lp); case WM_SYSKEYUP: return 0; case WM_KEYDOWN: if(nKeyBufUsed<NKEYBUF) { int keyCode; keyCode=fsKeyMapper.VkToFsKey(wp); if(keyCode!=0) { keyBuffer[nKeyBufUsed++]=keyCode; } } break; case WM_CHAR: if(nCharBufUsed<NKEYBUF) { charBuffer[nCharBufUsed++]=wp; } break; case WM_ERASEBKGND: return 1; case WM_LBUTTONDOWN: case WM_LBUTTONUP: case WM_MBUTTONDOWN: case WM_MBUTTONUP: case WM_RBUTTONDOWN: case WM_RBUTTONUP: case WM_MOUSEMOVE: if(nMosBufUsed<NKEYBUF) { int eventType; switch(msg) { default: eventType=FSMOUSEEVENT_NONE; break; case WM_LBUTTONDOWN: eventType=FSMOUSEEVENT_LBUTTONDOWN; break; case WM_LBUTTONUP: eventType=FSMOUSEEVENT_LBUTTONUP; break; case WM_MBUTTONDOWN: eventType=FSMOUSEEVENT_MBUTTONDOWN; break; case WM_MBUTTONUP: eventType=FSMOUSEEVENT_MBUTTONUP; break; case WM_RBUTTONDOWN: eventType=FSMOUSEEVENT_RBUTTONDOWN; break; case WM_RBUTTONUP: eventType=FSMOUSEEVENT_RBUTTONUP; break; case WM_MOUSEMOVE: eventType=FSMOUSEEVENT_MOVE; break; } int lb=((wp & MK_LBUTTON)!=0); int mb=((wp & MK_MBUTTON)!=0); int rb=((wp & MK_RBUTTON)!=0); unsigned int shift=((wp & MK_SHIFT)!=0); unsigned int ctrl=((wp & MK_CONTROL)!=0); int mx=LOWORD(lp); int my=HIWORD(lp); if(eventType==FSMOUSEEVENT_MOVE && 0<nMosBufUsed && mosBuffer[nMosBufUsed-1].eventType==FSMOUSEEVENT_MOVE && mosBuffer[nMosBufUsed-1].lb==lb && mosBuffer[nMosBufUsed-1].mb==mb && mosBuffer[nMosBufUsed-1].rb==rb && mosBuffer[nMosBufUsed-1].shift==shift && mosBuffer[nMosBufUsed-1].ctrl==ctrl) { mosBuffer[nMosBufUsed-1].mx=mx; mosBuffer[nMosBufUsed-1].my=my; break; } mosBuffer[nMosBufUsed].eventType=eventType; mosBuffer[nMosBufUsed].lb=lb; mosBuffer[nMosBufUsed].mb=mb; mosBuffer[nMosBufUsed].rb=rb; mosBuffer[nMosBufUsed].shift=shift; mosBuffer[nMosBufUsed].ctrl=ctrl; mosBuffer[nMosBufUsed].mx=mx; mosBuffer[nMosBufUsed].my=my; nMosBufUsed++; } break; default: return DefWindowProc(hWnd,msg,wp,lp); } return 1; }
LRESULT GLWindow::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_CREATE: // window creation { m_hdc = GetDC(hWnd); setupPixelFormat(); //Set the version that we want, in this case 3.0 int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 0, 0}; //zero indicates the end of the array //Create temporary context so we can get a pointer to the function HGLRC tmpContext = wglCreateContext(m_hdc); //Make it current wglMakeCurrent(m_hdc, tmpContext); //Get the function pointer wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB"); //If this is NULL then OpenGL 3.0 is not supported if (!wglCreateContextAttribsARB) { std::cerr << "OpenGL 3.0 is not supported, falling back to GL 2.1" << std::endl; m_hglrc = tmpContext; } else { // Create an OpenGL 3.0 context using the new function m_hglrc = wglCreateContextAttribsARB(m_hdc, 0, attribs); //Delete the temporary context wglDeleteContext(tmpContext); } //Make the GL3 context current wglMakeCurrent(m_hdc, m_hglrc); m_isRunning = true; //Mark our window as running } break; case WM_DESTROY: // window destroy case WM_CLOSE: // windows is closing wglMakeCurrent(m_hdc, NULL); wglDeleteContext(m_hglrc); m_isRunning = false; //Stop the main loop PostQuitMessage(0); //Send a WM_QUIT message return 0; break; case WM_SIZE: { int height = HIWORD(lParam); // retrieve width and height int width = LOWORD(lParam); getAttachedExample()->onResize(width, height); //Call the example's resize method } break; case WM_KEYDOWN: if (wParam == VK_ESCAPE) //If the escape key was pressed { DestroyWindow(m_hwnd); //Send a WM_DESTROY message } break; default: break; } return DefWindowProc(hWnd, uMsg, wParam, lParam); }
bool csGraphics2DOpenGL::Open () { if (is_open) return true; csRef<iVerbosityManager> verbosemgr ( csQueryRegistry<iVerbosityManager> (object_reg)); if (verbosemgr) detector.SetVerbose (verbosemgr->Enabled ("renderer.windows.gldriver")); // create the window. if (FullScreen) { SwitchDisplayMode (false); } int pixelFormat = -1; csGLPixelFormatPicker picker (this); /* Check if the WGL pixel format check should be used at all. It appears that some drivers take "odd" choices when using the WGL pixel format path (e.g. returning Accum-capable formats even if none was requested). */ bool doWGLcheck = false; { GLPixelFormat format; if (picker.GetNextFormat (format)) { doWGLcheck = (format[glpfvMultiSamples] != 0); picker.Reset (); } } if (doWGLcheck) pixelFormat = FindPixelFormatWGL (picker); m_bActivated = true; int wwidth = fbWidth; int wheight = fbHeight; DWORD exStyle = 0; DWORD style = WS_POPUP | WS_SYSMENU; int xpos = 0; int ypos = 0; if (FullScreen) { /*exStyle |= WS_EX_TOPMOST;*/ } else { style |= WS_CAPTION | WS_MINIMIZEBOX; if (AllowResizing) style |= WS_THICKFRAME | WS_MAXIMIZEBOX; wwidth += 2 * GetSystemMetrics (SM_CXFIXEDFRAME); wheight += 2 * GetSystemMetrics (SM_CYFIXEDFRAME) + GetSystemMetrics (SM_CYCAPTION); xpos = (GetSystemMetrics (SM_CXSCREEN) - wwidth) / 2; ypos = (GetSystemMetrics (SM_CYSCREEN) - wheight) / 2; } m_hWnd = m_piWin32Assistant->CreateCSWindow (this, exStyle, style, xpos, ypos, wwidth, wheight); if (!m_hWnd) SystemFatalError (L"Cannot create Crystal Space window", GetLastError()); SetTitle (win_title); // Subclass the window if (IsWindowUnicode (m_hWnd)) { m_OldWndProc = (WNDPROC)SetWindowLongPtrW (m_hWnd, GWLP_WNDPROC, (LONG_PTR) WindowProc); SetWindowLongPtrW (m_hWnd, GWLP_USERDATA, (LONG_PTR)this); } else { m_OldWndProc = (WNDPROC)SetWindowLongPtrA (m_hWnd, GWLP_WNDPROC, (LONG_PTR) WindowProc); SetWindowLongPtrA (m_hWnd, GWLP_USERDATA, (LONG_PTR)this); } hDC = GetDC (m_hWnd); if (pixelFormat == -1) { picker.Reset(); pixelFormat = FindPixelFormatGDI (hDC, picker); } PIXELFORMATDESCRIPTOR pfd; if (DescribePixelFormat (hDC, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd) == 0) SystemFatalError (L"DescribePixelFormat failed.", GetLastError()); if (SetPixelFormat (hDC, pixelFormat, &pfd) != TRUE) { HRESULT spfErr = (HRESULT)GetLastError(); SystemFatalError (L"SetPixelFormat failed.", spfErr); } currentFormat[glpfvColorBits] = pfd.cColorBits; currentFormat[glpfvAlphaBits] = pfd.cAlphaBits; currentFormat[glpfvDepthBits] = pfd.cDepthBits; currentFormat[glpfvStencilBits] = pfd.cStencilBits; currentFormat[glpfvAccumColorBits] = pfd.cAccumBits; currentFormat[glpfvAccumAlphaBits] = pfd.cAccumAlphaBits; Depth = pfd.cColorBits; hardwareAccelerated = !(pfd.dwFlags & PFD_GENERIC_FORMAT) || (pfd.dwFlags & PFD_GENERIC_ACCELERATED); hGLRC = wglCreateContext (hDC); wglMakeCurrent (hDC, hGLRC); UpdateWindow (m_hWnd); ShowWindow (m_hWnd, m_nCmdShow); SetForegroundWindow (m_hWnd); SetFocus (m_hWnd); /* Small hack to emit "no HW acceleration" message on both GDI Generic and * sucky Direct3D default OpenGL */ hardwareAccelerated &= (strncmp ((char*)glGetString (GL_VENDOR), "Microsoft", 9) != 0); if (!hardwareAccelerated) { Report (CS_REPORTER_SEVERITY_WARNING, "No hardware acceleration!"); } detector.DoDetection (m_hWnd, hDC); Report (CS_REPORTER_SEVERITY_NOTIFY, "GL driver: %s %s", detector.GetDriverDLL(), detector.GetDriverVersion() ? detector.GetDriverVersion() : "<version unknown>"); if (FullScreen) { /* * from the Windows Shell docs: * "It is possible to cover the taskbar by explicitly setting the size * of the window rectangle equal to the size of the screen with * SetWindowPos." */ SetWindowPos (m_hWnd, CS_WINDOW_Z_ORDER, 0, 0, fbWidth, fbHeight, 0); } if (!csGraphics2DGLCommon::Open ()) return false; ext.InitWGL_EXT_swap_control (hDC); if (ext.CS_WGL_EXT_swap_control) { ext.wglSwapIntervalEXT (vsync ? 1 : 0); vsync = (ext.wglGetSwapIntervalEXT() != 0); Report (CS_REPORTER_SEVERITY_NOTIFY, "VSync is %s.", vsync ? "enabled" : "disabled"); } return true; }
/* ============ WZ_WndProc ============ */ LONG WINAPI WZ_WndProc ( HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { int fwKeys, xPos, yPos; RECT rect; GetClientRect(hWnd, &rect); switch (uMsg) { case WM_DESTROY: QEW_StopGL( hWnd, s_hglrcZ, s_hdcZ ); return 0; case WM_CREATE: s_hdcZ = GetDC(hWnd); QEW_SetupPixelFormat( s_hdcZ, false); if ( ( s_hglrcZ = wglCreateContext( s_hdcZ ) ) == 0 ) Error( "wglCreateContext in WZ_WndProc failed" ); if (!wglMakeCurrent( s_hdcZ, s_hglrcZ )) Error ("wglMakeCurrent in WZ_WndProc failed"); if (!wglShareLists( g_qeglobals.d_hglrcBase, s_hglrcZ ) ) Error( "wglShareLists in WZ_WndProc failed" ); return 0; case WM_PAINT: { PAINTSTRUCT ps; BeginPaint(hWnd, &ps); if ( !wglMakeCurrent( s_hdcZ, s_hglrcZ ) ) Error ("wglMakeCurrent failed"); QE_CheckOpenGLForErrors(); Z_Draw (); SwapBuffers(s_hdcZ); EndPaint(hWnd, &ps); } return 0; case WM_KEYDOWN: QE_KeyDown (wParam); return 0; case WM_MBUTTONDOWN: case WM_RBUTTONDOWN: case WM_LBUTTONDOWN: if (GetTopWindow(g_qeglobals.d_hwndMain) != hWnd) BringWindowToTop(hWnd); SetFocus( g_qeglobals.d_hwndZ ); SetCapture( g_qeglobals.d_hwndZ ); fwKeys = wParam; // key flags xPos = (short)LOWORD(lParam); // horizontal position of cursor yPos = (short)HIWORD(lParam); // vertical position of cursor yPos = (int)rect.bottom - 1 - yPos; Z_MouseDown (xPos, yPos, fwKeys); return 0; case WM_MBUTTONUP: case WM_RBUTTONUP: case WM_LBUTTONUP: fwKeys = wParam; // key flags xPos = (short)LOWORD(lParam); // horizontal position of cursor yPos = (short)HIWORD(lParam); // vertical position of cursor yPos = (int)rect.bottom - 1 - yPos; Z_MouseUp (xPos, yPos, fwKeys); if (! (fwKeys & (MK_LBUTTON|MK_RBUTTON|MK_MBUTTON))) ReleaseCapture (); return 0; case WM_GETMINMAXINFO: { MINMAXINFO *pmmi = (LPMINMAXINFO) lParam; pmmi->ptMinTrackSize.x = ZWIN_WIDTH; return 0; } case WM_MOUSEMOVE: fwKeys = wParam; // key flags xPos = (short)LOWORD(lParam); // horizontal position of cursor yPos = (short)HIWORD(lParam); // vertical position of cursor yPos = (int)rect.bottom - 1 - yPos; Z_MouseMoved (xPos, yPos, fwKeys); return 0; case WM_SIZE: z.width = rect.right; z.height = rect.bottom; InvalidateRect( g_qeglobals.d_hwndZ, NULL, false); return 0; case WM_NCCALCSIZE:// don't let windows copy pixels DefWindowProc (hWnd, uMsg, wParam, lParam); return WVR_REDRAW; case WM_KILLFOCUS: case WM_SETFOCUS: SendMessage( hWnd, WM_NCACTIVATE, uMsg == WM_SETFOCUS, 0 ); return 0; case WM_CLOSE: /* call destroy window to cleanup and go away */ DestroyWindow (hWnd); return 0; } return DefWindowProc (hWnd, uMsg, wParam, lParam); }
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag) { GLuint PixelFormat; // Holds The Results After Searching For A Match WNDCLASS wc; // Windows Class Structure DWORD dwExStyle; // Window Extended Style DWORD dwStyle; // Window Style RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values WindowRect.left=(long)0; // Set Left Value To 0 WindowRect.right=(long)width; // Set Right Value To Requested Width WindowRect.top=(long)0; // Set Top Value To 0 WindowRect.bottom=(long)height; // Set Bottom Value To Requested Height fullscreen=fullscreenflag; // Set The Global Fullscreen Flag hInstance = GetModuleHandle(NULL); // Grab An Instance For Our Window wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Redraw On Size, And Own DC For Window. wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages wc.cbClsExtra = 0; // No Extra Window Data wc.cbWndExtra = 0; // No Extra Window Data wc.hInstance = hInstance; // Set The Instance wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Load The Default Icon wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Load The Arrow Pointer wc.hbrBackground = NULL; // No Background Required For GL wc.lpszMenuName = NULL; // We Don't Want A Menu wc.lpszClassName = "OpenGL"; // Set The Class Name if (!RegisterClass(&wc)) // Attempt To Register The Window Class { MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (fullscreen) // Attempt Fullscreen Mode? { DEVMODE dmScreenSettings; // Device Mode memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure dmScreenSettings.dmPelsWidth = width; // Selected Screen Width dmScreenSettings.dmPelsHeight = height; // Selected Screen Height dmScreenSettings.dmBitsPerPel = bits; // Selected Bits Per Pixel dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; // Try To Set Selected Mode And Get Results. NOTE: CDS_FULLSCREEN Gets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { // If The Mode Fails, Offer Two Options. Quit Or Use Windowed Mode. if (MessageBox(NULL,"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?","NeHe GL",MB_YESNO|MB_ICONEXCLAMATION)==IDYES) { fullscreen=FALSE; // Windowed Mode Selected. Fullscreen = FALSE } else { // Pop Up A Message Box Letting User Know The Program Is Closing. MessageBox(NULL,"Program Will Now Close.","ERROR",MB_OK|MB_ICONSTOP); return FALSE; // Return FALSE } } } if (fullscreen) // Are We Still In Fullscreen Mode? { dwExStyle=WS_EX_APPWINDOW; // Window Extended Style dwStyle=WS_POPUP; // Windows Style ShowCursor(FALSE); // Hide Mouse Pointer } else { dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Window Extended Style dwStyle=WS_OVERLAPPEDWINDOW; // Windows Style } AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size // Create The Window if (!(hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window "OpenGL", // Class Name title, // Window Title dwStyle | // Defined Window Style WS_CLIPSIBLINGS | // Required Window Style WS_CLIPCHILDREN, // Required Window Style 0, 0, // Window Position WindowRect.right-WindowRect.left, // Calculate Window Width WindowRect.bottom-WindowRect.top, // Calculate Window Height NULL, // No Parent Window NULL, // No Menu hInstance, // Instance NULL))) // Dont Pass Anything To WM_CREATE { KillGLWindow(); // Reset The Display MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } static 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 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 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 }; if (!(hDC=GetDC(hWnd))) // Did We Get A Device Context? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd))) // Did Windows Find A Matching Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(hRC=wglCreateContext(hDC))) // Are We Able To Get A Rendering Context? { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!wglMakeCurrent(hDC,hRC)) // Try To Activate The Rendering Context { KillGLWindow(); // Reset The Display MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } ShowWindow(hWnd,SW_SHOW); // Show The Window SetForegroundWindow(hWnd); // Slightly Higher Priority SetFocus(hWnd); // Sets Keyboard Focus To The Window ReSizeGLScene(width, height); // Set Up Our Perspective GL Screen if (!InitGL()) // Initialize Our Newly Created GL Window { KillGLWindow(); // Reset The Display MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } return TRUE; // Success }
void Win32PBuffer::createPBuffer() { // Process format int bits=0; bool isFloat=false; #if 0 bool hasAlpha=true; #endif switch(mFormat) { case PCT_BYTE: bits=8; isFloat=false; break; case PCT_SHORT: bits=16; isFloat=false; break; case PCT_FLOAT16: bits=16; isFloat=true; break; case PCT_FLOAT32: bits=32; isFloat=true; break; default: break; }; LogManager::getSingleton().logMessage( " Win32PBuffer::Creating PBuffer of format bits="+ StringConverter::toString(bits)+ " float="+StringConverter::toString(isFloat) ); HDC old_hdc = wglGetCurrentDC(); HGLRC old_context = wglGetCurrentContext(); // Bind to RGB or RGBA texture int bttype = 0; #if 0 if(mUseBind) { // Only provide bind type when actually binding bttype = PixelUtil::hasAlpha(mInternalFormat)? WGL_BIND_TO_TEXTURE_RGBA_ARB : WGL_BIND_TO_TEXTURE_RGB_ARB; } int texformat = hasAlpha? WGL_TEXTURE_RGBA_ARB : WGL_TEXTURE_RGB_ARB; #endif // Make a float buffer? int pixeltype = isFloat? WGL_TYPE_RGBA_FLOAT_ARB: WGL_TYPE_RGBA_ARB; int attrib[] = { WGL_RED_BITS_ARB,bits, WGL_GREEN_BITS_ARB,bits, WGL_BLUE_BITS_ARB,bits, WGL_ALPHA_BITS_ARB,bits, WGL_STENCIL_BITS_ARB,1, WGL_DEPTH_BITS_ARB,15, WGL_DRAW_TO_PBUFFER_ARB,true, WGL_SUPPORT_OPENGL_ARB,true, WGL_PIXEL_TYPE_ARB,pixeltype, //WGL_DOUBLE_BUFFER_ARB,true, //WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB, // Make sure it is accelerated bttype,true, // must be last, as bttype can be zero 0 }; int pattrib_default[] = { 0 }; #if 0 int pattrib_bind[] = { WGL_TEXTURE_FORMAT_ARB, texformat, WGL_TEXTURE_TARGET_ARB, WGL_TEXTURE_2D_ARB, WGL_PBUFFER_LARGEST_ARB, true, 0 }; #endif int format; unsigned int count; PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); // Choose suitable pixel format wglChoosePixelFormatARB(old_hdc,attrib,NULL,1,&format,&count); if(count == 0) OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglChoosePixelFormatARB() failed", " Win32PBuffer::createPBuffer"); // Analyse pixel format const int piAttributes[]={ WGL_RED_BITS_ARB,WGL_GREEN_BITS_ARB,WGL_BLUE_BITS_ARB,WGL_ALPHA_BITS_ARB, WGL_DEPTH_BITS_ARB,WGL_STENCIL_BITS_ARB }; int piValues[sizeof(piAttributes)/sizeof(const int)]; PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribiv = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC)wglGetProcAddress("wglGetPixelFormatAttribivARB"); wglGetPixelFormatAttribiv(old_hdc,format,0,sizeof(piAttributes)/sizeof(const int),piAttributes,piValues); LogManager::getSingleton().stream() << " Win32PBuffer::PBuffer -- Chosen pixel format rgba=" << piValues[0] << "," << piValues[1] << "," << piValues[2] << "," << piValues[3] << " depth=" << piValues[4] << " stencil=" << piValues[5]; // FIXME lookup procaddress mPBuffer = 0;//wglCreatePbufferARB(old_hdc,format,mWidth,mHeight,pattrib_default); if(!mPBuffer) OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglCreatePbufferARB() failed", " Win32PBuffer::createPBuffer"); #if 0 mHDC = wglGetPbufferDCARB(mPBuffer); if(!mHDC) { wglDestroyPbufferARB(mPBuffer); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglGetPbufferDCARB() failed", " Win32PBuffer::createPBuffer"); } mGlrc = wglCreateContext(mHDC); if(!mGlrc) { wglReleasePbufferDCARB(mPBuffer,mHDC); wglDestroyPbufferARB(mPBuffer); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglCreateContext() failed", " Win32PBuffer::createPBuffer"); } if(!wglShareLists(old_context,mGlrc)) { wglDeleteContext(mGlrc); wglReleasePbufferDCARB(mPBuffer,mHDC); wglDestroyPbufferARB(mPBuffer); OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR, "wglShareLists() failed", " Win32PBuffer::createPBuffer"); } // Query real width and height int iWidth, iHeight; wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_WIDTH_ARB, &iWidth); wglQueryPbufferARB(mPBuffer, WGL_PBUFFER_HEIGHT_ARB, &iHeight); mWidth = iWidth; mHeight = iHeight; LogManager::getSingleton().stream() << "Win32RenderTexture::PBuffer created -- Real dimensions " << mWidth << "x" << mHeight; #endif }
//------------------------------------------------------------------------------ //-------------------------------------- // Object proper... //-------------------------------------- // Surface* Surface::create(HWND io_clientWnd, const Int32 in_width, const Int32 in_height) { // Must return a new OpenGL::Surface* of resolution closest to in_w/h. // Should also activate the device. // AssertFatal(io_clientWnd != NULL, "No client window handle"); Surface* pRetSurf = new Surface; #ifndef DEBUG BOOL test = TRUE; bool found = false; UInt32 modeNum = 0; DEVMODE devMode; while (test == TRUE) { memset(&devMode, 0, sizeof(devMode)); devMode.dmSize = sizeof(devMode); test = EnumDisplaySettings(NULL, modeNum, &devMode); if (devMode.dmPelsWidth == (UInt32)in_width && devMode.dmPelsHeight == (UInt32)in_height) { found = true; } modeNum++; } if (found == false) { delete pRetSurf; return NULL; } // Change the window position AssertMessage(false, avar("Changing window style (%d, %d)", in_width, in_height)); GetWindowRect(io_clientWnd, &pRetSurf->m_oldWindowRect); LONG style = GetWindowLong(io_clientWnd, GWL_STYLE); style &= ~(WS_CAPTION | WS_SYSMENU | WS_THICKFRAME); SetWindowLong(io_clientWnd, GWL_STYLE, style); LONG exStyle = GetWindowLong(io_clientWnd, GWL_EXSTYLE); exStyle |= WS_EX_TOPMOST; SetWindowLong(io_clientWnd, GWL_EXSTYLE, exStyle); BOOL posSuccess = SetWindowPos(io_clientWnd, 0, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_FRAMECHANGED); AssertFatal(posSuccess == TRUE, "Error setting pos"); // Annnnd, set the new display mode. Desktop icons? // memset(&devMode, 0, sizeof(devMode)); devMode.dmSize = sizeof(devMode); devMode.dmPelsWidth = in_width; devMode.dmPelsHeight = in_height; devMode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT; #if 1 AssertMessage(false, avar("Changing display settings: (%d, %d)", devMode.dmPelsWidth, devMode.dmPelsHeight)); ChangeDisplaySettings(&devMode, CDS_FULLSCREEN); VidModeChecker::sm_theInstance.changedDisplaySettings(); #endif SetForegroundWindow(io_clientWnd); posSuccess = SetWindowPos(io_clientWnd, HWND_TOPMOST, 0, 0, in_width, in_height, SWP_FRAMECHANGED); AssertFatal(posSuccess == TRUE, "Error setting pos"); pRetSurf->m_windowStyleChanged = true; #endif pRetSurf->m_hWnd = io_clientWnd; pRetSurf->m_hDC = GetDC(pRetSurf->m_hWnd); if (pRetSurf->m_hDC == NULL) { AssertWarn(0, "Unable to get a DC for the window"); delete pRetSurf; return NULL; } // Set the Pixel format, first retrieving the old format // pRetSurf->m_oldPixelFormat = GetPixelFormat(pRetSurf->m_hDC); DescribePixelFormat(pRetSurf->m_hDC, pRetSurf->m_oldPixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pRetSurf->m_oldPixelFormatDescriptor); int chosenPixelFormat; PIXELFORMATDESCRIPTOR chosenPFD; if (pRetSurf->choosePixelFormat(chosenPixelFormat, chosenPFD, pRetSurf->m_hWnd, pRetSurf->m_hDC) == false) { AssertWarn(0, "Unable to choose a pixel format"); delete pRetSurf; return NULL; } BOOL spSuccess = SetPixelFormat(pRetSurf->m_hDC, chosenPixelFormat, &chosenPFD); if (spSuccess != TRUE) { AssertWarn(0, "Unable to set the pixel format"); delete pRetSurf; return NULL; } // Create the HGLRC // pRetSurf->m_hGLRC = wglCreateContext(pRetSurf->m_hDC); if (pRetSurf->m_hGLRC == NULL) { AssertWarn(0, "Unable to create a GL Render context"); delete pRetSurf; return NULL; } BOOL mcSuccess = wglMakeCurrent(pRetSurf->m_hDC, pRetSurf->m_hGLRC); if (mcSuccess != TRUE) { AssertWarn(0, "Unable to make the GL Render context current"); delete pRetSurf; return NULL; } pRetSurf->m_glrcMadeCurrent = true; // Retreive the strings associated with this driver, they are useful // for debugging and such... // const char* pVendor = (const char*)glGetString(GL_VENDOR); const char* pRenderer = (const char*)glGetString(GL_RENDERER); const char* pVersion = (const char*)glGetString(GL_VERSION); const char* pExtensions = (const char*)glGetString(GL_EXTENSIONS); if (pVendor != NULL) { pRetSurf->m_pVendorString = new char[strlen(pVendor) + 1]; strcpy(pRetSurf->m_pVendorString, pVendor); } if (pRenderer != NULL) { pRetSurf->m_pRendererString = new char[strlen(pRenderer) + 1]; strcpy(pRetSurf->m_pRendererString, pRenderer); } if (pVersion != NULL) { pRetSurf->m_pVersionString = new char[strlen(pVersion) + 1]; strcpy(pRetSurf->m_pVersionString, pVersion); } if (pExtensions != NULL) { pRetSurf->m_pExtensionsString = new char[strlen(pExtensions) + 1]; strcpy(pRetSurf->m_pExtensionsString, pExtensions); } // Allocate our vertex arrays... // pRetSurf->m_pVertexArray = new DGLVertex4F[sm_maxNumVertices]; pRetSurf->m_pColorArray = new DGLColor4F[sm_maxNumVertices]; pRetSurf->m_pTexCoord0Array = new DGLTexCoord4F[sm_maxNumVertices]; pRetSurf->m_pHazeStoreArray = new DGLHazeCoordF[sm_maxNumVertices]; pRetSurf->surfaceWidth = in_width; pRetSurf->surfaceHeight = in_height; // Create the texture/handle cache... // pRetSurf->m_pTextureCache = new TextureCache(pRetSurf); pRetSurf->m_pHandleCache = new HandleCache(2048, 2153); // Set up our default state... // pRetSurf->setFillMode(GFX_FILL_CONSTANT); pRetSurf->setFillColor(&ColorF(0, 0, 0)); pRetSurf->setAlphaSource(GFX_ALPHA_NONE); pRetSurf->setShadeSource(GFX_SHADE_NONE); pRetSurf->setHazeSource(GFX_HAZE_NONE); pRetSurf->setTextureWrap(true); pRetSurf->setTransparency(false); glPixelStorei(GL_UNPACK_ALIGNMENT, 1); // We're ready to go... // return pRetSurf; }
static int togl_pixelFormat(Togl *togl, HWND hwnd) { /* return 0 when pixel format is unavailable. */ int pixelformat = 0; static int loadedOpenGL = FALSE; int formats[256]; UINT numFormats; FBInfo *info; UINT i; int attribs[128]; int na = 0; if (!loadedOpenGL) { HWND test = NULL; HDC dc; HGLRC rc; if (wglGetCurrentContext() != NULL) { dc = wglGetCurrentDC(); } else { /* HWND hwnd = Tk_GetHWND(Tk_WindowId(togl->TkWin)); */ test = toglCreateTestWindow(hwnd); if (test == NULL) { Tcl_SetResult(togl->Interp, TCL_STUPID "can't create dummy OpenGL window", TCL_STATIC); return 0; } dc = GetDC(test); rc = wglCreateContext(dc); wglMakeCurrent(dc, rc); } loadedOpenGL = TRUE; /* * Now that we have an OpenGL window, we can initialize all * OpenGL information and figure out if multisampling is supported. */ getExtensionsString = (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress("wglGetExtensionsStringARB"); if (getExtensionsString == NULL) getExtensionsString = (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress("wglGetExtensionsStringEXT"); if (getExtensionsString) { const char *extensions = getExtensionsString(dc); if (strstr(extensions, "WGL_ARB_multisample") != NULL || strstr(extensions, "WGL_EXT_multisample") != NULL) hasMultisampling = TRUE; if (strstr(extensions, "WGL_ARB_pixel_format") != NULL) { choosePixelFormat = (PFNWGLCHOOSEPIXELFORMATARBPROC) wglGetProcAddress("wglChoosePixelFormatARB"); getPixelFormatAttribiv = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC) wglGetProcAddress("wglGetPixelFormatAttribivARB"); if (choosePixelFormat == NULL || getPixelFormatAttribiv == NULL) { choosePixelFormat = NULL; getPixelFormatAttribiv = NULL; } } if (choosePixelFormat == NULL && strstr(extensions, "WGL_EXT_pixel_format") != NULL) { choosePixelFormat = (PFNWGLCHOOSEPIXELFORMATARBPROC) wglGetProcAddress("wglChoosePixelFormatEXT"); getPixelFormatAttribiv = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC) wglGetProcAddress("wglGetPixelFormatAttribivEXT"); if (choosePixelFormat == NULL || getPixelFormatAttribiv == NULL) { choosePixelFormat = NULL; getPixelFormatAttribiv = NULL; } } if (createPbuffer == NULL && strstr(extensions, "WGL_ARB_pbuffer") != NULL) { createPbuffer = (PFNWGLCREATEPBUFFERARBPROC) wglGetProcAddress("wglCreatePbufferARB"); destroyPbuffer = (PFNWGLDESTROYPBUFFERARBPROC) wglGetProcAddress("wglDestroyPbufferARB"); getPbufferDC = (PFNWGLGETPBUFFERDCARBPROC) wglGetProcAddress("wglGetPbufferDCARB"); releasePbufferDC = (PFNWGLRELEASEPBUFFERDCARBPROC) wglGetProcAddress("wglReleasePbufferDCARB"); queryPbuffer = (PFNWGLQUERYPBUFFERARBPROC) wglGetProcAddress("wglQueryPbufferARB"); if (createPbuffer == NULL || destroyPbuffer == NULL || getPbufferDC == NULL || releasePbufferDC == NULL || queryPbuffer == NULL) { createPbuffer = NULL; destroyPbuffer = NULL; getPbufferDC = NULL; releasePbufferDC = NULL; queryPbuffer = NULL; } else { hasPbuffer = TRUE; hasARBPbuffer = TRUE; } } if (createPbuffer == NULL && strstr(extensions, "WGL_EXT_pbuffer") != NULL) { createPbuffer = (PFNWGLCREATEPBUFFERARBPROC) wglGetProcAddress("wglCreatePbufferEXT"); destroyPbuffer = (PFNWGLDESTROYPBUFFERARBPROC) wglGetProcAddress("wglDestroyPbufferEXT"); getPbufferDC = (PFNWGLGETPBUFFERDCARBPROC) wglGetProcAddress("wglGetPbufferDCEXT"); releasePbufferDC = (PFNWGLRELEASEPBUFFERDCARBPROC) wglGetProcAddress("wglReleasePbufferDCEXT"); queryPbuffer = (PFNWGLQUERYPBUFFERARBPROC) wglGetProcAddress("wglQueryPbufferEXT"); if (createPbuffer == NULL || destroyPbuffer == NULL || getPbufferDC == NULL || releasePbufferDC == NULL || queryPbuffer == NULL) { createPbuffer = NULL; destroyPbuffer = NULL; getPbufferDC = NULL; releasePbufferDC = NULL; queryPbuffer = NULL; } else { hasPbuffer = TRUE; } } } /* No need to confirm multisampling is in glGetString(GL_EXTENSIONS) * because OpenGL driver is local */ if (test != NULL) { /* cleanup by removing temporary OpenGL window */ wglMakeCurrent(NULL, NULL); wglDeleteContext(rc); ReleaseDC(test, dc); DestroyWindow(test); } } if (togl->MultisampleFlag && !hasMultisampling) { Tcl_SetResult(togl->Interp, TCL_STUPID "multisampling not supported", TCL_STATIC); return 0; } if (togl->PbufferFlag && !hasPbuffer) { Tcl_SetResult(togl->Interp, TCL_STUPID "pbuffers are not supported", TCL_STATIC); return 0; } if (choosePixelFormat == NULL) { PIXELFORMATDESCRIPTOR pfd; /* Don't have the great wglChoosePixelFormatARB() function, so do it * the old way. */ if (togl->MultisampleFlag) { Tcl_SetResult(togl->Interp, TCL_STUPID "multisampling not supported", TCL_STATIC); return 0; } memset(&pfd, 0, sizeof pfd); pfd.nSize = sizeof pfd; pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_SUPPORT_COMPOSITION; if (togl->DoubleFlag) { pfd.dwFlags |= PFD_DOUBLEBUFFER; } if (togl->Stereo == TOGL_STEREO_NATIVE) { pfd.dwFlags |= PFD_STEREO; } pfd.iPixelType = togl->RgbaFlag ? PFD_TYPE_RGBA : PFD_TYPE_COLORINDEX; pfd.cColorBits = togl->RgbaRed + togl->RgbaGreen + togl->RgbaBlue; /* Alpha bitplanes are not supported in the current generic OpenGL * implementation, but may be supported by specific hardware devices. */ pfd.cAlphaBits = togl->AlphaFlag ? togl->AlphaSize : 0; pfd.cAccumBits = togl->AccumFlag ? (togl->AccumRed + togl->AccumGreen + togl->AccumBlue + togl->AccumAlpha) : 0; pfd.cDepthBits = togl->DepthFlag ? togl->DepthSize : 0; pfd.cStencilBits = togl->StencilFlag ? togl->StencilSize : 0; /* Auxiliary buffers are not supported in the current generic OpenGL * implementation, but may be supported by specific hardware devices. */ pfd.cAuxBuffers = togl->AuxNumber; pfd.iLayerType = PFD_MAIN_PLANE; if ((pixelformat = ChoosePixelFormat(togl->tglGLHdc, &pfd)) == 0) { Tcl_SetResult(togl->Interp, TCL_STUPID "couldn't choose pixel format", TCL_STATIC); return 0; } /* double check that we got the stereo format we requested */ if (togl->Stereo == TOGL_STEREO_NATIVE) { DescribePixelFormat(togl->tglGLHdc, pixelformat, sizeof (pfd), &pfd); if ((pfd.dwFlags & PFD_STEREO) == 0) { Tcl_SetResult(togl->Interp, TCL_STUPID "couldn't choose stereo pixel format", TCL_STATIC); return 0; } } return pixelformat; } // We have the new wglChoosePixelFormat!! if (togl->MultisampleFlag && !hasMultisampling) { Tcl_SetResult(togl->Interp, TCL_STUPID "multisampling not supported", TCL_STATIC); return 0; } if (togl->PbufferFlag) attribs[na++] = WGL_DRAW_TO_PBUFFER_ARB; else attribs[na++] = WGL_DRAW_TO_WINDOW_ARB; attribs[na++] = GL_TRUE; attribs[na++] = WGL_SUPPORT_OPENGL_ARB; attribs[na++] = GL_TRUE; attribs[na++] = WGL_PIXEL_TYPE_ARB; if (!togl->RgbaFlag) { attribs[na++] = WGL_TYPE_COLORINDEX_ARB; } else { attribs[na++] = WGL_TYPE_RGBA_ARB; attribs[na++] = WGL_RED_BITS_ARB; attribs[na++] = togl->RgbaRed; attribs[na++] = WGL_GREEN_BITS_ARB; attribs[na++] = togl->RgbaGreen; attribs[na++] = WGL_BLUE_BITS_ARB; attribs[na++] = togl->RgbaBlue; if (togl->AlphaFlag) { attribs[na++] = WGL_ALPHA_BITS_ARB; attribs[na++] = togl->AlphaSize; } } if (togl->DepthFlag) { attribs[na++] = WGL_DEPTH_BITS_ARB; attribs[na++] = togl->DepthSize; } if (togl->DoubleFlag) { attribs[na++] = WGL_DOUBLE_BUFFER_ARB; attribs[na++] = GL_TRUE; } if (togl->StencilFlag) { attribs[na++] = WGL_STENCIL_BITS_ARB; attribs[na++] = togl->StencilSize; } if (togl->AccumFlag) { attribs[na++] = WGL_ACCUM_RED_BITS_ARB; attribs[na++] = togl->AccumRed; attribs[na++] = WGL_ACCUM_GREEN_BITS_ARB; attribs[na++] = togl->AccumGreen; attribs[na++] = WGL_ACCUM_BLUE_BITS_ARB; attribs[na++] = togl->AccumBlue; if (togl->AlphaFlag) { attribs[na++] = WGL_ACCUM_ALPHA_BITS_ARB; attribs[na++] = togl->AccumAlpha; } } if (togl->Stereo == TOGL_STEREO_NATIVE) { attribs[na++] = WGL_STEREO_ARB; attribs[na++] = GL_TRUE; } if (togl->MultisampleFlag) { attribs[na++] = WGL_SAMPLE_BUFFERS_ARB; attribs[na++] = 1; attribs[na++] = WGL_SAMPLES_ARB; attribs[na++] = 2; } if (togl->AuxNumber) { attribs[na++] = WGL_AUX_BUFFERS_ARB; attribs[na++] = togl->AuxNumber; } attribs[na++] = 0; // must be last if (!choosePixelFormat(togl->tglGLHdc, &attribs[0], NULL, 256, formats, &numFormats) || numFormats == 0) { Tcl_SetResult(togl->Interp, TCL_STUPID "couldn't choose pixel format", TCL_STATIC); return 0; } /* * Pick best format */ info = (FBInfo *) malloc(numFormats * sizeof (FBInfo)); for (i = 0; i != numFormats; ++i) { info[i].pixelFormat = formats[i]; getPixelFormatAttribiv(togl->tglGLHdc, formats[i], 0, NUM_FBAttribs, FBAttribs, &info[i].stereo); /* revise attributes so larger is better */ if (!togl->DepthFlag) info[i].depth = -info[i].depth; if (!togl->MultisampleFlag) info[i].samples = -info[i].samples; if (togl->Stereo != TOGL_STEREO_NATIVE) info[i].stereo = -info[i].stereo; } qsort(info, numFormats, sizeof info[0], FBInfoCmp); pixelformat = info[0].pixelFormat; /* double check that we got the stereo format we requested */ if (togl->Stereo == TOGL_STEREO_NATIVE && !info[0].stereo) { Tcl_SetResult(togl->Interp, TCL_STUPID "couldn't choose stereo pixel format", TCL_STATIC); free(info); return 0; } free(info); return pixelformat; }
BOOL CreateGLWindow(char* title, int width, int height, int bit, bool fullScreenFlag) { GLuint PixelFormat; WNDCLASS wc; DWORD dwExStyle; DWORD dwStyle; RECT WindowRect; WindowRect.left = 0; WindowRect.right = width; WindowRect.top = 0; WindowRect.bottom = height; fullscreen = fullScreenFlag; hInstance = GetModuleHandle(NULL); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = L"OpenGL"; RegisterClass(&wc); dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPEDWINDOW; AdjustWindowRectEx(&WindowRect, dwStyle, NULL, dwExStyle); hWnd = CreateWindowEx(dwExStyle, L"OpenGL", (LPCWSTR)title, dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN , 0, 0, WindowRect.right, WindowRect.bottom, NULL, NULL, hInstance, NULL); static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 24, 0,0,0,0,0,0, 0, 0, 0, 0, 32, 0, 0, PFD_MAIN_PLANE, 0, 0,0,0 }; hDC = GetDC(hWnd); PixelFormat = ChoosePixelFormat(hDC, &pfd); SetPixelFormat(hDC, PixelFormat, &pfd); hRC = wglCreateContext(hDC); wglMakeCurrent(hDC, hRC); ShowWindow(hWnd, SW_SHOW); SetForegroundWindow(hWnd); SetFocus(hWnd); //调用opemGL API Reshape(width, height); init(); return TRUE; }
ne_status gfx_sys_init(bool debug) { HWND window; HGLRC dummy = INVALID_HANDLE_VALUE; int fmt = 0, p_fmt = 0; unsigned n_fmt = 0; PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = NULL; PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = NULL; PFNGLDEBUGMESSAGECALLBACKPROC _glDebugMessageCallback = NULL; PFNGLDEBUGMESSAGECALLBACKARBPROC _glDebugMessageCallbackARB = NULL; PFNGLDEBUGMESSAGECALLBACKAMDPROC _glDebugMessageCallbackAMD = NULL; const int pfa[] = { 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, 0, WGL_SAMPLE_BUFFERS_ARB, 0, WGL_SAMPLES_ARB, 1, 0 }; int attr[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 4, WGL_CONTEXT_MINOR_VERSION_ARB, 6, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_CORE_PROFILE_BIT_ARB, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 }; window = GetActiveWindow(); _dc = GetDC(window); fmt = ChoosePixelFormat(_dc, &pfd); if (!fmt) return NE_NO_PIXEL_FMT; if (!SetPixelFormat(_dc, fmt, &pfd)) return NE_NO_PIXEL_FMT; dummy = wglCreateContext(_dc); if (!dummy) return NE_GFX_CTX_CREATE_FAIL; if (!wglMakeCurrent(_dc, dummy)) { wglDeleteContext(dummy); return NE_GFX_CTX_CREATE_FAIL; } wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB"); if (!wglCreateContextAttribsARB) { wglMakeCurrent(NULL, NULL); wglDeleteContext(dummy); return NE_GFX_CTX_CREATE_FAIL; } wglMakeCurrent(NULL, NULL); wglDeleteContext(dummy); wglChoosePixelFormatARB = (PFNWGLCHOOSEPIXELFORMATARBPROC) wglGetProcAddress("wglChoosePixelFormatARB"); if (wglChoosePixelFormatARB) { wglChoosePixelFormatARB(_dc, pfa, NULL, 1, &p_fmt, &n_fmt); SetPixelFormat(_dc, p_fmt, &pfd); } if (debug) attr[8] |= WGL_CONTEXT_DEBUG_BIT_ARB; /*else attr[8] |= GL_KHR_no_error;*/ _ctx = wglCreateContextAttribsARB(_dc, NULL, attr); if (!_ctx) return NE_GFX_CTX_CREATE_FAIL; _load_ctx = wglCreateContextAttribsARB(_dc, _ctx, attr); if (!_load_ctx) { wglDeleteContext(_ctx); return NE_GFX_CTX_CREATE_FAIL; } wglMakeCurrent(_dc, _ctx); if (!gladLoadGL()) return NE_GFX_GL_LOAD_FAIL; if (debug) { _glDebugMessageCallback = (PFNGLDEBUGMESSAGECALLBACKPROC) wglGetProcAddress("glDebugMessageCallback"); _glDebugMessageCallbackARB = (PFNGLDEBUGMESSAGECALLBACKARBPROC) wglGetProcAddress("glDebugMessageCallbackARB"); _glDebugMessageCallbackAMD = (PFNGLDEBUGMESSAGECALLBACKAMDPROC) wglGetProcAddress("glDebugMessageCallbackAMD"); if (_glDebugMessageCallback != NULL) _glDebugMessageCallback(_gfx_dbg_cb, NULL); else if (_glDebugMessageCallbackARB != NULL) _glDebugMessageCallbackARB(_gfx_dbg_cb, NULL); else if (_glDebugMessageCallbackAMD, NULL) _glDebugMessageCallbackAMD(_gfx_dbg_cb_amd, NULL); else OutputDebugString("OpenGL debug callback not available.\n"); if ((_glDebugMessageCallback != NULL) || (_glDebugMessageCallbackARB != NULL)) glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS); } wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT"); return NE_OK; }
bool OpenGLApp::initAPI(){ PixelFormat pf; initPixelFormat(pf); selectPixelFormat(pf); int bpp = pf.alphaBits > 0? 32 : 24; wa = (pf.accumBits > 0); static PIXELFORMATDESCRIPTOR pfd = { sizeof (PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, bpp, 0, 0, 0, 0, 0, 0, 0, 0, pf.accumBits, pf.accumBits / 4, pf.accumBits / 4, pf.accumBits / 4, pf.accumBits / 4, pf.depthBits, pf.stencilBits, pf.alphaBits, PFD_MAIN_PLANE, 0, 0, 0, 0 }; WNDCLASS wincl; HINSTANCE hInst = (HINSTANCE) GetWindowLong(hwnd, GWL_HINSTANCE); wincl.hInstance = hInst; wincl.lpszClassName = "PFrmt"; wincl.lpfnWndProc = PFWinProc; wincl.style = 0; wincl.hIcon = NULL; wincl.hCursor = NULL; wincl.lpszMenuName = NULL; wincl.cbClsExtra = 0; wincl.cbWndExtra = 0; wincl.hbrBackground = NULL; RegisterClass(&wincl); HWND hPFwnd = CreateWindow("PFrmt", "PFormat", WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0, 8, 8, HWND_DESKTOP, NULL, hInst, NULL); initEntryPoints(hPFwnd, pfd); SendMessage(hPFwnd, WM_CLOSE, 0, 0); hdc = GetDC(hwnd); int pixelFormat; float fAttribs[256]; int iAttribs[256] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_RED_BITS_ARB, pf.redBits, WGL_GREEN_BITS_ARB, pf.greenBits, WGL_BLUE_BITS_ARB, pf.blueBits, WGL_ALPHA_BITS_ARB, pf.alphaBits, WGL_DEPTH_BITS_ARB, pf.depthBits, WGL_STENCIL_BITS_ARB, pf.stencilBits, WGL_ACCUM_BITS_ARB, pf.accumBits, }; while (true){ int *iAtt = iAttribs + 20; float *fAtt = fAttribs; if (WGL_ARB_multisample_supported && pf.fsaaLevel > 0){ *iAtt++ = WGL_SAMPLE_BUFFERS_ARB; *iAtt++ = GL_TRUE; *iAtt++ = WGL_SAMPLES_ARB; *iAtt++ = pf.fsaaLevel; } *iAtt++ = 0; *fAtt++ = 0; unsigned int nMatchingPixelFormats; if (!WGL_ARB_pixel_format_supported || !wglChoosePixelFormatARB(hdc, iAttribs, fAttribs, 1, &pixelFormat, &nMatchingPixelFormats) || nMatchingPixelFormats == 0){ if (pf.fsaaLevel > 0){ pf.fsaaLevel -= 2; } else { pixelFormat = ChoosePixelFormat(hdc, &pfd); break; } } else break; } SetPixelFormat(hdc, pixelFormat, &pfd); hglrc = wglCreateContext(hdc); wglMakeCurrent(hdc, hglrc); initExtensions(hdc); if (WGL_ARB_multisample_supported && pf.fsaaLevel > 0){ glEnable(GL_MULTISAMPLE_ARB); } renderer = new OpenGLRenderer(hdc, hglrc); return true; }
// Initialize WGL-specific extensions // static void loadWGLExtensions(void) { PIXELFORMATDESCRIPTOR pfd; HGLRC rc; HDC dc = GetDC(_glfw.win32.helperWindowHandle);; _glfw.wgl.extensionsLoaded = GLFW_TRUE; // NOTE: A dummy context has to be created for opengl32.dll to load the // OpenGL ICD, from which we can then query WGL extensions // NOTE: This code will accept the Microsoft GDI ICD; accelerated context // creation failure occurs during manual pixel format enumeration 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; if (!SetPixelFormat(dc, ChoosePixelFormat(dc, &pfd), &pfd)) { _glfwInputError(GLFW_PLATFORM_ERROR, "WGL: Failed to set pixel format for dummy context"); return; } rc = wglCreateContext(dc); if (!rc) { _glfwInputError(GLFW_PLATFORM_ERROR, "WGL: Failed to create dummy context"); return; } if (!wglMakeCurrent(dc, rc)) { wglDeleteContext(rc); _glfwInputError(GLFW_PLATFORM_ERROR, "WGL: Failed to make dummy context current"); return; } // NOTE: Functions must be loaded first as they're needed to retrieve the // extension string that tells us whether the functions are supported _glfw.wgl.GetExtensionsStringEXT = (PFNWGLGETEXTENSIONSSTRINGEXTPROC) wglGetProcAddress("wglGetExtensionsStringEXT"); _glfw.wgl.GetExtensionsStringARB = (PFNWGLGETEXTENSIONSSTRINGARBPROC) wglGetProcAddress("wglGetExtensionsStringARB"); _glfw.wgl.CreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC) wglGetProcAddress("wglCreateContextAttribsARB"); _glfw.wgl.SwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC) wglGetProcAddress("wglSwapIntervalEXT"); _glfw.wgl.GetPixelFormatAttribivARB = (PFNWGLGETPIXELFORMATATTRIBIVARBPROC) wglGetProcAddress("wglGetPixelFormatAttribivARB"); // NOTE: WGL_ARB_extensions_string and WGL_EXT_extensions_string are not // checked below as we are already using them _glfw.wgl.ARB_multisample = extensionSupportedWGL("WGL_ARB_multisample"); _glfw.wgl.ARB_framebuffer_sRGB = extensionSupportedWGL("WGL_ARB_framebuffer_sRGB"); _glfw.wgl.EXT_framebuffer_sRGB = extensionSupportedWGL("WGL_EXT_framebuffer_sRGB"); _glfw.wgl.ARB_create_context = extensionSupportedWGL("WGL_ARB_create_context"); _glfw.wgl.ARB_create_context_profile = extensionSupportedWGL("WGL_ARB_create_context_profile"); _glfw.wgl.EXT_create_context_es2_profile = extensionSupportedWGL("WGL_EXT_create_context_es2_profile"); _glfw.wgl.ARB_create_context_robustness = extensionSupportedWGL("WGL_ARB_create_context_robustness"); _glfw.wgl.EXT_swap_control = extensionSupportedWGL("WGL_EXT_swap_control"); _glfw.wgl.ARB_pixel_format = extensionSupportedWGL("WGL_ARB_pixel_format"); _glfw.wgl.ARB_context_flush_control = extensionSupportedWGL("WGL_ARB_context_flush_control"); wglMakeCurrent(dc, NULL); wglDeleteContext(rc); }
void entrypoint( void ) { // full screen #ifdef SETRESOLUTION if( ChangeDisplaySettings(&screenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) return; #endif // create window HWND 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; HGLRC tempOpenGLContext; tempOpenGLContext = wglCreateContext(hDC); wglMakeCurrent(hDC, tempOpenGLContext); // create openGL functions for (int i=0; i<NUM_GL_NAMES; i++) glFP[i] = (GenFP)wglGetProcAddress(glnames[i]); HGLRC hRC = wglCreateContextAttribsARB(hDC, NULL, glAttribs); // Remove temporary context and set new one wglMakeCurrent(NULL, NULL); wglDeleteContext(tempOpenGLContext); wglMakeCurrent(hDC, hRC); // init intro intro_init(); // open audio device waveOutOpen(&hWaveOut, WAVE_MAPPER, &wfx, 0, 0, CALLBACK_NULL); // create music block mzk_init(); // prepare and play music block header[0].lpData = (char *)myMuzikBlock[0]; header[1].lpData = (char *)myMuzikBlock[1]; header[0].dwBufferLength = AUDIO_BUFFER_SIZE * MZK_NUMCHANNELS * 2; header[1].dwBufferLength = AUDIO_BUFFER_SIZE * MZK_NUMCHANNELS * 2; waveOutPrepareHeader(hWaveOut, &(header[0]), sizeof(WAVEHDR)); waveOutWrite(hWaveOut, &(header[0]), sizeof(WAVEHDR)); waveOutPrepareHeader(hWaveOut, &(header[1]), sizeof(WAVEHDR)); waveOutWrite(hWaveOut, &(header[1]), sizeof(WAVEHDR)); timer.wType = TIME_SAMPLES; do { MSG msg; PeekMessage(&msg, NULL, 0, 0, PM_REMOVE); ShowCursor(0); waveOutGetPosition(hWaveOut, &timer, sizeof(timer)); DWORD t = timer.u.sample; intro_do(t); //SwapBuffers ( hDC ); wglSwapLayerBuffers( hDC, WGL_SWAP_MAIN_PLANE ); // Try to unprepare header if (waveOutUnprepareHeader(hWaveOut, &(header[nextPlayBlock]), sizeof(WAVEHDR)) != WAVERR_STILLPLAYING) { mzk_prepare_block(myMuzikBlock[nextPlayBlock]); waveOutPrepareHeader(hWaveOut, &(header[nextPlayBlock]), sizeof(WAVEHDR)); waveOutWrite(hWaveOut, &(header[nextPlayBlock]), sizeof(WAVEHDR)); nextPlayBlock = 1 - nextPlayBlock; } } while ( !(GetAsyncKeyState(VK_ESCAPE) || GetAsyncKeyState(VK_F4))); sndPlaySound(0,0); ExitProcess(0); }
// Create the OpenGL or OpenGL ES context // GLFWbool _glfwCreateContextWGL(_GLFWwindow* window, const _GLFWctxconfig* ctxconfig, const _GLFWfbconfig* fbconfig) { int attribs[40]; int pixelFormat; PIXELFORMATDESCRIPTOR pfd; HGLRC share = NULL; if (!_glfw.wgl.extensionsLoaded) loadWGLExtensions(); if (ctxconfig->share) share = ctxconfig->share->context.wgl.handle; window->context.wgl.dc = GetDC(window->win32.handle); if (!window->context.wgl.dc) { _glfwInputError(GLFW_PLATFORM_ERROR, "WGL: Failed to retrieve DC for window"); return GLFW_FALSE; } pixelFormat = choosePixelFormat(window, fbconfig); if (!pixelFormat) return GLFW_FALSE; if (!DescribePixelFormat(window->context.wgl.dc, pixelFormat, sizeof(pfd), &pfd)) { _glfwInputError(GLFW_PLATFORM_ERROR, "WGL: Failed to retrieve PFD for selected pixel format"); return GLFW_FALSE; } if (!SetPixelFormat(window->context.wgl.dc, pixelFormat, &pfd)) { _glfwInputError(GLFW_PLATFORM_ERROR, "WGL: Failed to set selected pixel format"); return GLFW_FALSE; } if (ctxconfig->client == GLFW_OPENGL_API) { if (ctxconfig->forward) { if (!_glfw.wgl.ARB_create_context) { _glfwInputError(GLFW_VERSION_UNAVAILABLE, "WGL: A forward compatible OpenGL context requested but WGL_ARB_create_context is unavailable"); return GLFW_FALSE; } } if (ctxconfig->profile) { if (!_glfw.wgl.ARB_create_context_profile) { _glfwInputError(GLFW_VERSION_UNAVAILABLE, "WGL: OpenGL profile requested but WGL_ARB_create_context_profile is unavailable"); return GLFW_FALSE; } } } else { if (!_glfw.wgl.ARB_create_context || !_glfw.wgl.ARB_create_context_profile || !_glfw.wgl.EXT_create_context_es2_profile) { _glfwInputError(GLFW_API_UNAVAILABLE, "WGL: OpenGL ES requested but WGL_ARB_create_context_es2_profile is unavailable"); return GLFW_FALSE; } } if (_glfw.wgl.ARB_create_context) { int index = 0, mask = 0, flags = 0; if (ctxconfig->client == GLFW_OPENGL_API) { if (ctxconfig->forward) flags |= WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB; if (ctxconfig->profile == GLFW_OPENGL_CORE_PROFILE) mask |= WGL_CONTEXT_CORE_PROFILE_BIT_ARB; else if (ctxconfig->profile == GLFW_OPENGL_COMPAT_PROFILE) mask |= WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB; } else mask |= WGL_CONTEXT_ES2_PROFILE_BIT_EXT; if (ctxconfig->debug) flags |= WGL_CONTEXT_DEBUG_BIT_ARB; if (ctxconfig->noerror) flags |= GL_CONTEXT_FLAG_NO_ERROR_BIT_KHR; if (ctxconfig->robustness) { if (_glfw.wgl.ARB_create_context_robustness) { if (ctxconfig->robustness == GLFW_NO_RESET_NOTIFICATION) { setWGLattrib(WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB, WGL_NO_RESET_NOTIFICATION_ARB); } else if (ctxconfig->robustness == GLFW_LOSE_CONTEXT_ON_RESET) { setWGLattrib(WGL_CONTEXT_RESET_NOTIFICATION_STRATEGY_ARB, WGL_LOSE_CONTEXT_ON_RESET_ARB); } flags |= WGL_CONTEXT_ROBUST_ACCESS_BIT_ARB; } } if (ctxconfig->release) { if (_glfw.wgl.ARB_context_flush_control) { if (ctxconfig->release == GLFW_RELEASE_BEHAVIOR_NONE) { setWGLattrib(WGL_CONTEXT_RELEASE_BEHAVIOR_ARB, WGL_CONTEXT_RELEASE_BEHAVIOR_NONE_ARB); } else if (ctxconfig->release == GLFW_RELEASE_BEHAVIOR_FLUSH) { setWGLattrib(WGL_CONTEXT_RELEASE_BEHAVIOR_ARB, WGL_CONTEXT_RELEASE_BEHAVIOR_FLUSH_ARB); } } } // NOTE: Only request an explicitly versioned context when necessary, as // explicitly requesting version 1.0 does not always return the // highest version supported by the driver if (ctxconfig->major != 1 || ctxconfig->minor != 0) { setWGLattrib(WGL_CONTEXT_MAJOR_VERSION_ARB, ctxconfig->major); setWGLattrib(WGL_CONTEXT_MINOR_VERSION_ARB, ctxconfig->minor); } if (flags) setWGLattrib(WGL_CONTEXT_FLAGS_ARB, flags); if (mask) setWGLattrib(WGL_CONTEXT_PROFILE_MASK_ARB, mask); setWGLattrib(0, 0); window->context.wgl.handle = _glfw.wgl.CreateContextAttribsARB(window->context.wgl.dc, share, attribs); if (!window->context.wgl.handle) { const DWORD error = GetLastError(); if (error == (0xc0070000 | ERROR_INVALID_VERSION_ARB)) { if (ctxconfig->client == GLFW_OPENGL_API) { _glfwInputError(GLFW_VERSION_UNAVAILABLE, "WGL: Driver does not support OpenGL version %i.%i", ctxconfig->major, ctxconfig->minor); } else { _glfwInputError(GLFW_VERSION_UNAVAILABLE, "WGL: Driver does not support OpenGL ES version %i.%i", ctxconfig->major, ctxconfig->minor); } } else if (error == (0xc0070000 | ERROR_INVALID_PROFILE_ARB)) { _glfwInputError(GLFW_VERSION_UNAVAILABLE, "WGL: Driver does not support the requested OpenGL profile"); } else { if (ctxconfig->client == GLFW_OPENGL_API) { _glfwInputError(GLFW_VERSION_UNAVAILABLE, "WGL: Failed to create OpenGL context"); } else { _glfwInputError(GLFW_VERSION_UNAVAILABLE, "WGL: Failed to create OpenGL ES context"); } } return GLFW_FALSE; } } else { window->context.wgl.handle = wglCreateContext(window->context.wgl.dc); if (!window->context.wgl.handle) { _glfwInputError(GLFW_VERSION_UNAVAILABLE, "WGL: Failed to create OpenGL context"); return GLFW_FALSE; } if (share) { if (!wglShareLists(share, window->context.wgl.handle)) { _glfwInputError(GLFW_PLATFORM_ERROR, "WGL: Failed to enable sharing with specified OpenGL context"); return GLFW_FALSE; } } } window->context.makeCurrent = makeContextCurrentWGL; window->context.swapBuffers = swapBuffersWGL; window->context.swapInterval = swapIntervalWGL; window->context.extensionSupported = extensionSupportedWGL; window->context.getProcAddress = getProcAddressWGL; window->context.destroy = destroyContextWGL; return GLFW_TRUE; }
void WglContext::CreateContext(WglContext* shared, unsigned int bitsPerPixel, const ContextSettings& settings) { // Save the creation settings mySettings = settings; // Let's find a suitable pixel format -- first try with antialiasing int bestFormat = 0; if (mySettings.AntialiasingLevel > 0) { // Get the wglChoosePixelFormatARB function (it is an extension) PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = reinterpret_cast<PFNWGLCHOOSEPIXELFORMATARBPROC>(wglGetProcAddress("wglChoosePixelFormatARB")); if (wglChoosePixelFormatARB) { // Define the basic attributes we want for our window int intAttributes[] = { WGL_DRAW_TO_WINDOW_ARB, GL_TRUE, WGL_SUPPORT_OPENGL_ARB, GL_TRUE, WGL_ACCELERATION_ARB, WGL_FULL_ACCELERATION_ARB, WGL_DOUBLE_BUFFER_ARB, GL_TRUE, WGL_SAMPLE_BUFFERS_ARB, (mySettings.AntialiasingLevel ? GL_TRUE : GL_FALSE), WGL_SAMPLES_ARB, mySettings.AntialiasingLevel, 0, 0 }; // Let's check how many formats are supporting our requirements int formats[128]; UINT nbFormats; float floatAttributes[] = {0, 0}; bool isValid = wglChoosePixelFormatARB(myDeviceContext, intAttributes, floatAttributes, sizeof(formats) / sizeof(*formats), formats, &nbFormats) != 0; while ((!isValid || (nbFormats == 0)) && mySettings.AntialiasingLevel > 0) { // Decrease the antialiasing level until we find a valid one mySettings.AntialiasingLevel--; intAttributes[11] = mySettings.AntialiasingLevel; isValid = wglChoosePixelFormatARB(myDeviceContext, intAttributes, floatAttributes, sizeof(formats) / sizeof(*formats), formats, &nbFormats) != 0; } // Get the best format among the returned ones if (isValid && (nbFormats > 0)) { int bestScore = 0xFFFF; for (UINT i = 0; i < nbFormats; ++i) { // Get the current format's attributes PIXELFORMATDESCRIPTOR attributes; attributes.nSize = sizeof(attributes); attributes.nVersion = 1; DescribePixelFormat(myDeviceContext, formats[i], sizeof(attributes), &attributes); // Evaluate the current configuration int color = attributes.cRedBits + attributes.cGreenBits + attributes.cBlueBits + attributes.cAlphaBits; int score = EvaluateFormat(bitsPerPixel, mySettings, color, attributes.cDepthBits, attributes.cStencilBits, mySettings.AntialiasingLevel); // Keep it if it's better than the current best if (score < bestScore) { bestScore = score; bestFormat = formats[i]; } } } } else { // wglChoosePixelFormatARB not supported ; disabling antialiasing Err() << "Antialiasing is not supported ; it will be disabled" << std::endl; mySettings.AntialiasingLevel = 0; } } // Find a pixel format with no antialiasing, if not needed or not supported if (bestFormat == 0) { // Setup a pixel format descriptor from the rendering settings PIXELFORMATDESCRIPTOR descriptor; ZeroMemory(&descriptor, sizeof(descriptor)); descriptor.nSize = sizeof(descriptor); descriptor.nVersion = 1; descriptor.iLayerType = PFD_MAIN_PLANE; descriptor.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; descriptor.iPixelType = PFD_TYPE_RGBA; descriptor.cColorBits = static_cast<BYTE>(bitsPerPixel); descriptor.cDepthBits = static_cast<BYTE>(mySettings.DepthBits); descriptor.cStencilBits = static_cast<BYTE>(mySettings.StencilBits); descriptor.cAlphaBits = bitsPerPixel == 32 ? 8 : 0; // Get the pixel format that best matches our requirements bestFormat = ChoosePixelFormat(myDeviceContext, &descriptor); if (bestFormat == 0) { Err() << "Failed to find a suitable pixel format for device context -- cannot create OpenGL context" << std::endl; return; } } // Extract the depth and stencil bits from the chosen format PIXELFORMATDESCRIPTOR actualFormat; actualFormat.nSize = sizeof(actualFormat); actualFormat.nVersion = 1; DescribePixelFormat(myDeviceContext, bestFormat, sizeof(actualFormat), &actualFormat); mySettings.DepthBits = actualFormat.cDepthBits; mySettings.StencilBits = actualFormat.cStencilBits; // Set the chosen pixel format if (!SetPixelFormat(myDeviceContext, bestFormat, &actualFormat)) { Err() << "Failed to set pixel format for device context -- cannot create OpenGL context" << std::endl; return; } // Get the context to share display lists with HGLRC sharedContext = shared ? shared->myContext : NULL; // Create the OpenGL context -- first try context versions >= 3.0 if it is requested (they require special code) while (!myContext && (mySettings.MajorVersion >= 3)) { PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB = reinterpret_cast<PFNWGLCREATECONTEXTATTRIBSARBPROC>(wglGetProcAddress("wglCreateContextAttribsARB")); if (wglCreateContextAttribsARB) { int attributes[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, mySettings.MajorVersion, WGL_CONTEXT_MINOR_VERSION_ARB, mySettings.MinorVersion, WGL_CONTEXT_PROFILE_MASK_ARB, WGL_CONTEXT_COMPATIBILITY_PROFILE_BIT_ARB, 0, 0 }; myContext = wglCreateContextAttribsARB(myDeviceContext, sharedContext, attributes); } // If we couldn't create the context, lower the version number and try again -- stop at 3.0 // Invalid version numbers will be generated by this algorithm (like 3.9), but we really don't care if (!myContext) { if (mySettings.MinorVersion > 0) { // If the minor version is not 0, we decrease it and try again mySettings.MinorVersion--; } else { // If the minor version is 0, we decrease the major version mySettings.MajorVersion--; mySettings.MinorVersion = 9; } } } // If the OpenGL >= 3.0 context failed or if we don't want one, create a regular OpenGL 1.x/2.x context if (!myContext) { // set the context version to 2.0 (arbitrary) mySettings.MajorVersion = 2; mySettings.MinorVersion = 0; myContext = wglCreateContext(myDeviceContext); if (!myContext) { Err() << "Failed to create an OpenGL context for this window" << std::endl; return; } // Share this context with others if (sharedContext) { // wglShareLists doesn't seem to be thread-safe static Mutex mutex; Lock lock(mutex); if (!wglShareLists(sharedContext, myContext)) Err() << "Failed to share the OpenGL context" << std::endl; } } }
/** * @brief Creates a new glc context for the given drawable and sharing object with the given glc context. * * @param drawable the drawing surface used by glc context * @param contextSharing specifies the context with which to share objects * * @return a new glc context associated with the given drawable and sharing objects with the given context * * @remarks If the new glc context status is GLC_STATUS_SUCCESS (i.e. glc_status(retVal) == GLC_STATUS_SUCCESS), * then the ownership of the given drawable is transfered to the glc context. */ glc_t * _glc_create_( glc_drawable_t * drawable, glc_t * contextSharing ) { assert( drawable != 0 && "Calls glc_create() with an null drawable." ); // @todo drawable_status() // Initializes the glc context with default values glc_t * retVal = (glc_t*)malloc( sizeof(glc_t) ); retVal->context = 0; retVal->contextRefCount = new int; (*retVal->contextRefCount) = 1; retVal->drawable = drawable; #ifdef __SDL2__ SDL_GL_SetAttribute(SDL_GL_STEREO, drawable->stereo); #elif WIN32 // Initializes the pixel format descriptor with the desired format. PIXELFORMATDESCRIPTOR pfd; memset( &pfd, 0, sizeof( PIXELFORMATDESCRIPTOR ) ); pfd.nSize = sizeof( PIXELFORMATDESCRIPTOR ); pfd.nVersion = 1; pfd.dwFlags = PFD_SUPPORT_COMPOSITION | PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cColorBits = drawable->colorSize; pfd.cDepthBits = drawable->depthSize; pfd.cStencilBits = drawable->stencilSize; pfd.iLayerType = PFD_MAIN_PLANE; if ( drawable->stereo ) { pfd.dwFlags |= PFD_STEREO; } #elif __MACOSX__ #error "Non win32 platform not yet supported." #else // POSIX int attributes[64]; int index = 0; attributes[index++] = GLX_RGBA; assert( drawable->colorSize == 32 ); attributes[index++] = GLX_RED_SIZE; attributes[index++] = 8; attributes[index++] = GLX_GREEN_SIZE; attributes[index++] = 8; attributes[index++] = GLX_BLUE_SIZE; attributes[index++] = 8; /*attributes[index++] = GLX_ALPHA_SIZE; attributes[index++] = 8;*/ attributes[index++] = GLX_DOUBLEBUFFER; attributes[index++] = GLX_DEPTH_SIZE; attributes[index++] = drawable->depthSize; attributes[index++] = GLX_STENCIL_SIZE; attributes[index++] = drawable->stencilSize; attributes[index++] = None; #endif #ifdef __SDL2__ // Shares OpenGL objects if (contextSharing) { SDL_GL_SetAttribute(SDL_GL_SHARE_WITH_CURRENT_CONTEXT, (int)(contextSharing->context)); } // else nothing to do // Create an OpenGL context associated with the window. SDL_GLContext context = SDL_GL_CreateContext(drawable->window); if ( context == NULL ) { fprintf( stderr, "In glc_create(), SDL_GL_CreateContext() fails (%s).", SDL_GetError() ); return retVal; } else { retVal->context = context; } #elif WIN32 // Chooses and sets the closest available pixel format. int iPixelFormat; BOOL bResult; iPixelFormat = ChoosePixelFormat( drawable->dc, &pfd ); if ( iPixelFormat == 0 ) { fprintf( stderr, "In glc_create(), ChoosePixelFormat() fails." ); return retVal; } bResult = SetPixelFormat( drawable->dc, iPixelFormat, &pfd ); if ( bResult == FALSE ) { fprintf( stderr, "In glc_create(), SetPixelFormat() fails." ); return retVal; } // Creates the OpenGL rendering context. GLC_GLRC_HANDLE context = wglCreateContext( drawable->dc ); if ( context == NULL ) { fprintf( stderr, "In glc_create(), wglCreateContext() fails." ); return retVal; } else { retVal->context = context; } // Shares OpenGL objects if ( contextSharing ) { BOOL success = wglShareLists( context, contextSharing->context ); if ( success != TRUE ) { fprintf( stderr, "In glc_create(), wglShareLists() fails." ); } // else nothing to do } // else nothing to do #else // Checks for supports the GLX extension if ( !glXQueryExtension( drawable->display, 0, 0 ) ) { // no glx extension fprintf( stderr, "In glc_create, GLX extension is missing.\n" ); return retVal; } // Chooses and sets the closest available visual. XVisualInfo * visual = glXChooseVisual( drawable->display, drawable->screen, &attributes[0] ); if ( !visual ) { fprintf( stderr, "In glc_create, Unable to choose a visual.\n" ); return retVal; } // Creates the OpenGL rendering context and // shares OpenGL objects (if requested). GLC_GLRC_HANDLE context; if ( contextSharing ) { context = glXCreateContext( drawable->display, visual, contextSharing->context, GL_TRUE ); } else { context = glXCreateContext( drawable->display, visual, None, GL_TRUE ); } if ( context == NULL ) { fprintf( stderr, "In glc_create(), glxCreateContext() fails." ); } else { retVal->context = context; } #endif return retVal; }
LRESULT CALLBACK csGraphics2DOpenGL::DummyWindow (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { switch(message) { case WM_CREATE: { DummyWndInfo* dwi = (DummyWndInfo*)(LPCREATESTRUCT(lParam)->lpCreateParams); HDC hDC = GetDC (hWnd); int acceleration = dwi->this_->config->GetBool ( "Video.OpenGL.FullAcceleration", true) ? WGL_FULL_ACCELERATION_ARB : WGL_GENERIC_ACCELERATION_ARB; csGLPixelFormatPicker& picker = *dwi->picker; int pixelFormat = dwi->this_->FindPixelFormatGDI (hDC, picker); PIXELFORMATDESCRIPTOR pfd; if (DescribePixelFormat (hDC, pixelFormat, sizeof(PIXELFORMATDESCRIPTOR), &pfd) == 0) SystemFatalError (L"DescribePixelFormat failed."); if (SetPixelFormat (hDC, pixelFormat, 0) != TRUE) { HRESULT spfErr = (HRESULT)GetLastError(); SystemFatalError (L"SetPixelFormat failed.", spfErr); } HGLRC hGLRC = wglCreateContext (hDC); wglMakeCurrent (hDC, hGLRC); csGLExtensionManager& ext = dwi->this_->ext; ext.Open(); dwi->this_->detector.DoDetection (hWnd, hDC); dwi->this_->OpenDriverDB ("preinit"); ext.InitWGL_ARB_pixel_format (hDC); if (ext.CS_WGL_ARB_pixel_format) { unsigned int numFormats = 0; int iAttributes[26]; float fAttributes[] = {0.0f, 0.0f}; GLPixelFormat format; memcpy (format, dwi->chosenFormat, sizeof (GLPixelFormat)); do { int index = 0; iAttributes[index++] = WGL_DRAW_TO_WINDOW_ARB; iAttributes[index++] = GL_TRUE; iAttributes[index++] = WGL_SUPPORT_OPENGL_ARB; iAttributes[index++] = GL_TRUE; iAttributes[index++] = WGL_ACCELERATION_ARB; iAttributes[index++] = acceleration; iAttributes[index++] = WGL_DOUBLE_BUFFER_ARB; iAttributes[index++] = GL_TRUE; iAttributes[index++] = WGL_SAMPLE_BUFFERS_ARB; iAttributes[index++] = (format[glpfvMultiSamples] != 0) ? 1 : 0; iAttributes[index++] = WGL_SAMPLES_ARB; iAttributes[index++] = format[glpfvMultiSamples]; iAttributes[index++] = WGL_COLOR_BITS_ARB; iAttributes[index++] = pfd.cColorBits; iAttributes[index++] = WGL_ALPHA_BITS_ARB; iAttributes[index++] = pfd.cAlphaBits; iAttributes[index++] = WGL_DEPTH_BITS_ARB; iAttributes[index++] = pfd.cDepthBits; iAttributes[index++] = WGL_STENCIL_BITS_ARB; iAttributes[index++] = pfd.cStencilBits; iAttributes[index++] = WGL_ACCUM_BITS_ARB; iAttributes[index++] = pfd.cAccumBits; iAttributes[index++] = WGL_ACCUM_ALPHA_BITS_ARB; iAttributes[index++] = pfd.cAccumAlphaBits; iAttributes[index++] = 0; iAttributes[index++] = 0; if ((ext.wglChoosePixelFormatARB (hDC, iAttributes, fAttributes, 1, &dwi->pixelFormat, &numFormats) == GL_TRUE) && (numFormats != 0)) { int queriedAttrs[] = {WGL_SAMPLES_ARB}; const int queriedAttrNum = sizeof(queriedAttrs) / sizeof(int); int attrValues[queriedAttrNum]; if (ext.wglGetPixelFormatAttribivARB (hDC, dwi->pixelFormat, 0, queriedAttrNum, queriedAttrs, attrValues) == GL_TRUE) { (*dwi->chosenFormat)[glpfvMultiSamples] = attrValues[0]; break; } } } while (picker.GetNextFormat (format)); } dwi->this_->driverdb.Close (); wglMakeCurrent (hDC, 0); wglDeleteContext (hGLRC); ReleaseDC (hWnd, hDC); } break; } return DefWindowProc (hWnd, message, wParam, lParam); }
inline void MainLoop::InitOGL() { #ifdef MW_OS_WINDOWS int border_size, top_border_size, bottom_border_size; static const char* WINDOW_NAME= "MW"; window_class.cbSize = sizeof(WNDCLASSEX); window_class.style = CS_OWNDC; window_class.lpfnWndProc = WindowProc; window_class.cbClsExtra = 0; window_class.cbWndExtra = 0; window_class.hInstance = 0; window_class.hIcon = LoadIcon( 0 , IDI_APPLICATION); window_class.hCursor = LoadCursor(NULL, IDC_ARROW); window_class.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); window_class.lpszMenuName = NULL; window_class.lpszClassName = WINDOW_NAME; window_class.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if ( ! RegisterClassEx( &window_class ) ) goto display_error; border_size= GetSystemMetrics(SM_CXFIXEDFRAME); bottom_border_size= GetSystemMetrics(SM_CYFIXEDFRAME); top_border_size= bottom_border_size + GetSystemMetrics(SM_CYCAPTION); border_x= border_size * 2; border_y= top_border_size + bottom_border_size; hwnd = CreateWindowEx(0, WINDOW_NAME, WINDOW_NAME, /*WS_OVERLAPPED|WS_CAPTION|WS_MINIMIZEBOX|WS_SYSMENU*/WS_OVERLAPPEDWINDOW, 0, 0, screen_x + border_size * 2, screen_y + top_border_size + bottom_border_size, NULL, NULL, /*h_instance*/0, NULL); if ( ! hwnd ) goto display_error; ShowWindow( hwnd, SW_SHOWNORMAL ); hdc= GetDC( hwnd ); wglMakeCurrent( 0, 0 ); PIXELFORMATDESCRIPTOR pfd; int format; ZeroMemory( &pfd, 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= 32; pfd.cStencilBits= 8; pfd.iLayerType= PFD_MAIN_PLANE; format= ChoosePixelFormat(hdc, &pfd); SetPixelFormat(hdc, format, &pfd); hrc= wglCreateContext( hdc ); wglMakeCurrent( hdc, hrc ); PFNWGLCREATECONTEXTATTRIBSARBPROC wglCreateContextAttribsARB= NULL; wglCreateContextAttribsARB = (PFNWGLCREATECONTEXTATTRIBSARBPROC)wglGetProcAddress("wglCreateContextAttribsARB"); wglMakeCurrent( NULL, NULL ); wglDeleteContext( hrc ); int attribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, 3, WGL_CONTEXT_MINOR_VERSION_ARB, 3, WGL_CONTEXT_FLAGS_ARB, /* WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB*/ 0x0002, /*WGL_CONTEXT_PROFILE_MASK_ARB*/0x9126, /*WGL_CONTEXT_CORE_PROFILE_BIT_ARB*/0x00000001, 0 }; hrc= wglCreateContextAttribsARB( hdc, 0, attribs ); wglMakeCurrent( hdc, hrc ); //Tun off vsync /*PFNWGLSWAPINTERVALEXTPROC wglSwapInterval= (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress( "wglSwapIntervalEXT" ); wglSwapInterval(0); */ #else int dblBuf[] = {GLX_RGBA, GLX_DEPTH_SIZE, 24, GLX_DOUBLEBUFFER, None}; XVisualInfo *vi; Colormap cmap; XSetWindowAttributes swa; GLXContext cx; int dummy; dpy = XOpenDisplay(NULL); if (dpy == NULL ) goto display_error; if(!glXQueryExtension(dpy, &dummy, &dummy)) goto display_error; if ( ( vi= glXChooseVisual(dpy, DefaultScreen(dpy), dblBuf) ) == NULL) goto display_error; cx = glXCreateContext(dpy, vi, /* no shared dlists */ None, /* direct rendering if possible */ GL_TRUE ); if (cx == NULL) goto display_error; cmap = XCreateColormap(dpy, RootWindow(dpy, vi->screen), vi->visual, AllocNone); swa.colormap = cmap; swa.border_pixel = 0; swa.event_mask = KeyPressMask | ExposureMask | ButtonPressMask | StructureNotifyMask; win = XCreateWindow(dpy, RootWindow(dpy, vi->screen), 0, 0, screen_x, screen_y, 0, vi->depth, InputOutput, vi->visual, CWBorderPixel | CWColormap | CWEventMask, &swa); XSetStandardProperties(dpy, win, "MW", "MW", None, NULL, 0, NULL); glXMakeCurrent(dpy, win, cx); XMapWindow(dpy, win); #endif int ver[2]; glGetIntegerv( GL_MAJOR_VERSION, ver ); glGetIntegerv( GL_MINOR_VERSION, ver + 1 ); if( ver[0] * 10 + ver[1] < MW_GL_VERSION ) exit(1025); return; display_error: exit(1024); }
PRBool nsGLPbufferWGL::Init(nsCanvasRenderingContextGLPrivate *priv) { // XXX lookup SYSTEM32 path! char *opengl32 = "C:\\WINDOWS\\SYSTEM32\\OPENGL32.DLL"; if (!gWGLWrap.OpenLibrary(opengl32)) return PR_FALSE; gWGLWrap.SetLookupFunc((LibrarySymbolLoader::PlatformLookupFunction) wglGetProcAddress); mPriv = priv; WNDCLASS wc; PIXELFORMATDESCRIPTOR pfd; if (!GetClassInfo(GetModuleHandle(NULL), "GLEW", &wc)) { ZeroMemory(&wc, sizeof(WNDCLASS)); wc.hInstance = GetModuleHandle(NULL); wc.lpfnWndProc = DefWindowProc; wc.lpszClassName = "GLEW"; if (!RegisterClass(&wc)) { LogMessage(NS_LITERAL_CSTRING("Canvas 3D: RegisterClass failed")); return PR_FALSE; } } // create window mGlewWindow = CreateWindow("GLEW", "GLEW", 0, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, GetModuleHandle(NULL), NULL); if (!mGlewWindow) { LogMessage(NS_LITERAL_CSTRING("Canvas 3D: CreateWindow failed")); return PR_FALSE; } // get the device context mGlewDC = GetDC(mGlewWindow); if (!mGlewDC) { LogMessage(NS_LITERAL_CSTRING("Canvas 3D: GetDC failed")); return PR_FALSE; } // find default pixel format ZeroMemory(&pfd, sizeof(PIXELFORMATDESCRIPTOR)); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL; int pixelformat = ChoosePixelFormat(mGlewDC, &pfd); // set the pixel format for the dc if (!SetPixelFormat(mGlewDC, pixelformat, &pfd)) { LogMessage(NS_LITERAL_CSTRING("Canvas 3D: SetPixelFormat failed")); return PR_FALSE; } // create rendering context mGlewWglContext = wglCreateContext(mGlewDC); if (!mGlewWglContext) { LogMessage(NS_LITERAL_CSTRING("Canvas 3D: wglCreateContext failed")); return PR_FALSE; } if (!wglMakeCurrent(mGlewDC, (HGLRC) mGlewWglContext)) { LogMessage(NS_LITERAL_CSTRING("Canvas 3D: wglMakeCurrent failed")); return PR_FALSE; } // grab all the wgl extension pieces that we couldn't grab before // we had a context if (!gWGLWrap.Init()) return PR_FALSE; // XXX look up system32 dir if (!mGLWrap.OpenLibrary(opengl32)) { LogMessage(NS_LITERAL_CSTRING("Canvas 3D: Failed to open opengl32.dll (only looked in c:\\windows\\system32, fixme)")); return PR_FALSE; } mGLWrap.SetLookupFunc((LibrarySymbolLoader::PlatformLookupFunction) wglGetProcAddress); if (!mGLWrap.Init(GLES20Wrap::TRY_NATIVE_GL)) { LogMessage(NS_LITERAL_CSTRING("Canvas 3D: GLWrap init failed")); return PR_FALSE; } return PR_TRUE; }
bool CWGLManager::initialize(const SIrrlichtCreationParameters& params, const SExposedVideoData& videodata) { // store params, videoData is set later as it would be overwritten else Params=params; // Create a window to test antialiasing support const fschar_t* ClassName = __TEXT("CWGLManager"); HINSTANCE lhInstance = GetModuleHandle(0); // Register Class WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = (WNDPROC)DefWindowProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = lhInstance; wcex.hIcon = NULL; wcex.hCursor = LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wcex.lpszMenuName = 0; wcex.lpszClassName = ClassName; wcex.hIconSm = 0; wcex.hIcon = 0; RegisterClassEx(&wcex); RECT clientSize; clientSize.top = 0; clientSize.left = 0; clientSize.right = Params.WindowSize.Width; clientSize.bottom = Params.WindowSize.Height; DWORD style = WS_POPUP; if (!Params.Fullscreen) style = WS_SYSMENU | WS_BORDER | WS_CAPTION | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; AdjustWindowRect(&clientSize, style, FALSE); const s32 realWidth = clientSize.right - clientSize.left; const s32 realHeight = clientSize.bottom - clientSize.top; const s32 windowLeft = (GetSystemMetrics(SM_CXSCREEN) - realWidth) / 2; const s32 windowTop = (GetSystemMetrics(SM_CYSCREEN) - realHeight) / 2; HWND temporary_wnd=CreateWindow(ClassName, __TEXT(""), style, windowLeft, windowTop, realWidth, realHeight, NULL, NULL, lhInstance, NULL); if (!temporary_wnd) { os::Printer::log("Cannot create a temporary window.", ELL_ERROR); UnregisterClass(ClassName, lhInstance); return false; } HDC HDc = GetDC(temporary_wnd); // Set up pixel format descriptor with desired parameters PIXELFORMATDESCRIPTOR tmp_pfd = { sizeof(PIXELFORMATDESCRIPTOR), // Size Of This Pixel Format Descriptor 1, // Version Number (DWORD)(PFD_DRAW_TO_WINDOW | // Format Must Support Window PFD_SUPPORT_OPENGL | // Format Must Support OpenGL (Params.Doublebuffer?PFD_DOUBLEBUFFER:0) | // Must Support Double Buffering (Params.Stereobuffer?PFD_STEREO:0)), // Must Support Stereo Buffer PFD_TYPE_RGBA, // Request An RGBA Format Params.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 Params.ZBufferBits, // Z-Buffer (Depth Buffer) BYTE(Params.Stencilbuffer ? 1 : 0), // Stencil Buffer Depth 0, // No Auxiliary Buffer PFD_MAIN_PLANE, // Main Drawing Layer 0, // Reserved 0, 0, 0 // Layer Masks Ignored }; pfd=tmp_pfd; for (u32 i=0; i<6; ++i) { if (i == 1) { if (Params.Stencilbuffer) { os::Printer::log("Cannot create a GL device with stencil buffer, disabling stencil shadows.", ELL_WARNING); Params.Stencilbuffer = false; pfd.cStencilBits = 0; } else continue; } else if (i == 2) { pfd.cDepthBits = 24; } else if (i == 3) { if (Params.Bits!=16) pfd.cDepthBits = 16; else continue; } else if (i == 4) { // try single buffer if (Params.Doublebuffer) pfd.dwFlags &= ~PFD_DOUBLEBUFFER; else continue; } else if (i == 5) { os::Printer::log("Cannot create a GL device context", "No suitable format for temporary window.", ELL_ERROR); ReleaseDC(temporary_wnd, HDc); DestroyWindow(temporary_wnd); UnregisterClass(ClassName, lhInstance); return false; } // choose pixelformat PixelFormat = ChoosePixelFormat(HDc, &pfd); if (PixelFormat) break; } SetPixelFormat(HDc, PixelFormat, &pfd); os::Printer::log("Temporary context"); HGLRC hrc=wglCreateContext(HDc); if (!hrc) { os::Printer::log("Cannot create a temporary GL rendering context.", ELL_ERROR); ReleaseDC(temporary_wnd, HDc); DestroyWindow(temporary_wnd); UnregisterClass(ClassName, lhInstance); return false; } CurrentContext.OpenGLWin32.HDc = HDc; CurrentContext.OpenGLWin32.HRc = hrc; CurrentContext.OpenGLWin32.HWnd = temporary_wnd; if (!activateContext(CurrentContext)) { os::Printer::log("Cannot activate a temporary GL rendering context.", ELL_ERROR); wglDeleteContext(hrc); ReleaseDC(temporary_wnd, HDc); DestroyWindow(temporary_wnd); UnregisterClass(ClassName, lhInstance); return false; } core::stringc wglExtensions; #ifdef WGL_ARB_extensions_string PFNWGLGETEXTENSIONSSTRINGARBPROC irrGetExtensionsString = (PFNWGLGETEXTENSIONSSTRINGARBPROC)wglGetProcAddress("wglGetExtensionsStringARB"); if (irrGetExtensionsString) wglExtensions = irrGetExtensionsString(HDc); #elif defined(WGL_EXT_extensions_string) PFNWGLGETEXTENSIONSSTRINGEXTPROC irrGetExtensionsString = (PFNWGLGETEXTENSIONSSTRINGEXTPROC)wglGetProcAddress("wglGetExtensionsStringEXT"); if (irrGetExtensionsString) wglExtensions = irrGetExtensionsString(HDc); #endif const bool pixel_format_supported = (wglExtensions.find("WGL_ARB_pixel_format") != -1); const bool multi_sample_supported = ((wglExtensions.find("WGL_ARB_multisample") != -1) || (wglExtensions.find("WGL_EXT_multisample") != -1) || (wglExtensions.find("WGL_3DFX_multisample") != -1) ); #ifdef _DEBUG os::Printer::log("WGL_extensions", wglExtensions); #endif #ifdef WGL_ARB_pixel_format PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormat_ARB = (PFNWGLCHOOSEPIXELFORMATARBPROC)wglGetProcAddress("wglChoosePixelFormatARB"); if (pixel_format_supported && wglChoosePixelFormat_ARB) { // This value determines the number of samples used for antialiasing // My experience is that 8 does not show a big // improvement over 4, but 4 shows a big improvement // over 2. if (Params.AntiAlias > 32) Params.AntiAlias = 32; f32 fAttributes[] = {0.0, 0.0}; s32 iAttributes[] = { WGL_DRAW_TO_WINDOW_ARB,1, WGL_SUPPORT_OPENGL_ARB,1, WGL_ACCELERATION_ARB,WGL_FULL_ACCELERATION_ARB, WGL_COLOR_BITS_ARB,(Params.Bits==32) ? 24 : 15, WGL_ALPHA_BITS_ARB,(Params.Bits==32) ? 8 : 1, WGL_DEPTH_BITS_ARB,Params.ZBufferBits, // 10,11 WGL_STENCIL_BITS_ARB,Params.Stencilbuffer ? 1 : 0, WGL_DOUBLE_BUFFER_ARB,Params.Doublebuffer ? 1 : 0, WGL_STEREO_ARB,Params.Stereobuffer ? 1 : 0, WGL_PIXEL_TYPE_ARB, WGL_TYPE_RGBA_ARB, #ifdef WGL_ARB_multisample WGL_SAMPLES_ARB,Params.AntiAlias, // 20,21 WGL_SAMPLE_BUFFERS_ARB, 1, #elif defined(WGL_EXT_multisample) WGL_SAMPLES_EXT,AntiAlias, // 20,21 WGL_SAMPLE_BUFFERS_EXT, 1, #elif defined(WGL_3DFX_multisample) WGL_SAMPLES_3DFX,AntiAlias, // 20,21 WGL_SAMPLE_BUFFERS_3DFX, 1, #endif #ifdef WGL_ARB_framebuffer_sRGB WGL_FRAMEBUFFER_SRGB_CAPABLE_ARB, Params.HandleSRGB ? 1:0, #elif defined(WGL_EXT_framebuffer_sRGB) WGL_FRAMEBUFFER_SRGB_CAPABLE_EXT, Params.HandleSRGB ? 1:0, #endif // WGL_DEPTH_FLOAT_EXT, 1, 0,0,0,0 }; int iAttrSize = sizeof(iAttributes)/sizeof(int); const bool framebuffer_srgb_supported = ((wglExtensions.find("WGL_ARB_framebuffer_sRGB") != -1) || (wglExtensions.find("WGL_EXT_framebuffer_sRGB") != -1)); if (!framebuffer_srgb_supported) { memmove(&iAttributes[24],&iAttributes[26],sizeof(int)*(iAttrSize-26)); iAttrSize -= 2; } if (!multi_sample_supported) { memmove(&iAttributes[20],&iAttributes[24],sizeof(int)*(iAttrSize-24)); iAttrSize -= 4; } s32 rv=0; // Try to get an acceptable pixel format do { int pixelFormat=0; UINT numFormats=0; const BOOL valid = wglChoosePixelFormat_ARB(HDc,iAttributes,fAttributes,1,&pixelFormat,&numFormats); if (valid && numFormats) rv = pixelFormat; else iAttributes[21] -= 1; } while(rv==0 && iAttributes[21]>1); if (rv) { PixelFormat=rv; Params.AntiAlias=iAttributes[21]; } } else #endif Params.AntiAlias=0; // this only terminates the temporary HRc destroyContext(); destroySurface(); terminate(); DestroyWindow(temporary_wnd); UnregisterClass(ClassName, lhInstance); // now get new window CurrentContext.OpenGLWin32.HWnd=videodata.OpenGLWin32.HWnd; // get hdc if (!(CurrentContext.OpenGLWin32.HDc=GetDC((HWND)videodata.OpenGLWin32.HWnd))) { os::Printer::log("Cannot create a GL device context.", ELL_ERROR); return false; } if (!PrimaryContext.OpenGLWin32.HWnd) { PrimaryContext.OpenGLWin32.HWnd=CurrentContext.OpenGLWin32.HWnd; PrimaryContext.OpenGLWin32.HDc=CurrentContext.OpenGLWin32.HDc; } return true; }
static int window_init(WININFO *info, bool use_custom_pixel_format = false, int custom_pixel_format = 0) { unsigned int PixelFormat; DWORD dwExStyle, dwStyle; DEVMODE dmScreenSettings; RECT rec; WNDCLASS wc; ZeroMemory(&wc, sizeof(WNDCLASS)); wc.style = CS_OWNDC | CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WndProc; wc.hInstance = info->hInstance; wc.lpszClassName = info->wndclass; if (!RegisterClass(&wc)) return(0); if (info->full) { dmScreenSettings.dmSize = sizeof(DEVMODE); dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; dmScreenSettings.dmBitsPerPel = 24; dmScreenSettings.dmPelsWidth = XRES; dmScreenSettings.dmPelsHeight = YRES; if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) return(0); dwExStyle = WS_EX_APPWINDOW; dwStyle = WS_VISIBLE | WS_POPUP;// | WS_CLIPSIBLINGS | WS_CLIPCHILDREN; ShowCursor(0); } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_VISIBLE | WS_CAPTION | WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_SYSMENU; } rec.left = 0; rec.top = 0; rec.right = XRES; rec.bottom = YRES; AdjustWindowRect(&rec, dwStyle, 0); windowRect.left = 0; windowRect.top = 0; windowRect.right = XRES; windowRect.bottom = YRES; info->hWnd = CreateWindowEx(dwExStyle, wc.lpszClassName, "live coding", dwStyle, (GetSystemMetrics(SM_CXSCREEN) - rec.right + rec.left) >> 1, (GetSystemMetrics(SM_CYSCREEN) - rec.bottom + rec.top) >> 1, rec.right - rec.left, rec.bottom - rec.top, 0, 0, info->hInstance, 0); if (!info->hWnd) return(0); if (!(info->hDC = GetDC(info->hWnd))) return(0); if (!use_custom_pixel_format) { if (!(PixelFormat = ChoosePixelFormat(info->hDC, &pfd))) return(0); if (!SetPixelFormat(info->hDC, PixelFormat, &pfd)) return(0); } else { if (!SetPixelFormat(info->hDC, custom_pixel_format, &pfd)) return(0); } if (!(info->hRC = wglCreateContext(info->hDC))) return(0); if (!wglMakeCurrent(info->hDC, info->hRC)) return(0); return(1); }
//=========================================================================== bool cViewport::update(bool resizeOnly) { // Clean up the old rendering context if necessary if ((resizeOnly == false) && m_glDC) cleanup(); // declare variables int formatIndex; // viewport is not yet enabled m_enabled = false; // gl display not yet ready m_glReady = false; // check display handle if (m_winHandle == NULL) { return (false); } // Find out the rectangle to which we should be rendering // If we're using the entire window... if (m_forceRenderArea.left == -1) { if (GetWindowRect(m_winHandle, &m_activeRenderingArea) == 0) { return (false); } // Convert from screen to window coordinates m_activeRenderingArea.right -= m_activeRenderingArea.left; m_activeRenderingArea.left = 0; m_activeRenderingArea.bottom -= m_activeRenderingArea.top; m_activeRenderingArea.top = 0; // Convert from y-axis-down to y-axis-up, since that's how we store // our rendering area. int height = m_activeRenderingArea.bottom; m_activeRenderingArea.top = height - m_activeRenderingArea.top; m_activeRenderingArea.bottom = height - m_activeRenderingArea.bottom; } // Otherwise use whatever rectangle the user wants us to use... else { m_activeRenderingArea = m_forceRenderArea; } // retrieve handle of the display device context m_glDC = ::GetDC(m_winHandle); if (m_glDC == 0) { return(false); } if (resizeOnly == false) { // find pixel format supported by the device context. If error return false. formatIndex = ChoosePixelFormat(m_glDC, &m_pixelFormat); if (formatIndex == 0) { return(false); } // sets the specified device context's pixel format. If error return false if (!SetPixelFormat(m_glDC, formatIndex, &m_pixelFormat)) { return(false); } formatIndex = GetPixelFormat (m_glDC); DescribePixelFormat (m_glDC, formatIndex, sizeof(PIXELFORMATDESCRIPTOR), &m_pixelFormat); // if stereo was enabled but can not be displayed, switch over to mono. if (((m_pixelFormat.dwFlags & PFD_STEREO) == 0) && m_stereoEnabled) { m_stereoEnabled = false; } // create display context m_glContext = wglCreateContext(m_glDC); if (m_glContext == 0) { return(false); } wglMakeCurrent(m_glDC, m_glContext); } // OpenGL is now ready for rendering m_glReady = true; // store this current view as the last active one lastActiveViewport = this; // enable viewport m_enabled = true; if (resizeOnly == false) onDisplayReset(); // return success return(true); }
bool COpenGLControl::initOpenGL(HINSTANCE hInstance, HWND* a_hWnd, int iMajorVersion, int iMinorVersion, void (*a_initScene)(LPVOID), void (*a_renderScene)(LPVOID), void(*a_releaseScene)(LPVOID), LPVOID lpParam) { if(!initGLEW(hInstance))return false; hWnd = a_hWnd; hDC = GetDC(*hWnd); bool bError = false; PIXELFORMATDESCRIPTOR pfd; if(iMajorVersion <= 2) { memset(&pfd, 0, sizeof(PIXELFORMATDESCRIPTOR)); pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; 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 iPixelFormat = ChoosePixelFormat(hDC, &pfd); if (iPixelFormat == 0)return false; if(!SetPixelFormat(hDC, iPixelFormat, &pfd))return false; // Create the old style context (OpenGL 2.1 and before) hRC = wglCreateContext(hDC); if(hRC)wglMakeCurrent(hDC, hRC); else bError = true; } else if(WGLEW_ARB_create_context && WGLEW_ARB_pixel_format) { const int iPixelFormatAttribList[] = { 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, 24, WGL_STENCIL_BITS_ARB, 8, 0 // End of attributes list }; int iContextAttribs[] = { WGL_CONTEXT_MAJOR_VERSION_ARB, iMajorVersion, WGL_CONTEXT_MINOR_VERSION_ARB, iMinorVersion, WGL_CONTEXT_FLAGS_ARB, WGL_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB, 0 // End of attributes list }; int iPixelFormat, iNumFormats; wglChoosePixelFormatARB(hDC, iPixelFormatAttribList, NULL, 1, &iPixelFormat, (UINT*)&iNumFormats); // PFD seems to be only redundant parameter now if(!SetPixelFormat(hDC, iPixelFormat, &pfd))return false; hRC = wglCreateContextAttribsARB(hDC, 0, iContextAttribs); // If everything went OK if(hRC) wglMakeCurrent(hDC, hRC); else bError = true; } else bError = true; if(bError) { // Generate error messages char sErrorMessage[255], sErrorTitle[255]; sprintf(sErrorMessage, "OpenGL %d.%d is not supported! Please download latest GPU drivers!", iMajorVersion, iMinorVersion); sprintf(sErrorTitle, "OpenGL %d.%d Not Supported", iMajorVersion, iMinorVersion); MessageBox(*hWnd, sErrorMessage, sErrorTitle, MB_ICONINFORMATION); return false; } renderScene = a_renderScene; initScene = a_initScene; releaseScene = a_releaseScene; if(initScene != NULL)initScene(lpParam); return true; }
static void _glitz_wgl_create_root_context (glitz_wgl_screen_info_t *screen_info) { WNDCLASSEX wcl; ATOM klass; static PIXELFORMATDESCRIPTOR pfd = { sizeof (PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL, PFD_TYPE_RGBA, 32, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; int pixel_format; wcl.cbSize = sizeof (wcl); wcl.style = 0; wcl.lpfnWndProc = DefWindowProc; wcl.cbClsExtra = 0; wcl.cbWndExtra = 0; wcl.hInstance = GetModuleHandle (NULL); wcl.hIcon = NULL; wcl.hCursor = LoadCursor (NULL, IDC_ARROW); wcl.hbrBackground = NULL; wcl.lpszMenuName = NULL; wcl.lpszClassName = "glitz-wgl-root-window-class"; wcl.hIconSm = NULL; klass = RegisterClassEx (&wcl); if (!klass) { exit (1); } screen_info->root_window = CreateWindowEx (0, (LPCTSTR) (DWORD) klass, "glitz-wgl-root-window", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, 100, 100, GetDesktopWindow (), NULL, GetModuleHandle (NULL), NULL); screen_info->root_dc = GetDC (screen_info->root_window); pixel_format = ChoosePixelFormat (screen_info->root_dc, &pfd); if (pixel_format != 0) { SetPixelFormat (screen_info->root_dc, pixel_format, &pfd); screen_info->root_context = wglCreateContext (screen_info->root_dc); wglMakeCurrent (screen_info->root_dc, screen_info->root_context); } else { screen_info->root_context = NULL; } }