static qboolean GLimp_SetFSMode( int *width, int *height ) { DEVMODE dm; HRESULT hr; EnumDisplaySettings (NULL, ENUM_CURRENT_SETTINGS, &originalDesktopMode); memset( &dm, 0, sizeof( dm ) ); dm.dmSize = sizeof( dm ); dm.dmPelsWidth = *width; dm.dmPelsHeight = *height; dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT; if (vid_displayfrequency->integer > 30) { dm.dmFields |= DM_DISPLAYFREQUENCY; dm.dmDisplayFrequency = vid_displayfrequency->integer; Com_Printf("...using display frequency %i\n", dm.dmDisplayFrequency); } if ( gl_bitdepth->integer > 0 ) { if(glw_state.allowdisplaydepthchange) { dm.dmFields |= DM_BITSPERPEL; dm.dmBitsPerPel = gl_bitdepth->integer; Com_Printf("...using gl_bitdepth of %d\n", gl_bitdepth->integer); } else { Com_Printf("WARNING:...changing depth not supported on Win95 < pre-OSR 2.x\n"); } } else { Com_Printf("...using desktop display depth of %d\n", originalDesktopMode.dmBitsPerPel); } Com_Printf ( "...calling CDS: " ); hr = ChangeDisplaySettings(&dm, CDS_FULLSCREEN); if (hr != DISP_CHANGE_SUCCESSFUL) { DEVMODE devmode; int modeNum; Com_Printf ( "failed\n" ); switch ((int)hr) { case DISP_CHANGE_BADFLAGS: //Shouldnt hapent Com_Printf("An invalid set of flags was passed in.\n"); return false; case DISP_CHANGE_BADPARAM: //Shouldnt hapent Com_Printf("An invalid parameter was passed in.\n"); return false; case DISP_CHANGE_RESTART: Com_Printf("Windows need to restart for that mode.\n"); return false; case DISP_CHANGE_FAILED: case DISP_CHANGE_BADMODE: if(hr == DISP_CHANGE_FAILED) Com_Printf("The display driver failed the specified graphics mode.\n"); else Com_Printf("The graphics mode is not supported.\n"); if(dm.dmFields & (DM_DISPLAYFREQUENCY|DM_BITSPERPEL)) { DWORD fields = dm.dmFields; dm.dmFields &= ~(DM_DISPLAYFREQUENCY|DM_BITSPERPEL); //Lets try without users params if(ChangeDisplaySettings(&dm, CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL) { if((fields & DM_DISPLAYFREQUENCY) && (fields & DM_BITSPERPEL)) Com_Printf("WARNING: vid_displayfrequency & gl_bitdepth is bad value(s), ignored\n"); else Com_Printf("WARNING: %s is bad value, ignored\n", (fields & DM_DISPLAYFREQUENCY) ? "vid_displayfrequency" : "gl_bitdepth"); return true; } dm.dmFields = fields; //it wasnt because of that } break; default: break; } // the exact mode failed, so scan EnumDisplaySettings for the next largest mode Com_Printf("...trying next higher resolution: " ); // we could do a better matching job here... for ( modeNum = 0 ; ; modeNum++ ) { if ( !EnumDisplaySettings( NULL, modeNum, &devmode ) ) { modeNum = -1; break; } if ( devmode.dmPelsWidth >= *width && devmode.dmPelsHeight >= *height && devmode.dmBitsPerPel >= 15 ) { break; } } if (modeNum == -1 || ChangeDisplaySettings(&devmode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { Com_Printf("failed\n"); return false; } *width = devmode.dmPelsWidth; *height = devmode.dmPelsHeight; Com_Printf ("ok, %ix%i\n", *width, *height); } else { Com_Printf ( "ok\n" ); } return true; }
/* ** GLW_SetMode */ static rserr_t GLW_SetMode( const char *drivername, int mode, int colorbits, qboolean cdsFullscreen ) { HDC hDC; const char *win_fs[] = { "W", "FS" }; int cdsRet; DEVMODE dm; // // print out informational messages // ri.Printf( PRINT_ALL, "...setting mode %d:", mode ); if ( !R_GetModeInfo( &glConfig.vidWidth, &glConfig.vidHeight, &glConfig.windowAspect, mode ) ) { ri.Printf( PRINT_ALL, " invalid mode\n" ); return RSERR_INVALID_MODE; } ri.Printf( PRINT_ALL, " %d %d %s\n", glConfig.vidWidth, glConfig.vidHeight, win_fs[cdsFullscreen] ); // // check our desktop attributes // hDC = GetDC( GetDesktopWindow() ); glw_state.desktopBitsPixel = GetDeviceCaps( hDC, BITSPIXEL ); glw_state.desktopWidth = GetDeviceCaps( hDC, HORZRES ); glw_state.desktopHeight = GetDeviceCaps( hDC, VERTRES ); ReleaseDC( GetDesktopWindow(), hDC ); // // verify desktop bit depth // if ( glConfig.driverType != GLDRV_VOODOO ) { if ( glw_state.desktopBitsPixel < 15 || glw_state.desktopBitsPixel == 24 ) { if ( colorbits == 0 || ( !cdsFullscreen && colorbits >= 15 ) ) { if ( MessageBox( NULL, "It is highly unlikely that a correct\n" "windowed display can be initialized with\n" "the current desktop display depth. Select\n" "'OK' to try anyway. Press 'Cancel' if you\n" "have a 3Dfx Voodoo, Voodoo-2, or Voodoo Rush\n" "3D accelerator installed, or if you otherwise\n" "wish to quit.", "Low Desktop Color Depth", MB_OKCANCEL | MB_ICONEXCLAMATION ) != IDOK ) { return RSERR_INVALID_MODE; } } } } // do a CDS if needed if ( cdsFullscreen ) { memset( &dm, 0, sizeof( dm ) ); dm.dmSize = sizeof( dm ); dm.dmPelsWidth = glConfig.vidWidth; dm.dmPelsHeight = glConfig.vidHeight; dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT; if ( r_displayRefresh->integer != 0 ) { dm.dmDisplayFrequency = r_displayRefresh->integer; dm.dmFields |= DM_DISPLAYFREQUENCY; } // try to change color depth if possible if ( colorbits != 0 ) { if ( glw_state.allowdisplaydepthchange ) { dm.dmBitsPerPel = colorbits; dm.dmFields |= DM_BITSPERPEL; ri.Printf( PRINT_ALL, "...using colorsbits of %d\n", colorbits ); } else { ri.Printf( PRINT_ALL, "WARNING:...changing depth not supported on Win95 < pre-OSR 2.x\n" ); } } else { ri.Printf( PRINT_ALL, "...using desktop display depth of %d\n", glw_state.desktopBitsPixel ); } // // if we're already in fullscreen then just create the window // if ( glw_state.cdsFullscreen ) { ri.Printf( PRINT_ALL, "...already fullscreen, avoiding redundant CDS\n" ); if ( !GLW_CreateWindow ( drivername, glConfig.vidWidth, glConfig.vidHeight, colorbits, qtrue ) ) { ri.Printf( PRINT_ALL, "...restoring display settings\n" ); ChangeDisplaySettings( 0, 0 ); return RSERR_INVALID_MODE; } } // // need to call CDS // else { ri.Printf( PRINT_ALL, "...calling CDS: " ); // try setting the exact mode requested, because some drivers don't report // the low res modes in EnumDisplaySettings, but still work if ( ( cdsRet = ChangeDisplaySettings( &dm, CDS_FULLSCREEN ) ) == DISP_CHANGE_SUCCESSFUL ) { ri.Printf( PRINT_ALL, "ok\n" ); if ( !GLW_CreateWindow ( drivername, glConfig.vidWidth, glConfig.vidHeight, colorbits, qtrue) ) { ri.Printf( PRINT_ALL, "...restoring display settings\n" ); ChangeDisplaySettings( 0, 0 ); return RSERR_INVALID_MODE; } glw_state.cdsFullscreen = qtrue; } else { // // the exact mode failed, so scan EnumDisplaySettings for the next largest mode // DEVMODE devmode; int modeNum; ri.Printf( PRINT_ALL, "failed, " ); PrintCDSError( cdsRet ); ri.Printf( PRINT_ALL, "...trying next higher resolution:" ); // we could do a better matching job here... for ( modeNum = 0 ; ; modeNum++ ) { if ( !EnumDisplaySettings( NULL, modeNum, &devmode ) ) { modeNum = -1; break; } if ( devmode.dmPelsWidth >= glConfig.vidWidth && devmode.dmPelsHeight >= glConfig.vidHeight && devmode.dmBitsPerPel >= 15 ) { break; } } if ( modeNum != -1 && ( cdsRet = ChangeDisplaySettings( &devmode, CDS_FULLSCREEN ) ) == DISP_CHANGE_SUCCESSFUL ) { ri.Printf( PRINT_ALL, " ok\n" ); if ( !GLW_CreateWindow( drivername, glConfig.vidWidth, glConfig.vidHeight, colorbits, qtrue) ) { ri.Printf( PRINT_ALL, "...restoring display settings\n" ); ChangeDisplaySettings( 0, 0 ); return RSERR_INVALID_MODE; } glw_state.cdsFullscreen = qtrue; } else { ri.Printf( PRINT_ALL, " failed, " ); PrintCDSError( cdsRet ); //@Barbatos - try initializing default 800x600 mode instead of crashing ri.Printf( PRINT_ALL, "... trying to fallback to r_mode 4 (800x600)\n"); ri.Cvar_Set( "r_mode", "4" ); glw_state.cdsFullscreen = qtrue; if ( !GLW_CreateWindow( drivername, glConfig.vidWidth, glConfig.vidHeight, colorbits, qtrue) ) { ri.Printf( PRINT_ALL, "...restoring display settings\n" ); ChangeDisplaySettings( 0, 0 ); glw_state.cdsFullscreen = qfalse; glConfig.isFullscreen = qfalse; if ( !GLW_CreateWindow( drivername, glConfig.vidWidth, glConfig.vidHeight, colorbits, qfalse) ) { return RSERR_INVALID_MODE; } return RSERR_INVALID_FULLSCREEN; } // Perform a vid_restart to apply the changes else { Cbuf_AddText( "vid_restart" ); } } } } if( glw_state.cdsFullscreen ) memcpy( &glw_fs_dm, &dm, sizeof( glw_fs_dm ) ); else memset( &glw_fs_dm, 0, sizeof( glw_fs_dm ) ); } else { if ( glw_state.cdsFullscreen ) { ChangeDisplaySettings( 0, 0 ); } glw_state.cdsFullscreen = qfalse; if ( !GLW_CreateWindow( drivername, glConfig.vidWidth, glConfig.vidHeight, colorbits, qfalse ) ) { return RSERR_INVALID_MODE; } } // // success, now check display frequency, although this won't be valid on Voodoo(2) // memset( &dm, 0, sizeof( dm ) ); dm.dmSize = sizeof( dm ); if ( EnumDisplaySettings( NULL, ENUM_CURRENT_SETTINGS, &dm ) ) { glConfig.displayFrequency = dm.dmDisplayFrequency; } // NOTE: this is overridden later on standalone 3Dfx drivers glConfig.isFullscreen = cdsFullscreen; return RSERR_OK; }
void create(HINSTANCE hInstance, int buffer, bool fullscreen, bool border, std::string title, int &x, int &y, unsigned int &w, unsigned int &h) { DWORD dwExStyle; DWORD style; if (fullscreen){ DEVMODE dmScreenSettings; // Device Mode if (!EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &dmScreenSettings)){ ::error("GEM: couldn't get screen capabilities!"); } else { w = dmScreenSettings.dmPelsWidth; h = dmScreenSettings.dmPelsHeight; } x=y=0; memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // Makes Sure Memory's Cleared dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Size Of The Devmode Structure dmScreenSettings.dmPelsWidth = w; // Selected Screen Width dmScreenSettings.dmPelsHeight = h; // Selected Screen Height dmScreenSettings.dmBitsPerPel = 32; // 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) { dmScreenSettings.dmPelsWidth = w; dmScreenSettings.dmPelsHeight = h; if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { ::error("couldn't switch to fullscreen"); fullscreen=false; } } } // Since Windows uses some of the window for the border, etc, // we have to ask how big the window should really be RECT newSize = getRealRect(x, y, w, h, border, fullscreen, style, dwExStyle); // Create the window win = CreateWindowEx ( dwExStyle, "GEM", title.c_str(), style, newSize.left, newSize.top, newSize.right - newSize.left, newSize.bottom - newSize.top, NULL, NULL, hInstance, NULL); if (!win) { throw(GemException("Unable to create window")); } // create the device context dc = GetDC(win); if (!dc) { throw(GemException("GEM: Unable to create device context")); } // set the pixel format for the window if (!bSetupPixelFormat(dc, buffer)) { throw(GemException("Unable to set window pixel format")); } // create the OpenGL context context = wglCreateContext(dc); if (!context) { throw(GemException("Unable to create OpenGL context")); } // do we share display lists? if (sharedContext) wglShareLists(sharedContext, context); // make the context the current rendering context if (!wglMakeCurrent(dc, context)) { throw(GemException("Unable to make OpenGL context current")); } }
SDL_Surface *DIB_SetVideoMode(_THIS, SDL_Surface *current, int width, int height, int bpp, Uint32 flags) { SDL_Surface *video; Uint32 prev_flags; DWORD style; const DWORD directstyle = (WS_POPUP); const DWORD windowstyle = (WS_OVERLAPPED|WS_CAPTION|WS_SYSMENU|WS_MINIMIZEBOX); const DWORD resizestyle = (WS_THICKFRAME|WS_MAXIMIZEBOX); int binfo_size; BITMAPINFO *binfo; HDC hdc; RECT bounds; int x, y; Uint32 Rmask, Gmask, Bmask; #ifdef HAVE_OPENGL //maks /* Clean up any GL context that may be hanging around */ if ( current->flags & SDL_OPENGL ) { //maks: close only in viewo quit to avoid texture lost when go to game mode WIN_GL_ShutDown(this); } #endif /* Recalculate the bitmasks if necessary */ if ( bpp == current->format->BitsPerPixel ) { video = current; } else { switch (bpp) { case 15: case 16: if ( DIB_SussScreenDepth() == 15 ) { /* 5-5-5 */ Rmask = 0x00007c00; Gmask = 0x000003e0; Bmask = 0x0000001f; } else { /* 5-6-5 */ Rmask = 0x0000f800; Gmask = 0x000007e0; Bmask = 0x0000001f; } break; case 24: case 32: /* GDI defined as 8-8-8 */ Rmask = 0x00ff0000; Gmask = 0x0000ff00; Bmask = 0x000000ff; break; default: Rmask = 0x00000000; Gmask = 0x00000000; Bmask = 0x00000000; break; } video = SDL_CreateRGBSurface(SDL_SWSURFACE, 0, 0, bpp, Rmask, Gmask, Bmask, 0); if ( video == NULL ) { SDL_OutOfMemory(); return(NULL); } } /* Fill in part of the video surface */ prev_flags = video->flags; video->flags = 0; /* Clear flags */ video->w = width; video->h = height; video->pitch = SDL_CalculatePitch(video); #ifdef WIN32_PLATFORM_PSPC /* Stuff to hide that $#!^%#$ WinCE taskbar in fullscreen... */ if ( flags & SDL_FULLSCREEN ) { if ( !(prev_flags & SDL_FULLSCREEN) ) { SHFullScreen(SDL_Window, SHFS_HIDETASKBAR); SHFullScreen(SDL_Window, SHFS_HIDESIPBUTTON); ShowWindow(FindWindow(TEXT("HHTaskBar"),NULL),SW_HIDE); } video->flags |= SDL_FULLSCREEN; } else { if ( prev_flags & SDL_FULLSCREEN ) { SHFullScreen(SDL_Window, SHFS_SHOWTASKBAR); SHFullScreen(SDL_Window, SHFS_SHOWSIPBUTTON); ShowWindow(FindWindow(TEXT("HHTaskBar"),NULL),SW_SHOWNORMAL); } } #endif #ifndef NO_CHANGEDISPLAYSETTINGS /* Set fullscreen mode if appropriate */ if ( (flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) { DEVMODE settings; memset(&settings, 0, sizeof(DEVMODE)); settings.dmSize = sizeof(DEVMODE); settings.dmBitsPerPel = video->format->BitsPerPixel; settings.dmPelsWidth = width; settings.dmPelsHeight = height; settings.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT | DM_BITSPERPEL; if ( ChangeDisplaySettings(&settings, CDS_FULLSCREEN) == DISP_CHANGE_SUCCESSFUL ) { video->flags |= SDL_FULLSCREEN; SDL_fullscreen_mode = settings; } } #endif /* !NO_CHANGEDISPLAYSETTINGS */ /* Reset the palette and create a new one if necessary */ if ( screen_pal != NULL ) { /* RJR: March 28, 2000 delete identity palette if switching from a palettized mode */ DeleteObject(screen_pal); screen_pal = NULL; } if ( bpp <= 8 ) { /* RJR: March 28, 2000 create identity palette switching to a palettized mode */ screen_pal = DIB_CreatePalette(bpp); } style = GetWindowLong(SDL_Window, GWL_STYLE); style &= ~(resizestyle|WS_MAXIMIZE); if ( (video->flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) { style &= ~windowstyle; style |= directstyle; } else { #ifndef NO_CHANGEDISPLAYSETTINGS if ( (prev_flags & SDL_FULLSCREEN) == SDL_FULLSCREEN ) { ChangeDisplaySettings(NULL, 0); } #endif if ( flags & SDL_NOFRAME ) { style &= ~windowstyle; style |= directstyle; video->flags |= SDL_NOFRAME; } else { style &= ~directstyle; style |= windowstyle; if ( flags & SDL_RESIZABLE ) { style |= resizestyle; video->flags |= SDL_RESIZABLE; } } #if WS_MAXIMIZE if (IsZoomed(SDL_Window)) style |= WS_MAXIMIZE; #endif } /* DJM: Don't piss of anyone who has setup his own window */ if ( SDL_windowid == NULL ) SetWindowLong(SDL_Window, GWL_STYLE, style); /* Delete the old bitmap if necessary */ if ( screen_bmp != NULL ) { DeleteObject(screen_bmp); } if ( ! (flags & SDL_OPENGL) ) { BOOL is16bitmode = (video->format->BytesPerPixel == 2); /* Suss out the bitmap info header */ binfo_size = sizeof(*binfo); if( is16bitmode ) { /* 16bit modes, palette area used for rgb bitmasks */ binfo_size += 3*sizeof(DWORD); } else if ( video->format->palette ) { binfo_size += video->format->palette->ncolors * sizeof(RGBQUAD); } binfo = (BITMAPINFO *)malloc(binfo_size); if ( ! binfo ) { if ( video != current ) { SDL_FreeSurface(video); } SDL_OutOfMemory(); return(NULL); } binfo->bmiHeader.biSize = sizeof(BITMAPINFOHEADER); binfo->bmiHeader.biWidth = video->w; binfo->bmiHeader.biHeight = -video->h; /* -ve for topdown bitmap */ binfo->bmiHeader.biPlanes = 1; binfo->bmiHeader.biSizeImage = video->h * video->pitch; binfo->bmiHeader.biXPelsPerMeter = 0; binfo->bmiHeader.biYPelsPerMeter = 0; binfo->bmiHeader.biClrUsed = 0; binfo->bmiHeader.biClrImportant = 0; binfo->bmiHeader.biBitCount = video->format->BitsPerPixel; if ( is16bitmode ) { /* BI_BITFIELDS tells CreateDIBSection about the rgb masks in the palette */ binfo->bmiHeader.biCompression = BI_BITFIELDS; ((Uint32*)binfo->bmiColors)[0] = video->format->Rmask; ((Uint32*)binfo->bmiColors)[1] = video->format->Gmask; ((Uint32*)binfo->bmiColors)[2] = video->format->Bmask; } else { binfo->bmiHeader.biCompression = BI_RGB; /* BI_BITFIELDS for 565 vs 555 */ if ( video->format->palette ) { memset(binfo->bmiColors, 0, video->format->palette->ncolors*sizeof(RGBQUAD)); } } /* Create the offscreen bitmap buffer */ hdc = GetDC(SDL_Window); screen_bmp = CreateDIBSection(hdc, binfo, DIB_RGB_COLORS, (void **)(&video->pixels), NULL, 0); ReleaseDC(SDL_Window, hdc); free(binfo); if ( screen_bmp == NULL ) { if ( video != current ) { SDL_FreeSurface(video); } SDL_SetError("Couldn't create DIB section"); return(NULL); } this->UpdateRects = DIB_NormalUpdate; /* Set video surface flags */ if ( bpp <= 8 ) { /* BitBlt() maps colors for us */ video->flags |= SDL_HWPALETTE; } } /* Resize the window */ if ( SDL_windowid == NULL ) { HWND top; UINT swp_flags; const char *window = getenv("SDL_VIDEO_WINDOW_POS"); const char *center = getenv("SDL_VIDEO_CENTERED"); if ( !SDL_windowX && !SDL_windowY ) { if ( window ) { if ( sscanf(window, "%d,%d", &x, &y) == 2 ) { SDL_windowX = x; SDL_windowY = y; } if ( strcmp(window, "center") == 0 ) { center = window; window = NULL; } } } swp_flags = (SWP_NOCOPYBITS | SWP_SHOWWINDOW); SDL_resizing = 1; bounds.left = SDL_windowX; bounds.top = SDL_windowY; bounds.right = SDL_windowX+video->w; bounds.bottom = SDL_windowY+video->h; AdjustWindowRectEx(&bounds, GetWindowLong(SDL_Window, GWL_STYLE), FALSE, 0); width = bounds.right-bounds.left; height = bounds.bottom-bounds.top; if ( (flags & SDL_FULLSCREEN) ) { x = (GetSystemMetrics(SM_CXSCREEN)-width)/2; y = (GetSystemMetrics(SM_CYSCREEN)-height)/2; } else if ( SDL_windowX || SDL_windowY || window ) { x = bounds.left; y = bounds.top; } else if ( center ) { x = (GetSystemMetrics(SM_CXSCREEN)-width)/2; y = (GetSystemMetrics(SM_CYSCREEN)-height)/2; } else { x = y = -1; swp_flags |= SWP_NOMOVE; } if ( y < 0 ) { /* Cover up title bar for more client area */ y -= GetSystemMetrics(SM_CYCAPTION)/2; } if ( flags & SDL_FULLSCREEN ) { top = HWND_TOPMOST; } else { top = HWND_NOTOPMOST; } SetWindowPos(SDL_Window, top, x, y, width, height, swp_flags); SDL_resizing = 0; SetForegroundWindow(SDL_Window); } #ifdef HAVE_OPENGL //maks /* Set up for OpenGL */ if ( flags & SDL_OPENGL ) { /*if ( WIN_GL_SetupWindow(this) < 0 ) { return(NULL); } video->flags |= SDL_OPENGL;*/ if ( WIN_GL_SetupWindow(this) >= 0 ) { video->flags |= SDL_OPENGL; } } #endif /* We're live! */ return(video); }
qboolean GLW_ResetDesktopMode( void ) { WG_RestoreGamma(); ChangeDisplaySettings( 0, 0 ); return qtrue; }
//初始化窗口类,创建应用程序窗口 void SystemClass::InitializeWindows(int& screenWidth, int& screenHeight) { WNDCLASSEX wc; DEVMODE dmScreenSettings; int posX, posY; //获取System class对象 ApplicationHandle = this; // 得到应用程序实例句柄 m_hinstance = GetModuleHandle(nullptr); // 应用程序名字 m_applicationName = TEXT("Engine"); // 设置窗口类参数. wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = m_hinstance; wc.hIcon = LoadIcon(nullptr, IDI_WINLOGO); wc.hIconSm = wc.hIcon; wc.hCursor = LoadCursor(nullptr, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wc.lpszMenuName = nullptr; wc.lpszClassName = m_applicationName; wc.cbSize = sizeof(WNDCLASSEX); // 注册窗口类 RegisterClassEx(&wc); // 得到windows桌面分辨率 screenWidth = GetSystemMetrics(SM_CXSCREEN); screenHeight = GetSystemMetrics(SM_CYSCREEN); // 根据是否全屏设置不同的分辨率 if(FULL_SCREEN) { //全屏模式下,设置窗口大小为windows桌面分辨率 memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); dmScreenSettings.dmSize = sizeof(dmScreenSettings); dmScreenSettings.dmPelsWidth = (DWORD)screenWidth; dmScreenSettings.dmPelsHeight = (DWORD)screenHeight; dmScreenSettings.dmBitsPerPel = 32; dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // 临时设置显示设备为全屏模式,注意:应用程序退出时候,将恢复系统默认设置 ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN); // 设置窗口的左上角坐标位置为(0,0) posX = posY = 0; } else { // 窗口模式:800*600 screenWidth = 800; screenHeight = 600; // 窗口左上角坐标位置,posX, posY posX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth) / 2; posY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2; } // 全屏和窗口使用不同的参数. if(FULL_SCREEN) { m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP, posX, posY, screenWidth, screenHeight, nullptr, nullptr, m_hinstance, nullptr); } else { m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName, WS_OVERLAPPEDWINDOW, posX, posY, screenWidth, screenHeight, nullptr, nullptr, m_hinstance, nullptr); } // 显示窗口并设置其为焦点. ShowWindow(m_hwnd, SW_SHOW); SetForegroundWindow(m_hwnd); SetFocus(m_hwnd); //隐藏鼠标 ShowCursor(FALSE); }
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; // Структура сообщения Windows WNDCLASS wc; // Структура класса Windows для установки типа окна HWND hWnd;// Сохранение дискриптора окна wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (WNDPROC) WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = NULL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = "OpenGL WinClass"; if(!RegisterClass(&wc)) { MessageBox(0,"Failed To Register The Window Class.","Error",MB_OK|MB_ICONERROR); return FALSE; } hWnd = CreateWindow( "OpenGL WinClass", "Jeff Molofee's GL Code Tutorial ... NeHe '99", // Заголовок вверху окна WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0, // Позиция окна на экране //640, 480, // Ширина и высота окна 1024, 600, // Ширина и высота окна NULL, NULL, hInstance, NULL); if(!hWnd) { MessageBox(0,"Window Creation Error.","Error",MB_OK|MB_ICONERROR); return FALSE; } DEVMODE dmScreenSettings; // Режим работы memset(&dmScreenSettings, 0, sizeof(DEVMODE)); // Очистка для хранения установок dmScreenSettings.dmSize = sizeof(DEVMODE); // Размер структуры Devmode dmScreenSettings.dmPelsWidth = 1024;//640; // Ширина экрана dmScreenSettings.dmPelsHeight = 600;//480; // Высота экрана dmScreenSettings.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT; // Режим Пиксела ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN); // Переключение в полный экран ShowWindow(hWnd, SW_SHOW); UpdateWindow(hWnd); SetFocus(hWnd); POINT pt; POINT lastPt; GetCursorPos(&lastPt); //загрузка модели Model *pModel = NULL; pModel = new MilkshapeModel(); if ( pModel->loadModelData( "guardianModel/model.ms3d" ) == false ) { MessageBox( NULL, "Couldn't load the model data/model.ms3d", "Error", MB_OK | MB_ICONERROR ); return 0; // Если модель не загружена, выходим } //pModel->reloadTextures(); //загрузка модели gameMap = new CGameMap("Maps\\map1.txt", texture); guardian = new CGuardian(1.5f, 1.5f, pModel); spawn = new CSpawn(4.0f, 1.5f); ShowCursor(FALSE); __int64 g_freq = Init(); __int64 lastTime = GetMicroTickCount(); //mciSendString("play Fone.mp3 wait", NULL, NULL, NULL);//Проба с музыкой while (1) { // Обработка всех сообщений while (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) { if (GetMessage(&msg, NULL, 0, 0)) { TranslateMessage(&msg); DispatchMessage(&msg); } else { return TRUE; } } __int64 newTime = GetMicroTickCount(); double dt = (newTime - lastTime) / 1000000.0; lastTime = newTime; guardian->Update(*gameMap, dt, player); gameMap -> update(); //zoombie spawn->CreateZoombi(dt); spawn->Update(*gameMap, dt, player); //zoombie GetCursorPos(&pt); if (keys[VK_UP]) { player.MakeStepUp(*gameMap, dt); } if (keys[VK_DOWN]) { player.MakeStepDown(*gameMap, dt); } if (keys[VK_LEFT]) { player.MakeStepLeft(*gameMap, dt); } if (keys[VK_RIGHT]) { player.MakeStepRight(*gameMap, dt); } if (keys['G']) { player.PutMark(texture[2]); keys['G'] = false; } player.MakeTurn((GLfloat)((lastPt.x - pt.x) * 0.7), (GLfloat)((pt.y - lastPt.y) * 0.2)); if (pt.x <= 0 || pt.x >= 1020) { SetCursorPos(1024 / 2, pt.y); GetCursorPos(&pt); } lastPt = pt; DrawGLScene(); // Нарисовать сцену SwapBuffers(hDC); // Переключить буфер экрана if (keys[VK_ESCAPE]) SendMessage(hWnd,WM_CLOSE,0,0); // Если ESC - выйти } delete gameMap; delete guardian; delete spawn; }
bool System::InitialiseWindows(OpenGL* openGL, int& screenWidth, int& screenHeight) { WNDCLASSEX wc; DEVMODE dmScreenSettings; int posX, posY; bool result; //Get and external pointer to this object ApplicationHandle = this; //Get the instance of this application m_hInstance = GetModuleHandle(NULL); //Give the application a name m_applicationName = "E03"; //Setup the windows class with default setting wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = m_hInstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hIconSm = wc.hIcon; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = m_applicationName; wc.cbSize = sizeof(WNDCLASSEX); //Register the window class RegisterClassEx(&wc); //Create a temporary windows to initialise OpenGL extentions m_hWnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName, WS_POPUP, 0, 0, 640, 480, NULL, NULL, m_hInstance, NULL); if (m_hWnd == NULL) { return false; } //Don't show the window ShowWindow(m_hWnd, SW_HIDE); //Initialise a temporary OpenGL window and load the extentions result = m_openGL->InitialiseExtentions(m_hWnd); if (!result) { MessageBox(m_hWnd, "Could not initialize the OpenGL extensions.", "Error", MB_OK); return false; } //Release the temporary window now that the extensions have been initialised DestroyWindow(m_hWnd); m_hWnd = NULL; //Determine the resolution of the clients desktop screen screenWidth = GetSystemMetrics(SM_CXSCREEN); screenHeight = GetSystemMetrics(SM_CYSCREEN); //Setup the screen settings depending on whether or not it is in full screen or windowed mode if (FULL_SCREEN) { //If fullscreen set the screen to maximum size of the users desktop and 32bit memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); dmScreenSettings.dmSize = sizeof(dmScreenSettings); dmScreenSettings.dmPelsWidth = (unsigned long)screenWidth; dmScreenSettings.dmPelsHeight = (unsigned long)screenHeight; dmScreenSettings.dmBitsPerPel = 32; dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; //Change the display settings to full screen ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN); //Set the position of the window to the top left corner posX = posY = 0; } else { //if windowed set the resolution to 800 x 600 screenWidth = 800; screenHeight = 600; //Place the window in the middle of the screen posX = 0;//(GetSystemMetrics(SM_CXSCREEN)-screenWidth/2); posY = 0;//(GetSystemMetrics(SM_CYSCREEN) - screenHeight / 2); } //Create the window with the screen settings and get the handle to it. m_hWnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName, WS_POPUP, posX, posY, screenWidth, screenHeight, NULL, NULL, m_hInstance, NULL); if (m_hWnd == NULL) { return false; } //Initialise OpenGL now that the window has been created result = m_openGL->InitialiseOpenGL(m_hWnd, screenWidth, screenHeight, SCREEN_DEPTH, SCREEN_NEAR, VSYNC_ENABLED); if (!result) { MessageBox(m_hWnd, "Could not initialize OpenGL, check if video card supports OpenGL 4.0.", "Error", MB_OK); return false; } //Bring the window up on the screen and set it as the main focus ShowWindow(m_hWnd, SW_SHOW); SetForegroundWindow(m_hWnd); SetFocus(m_hWnd); //Hide the mouse cursor ShowCursor(false); return true; }
BOOL CreateGLWindow(PGLFRAME pglFrame, char* title, int x, int y, int width, int height, int bits, int fullscreenflag) { GLuint PixelFormat; // Holds The Results After Searching For A Match DWORD dwExStyle; // Window Extended Style DWORD dwStyle; // Window Style RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values WindowBorderOfs_X = GetSystemMetrics( SM_CXFRAME ); WindowBorderOfs_Y = GetSystemMetrics( SM_CYFRAME ) + GetSystemMetrics( SM_CYCAPTION ); 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 TransformClear( &pglFrame->T ); pglFrame->next = pglRoot; if( pglRoot ) pglRoot->prior = pglFrame; pglRoot = pglFrame; pglFrame->fullscreen=fullscreenflag; // Set The Global Fullscreen Flag if (pglFrame->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 Run In A Window. 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) { pglFrame->fullscreen=FALSE; // Select Windowed Mode (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; // Exit And Return FALSE } } } if (pglFrame->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 dwExStyle = 0; dwStyle = WS_POPUP|WS_VISIBLE; } AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle); // Adjust Window To True Requested Size if (!(pglFrame->hWnd=CreateWindowEx( dwExStyle, // Extended Style For The Window "OpenGLWindow", // Class Name title, // Window Title WS_CLIPSIBLINGS | // Required Window Style WS_CLIPCHILDREN | // Required Window Style dwStyle, // Selected Window Style x, y, // Window Position WindowRect.right-WindowRect.left, // Calculate Adjusted Window Width WindowRect.bottom-WindowRect.top, // Calculate Adjusted Window Height NULL, // No Parent Window NULL, // No Menu GetModuleHandle(NULL), // Instance NULL))) // Don't Pass Anything To WM_CREATE { DWORD dwError = GetLastError(); KillGLWindow(pglFrame); // Reset The Display MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } SetWindowLong( pglFrame->hWnd, GWL_USERDATA, (DWORD)pglFrame ); { 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 0, // 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 }; pfd.cColorBits = bits; if (!(pglFrame->hDC=GetDC(pglFrame->hWnd))) // Did We Get A Device Context? { KillGLWindow(pglFrame); // Reset The Display MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(PixelFormat=ChoosePixelFormat(pglFrame->hDC,&pfd))) // Did Windows Find A Matching Pixel Format? { KillGLWindow(pglFrame); // Reset The Display MessageBox(NULL,"Can't Find A Suitable PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!SetPixelFormat(pglFrame->hDC,PixelFormat,&pfd)) // Are We Able To Set The Pixel Format? { KillGLWindow(pglFrame); // Reset The Display MessageBox(NULL,"Can't Set The PixelFormat.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } } if (!(pglFrame->hRC=wglCreateContext(pglFrame->hDC))) // Are We Able To Get A Rendering Context? { KillGLWindow(pglFrame); // Reset The Display MessageBox(NULL,"Can't Create A GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if(!wglMakeCurrent(pglFrame->hDC,pglFrame->hRC)) // Try To Activate The Rendering Context { KillGLWindow(pglFrame); // Reset The Display MessageBox(NULL,"Can't Activate The GL Rendering Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } ShowWindow(pglFrame->hWnd,SW_SHOW); // Show The Window SetForegroundWindow(pglFrame->hWnd); // Slightly Higher Priority SetFocus(pglFrame->hWnd); // Sets Keyboard Focus To The Window ReSizeGLScene(pglFrame,width, height); // Set Up Our Perspective GL Screen if (!InitGL()) // Initialize Our Newly Created GL Window { KillGLWindow(pglFrame); // Reset The Display MessageBox(NULL,"Initialization Failed.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } return TRUE; // Success }
/* ================================================================================== */ bool AtlasEngine::initializeWindows(OpenGLClass* ogl, int& width, int& height) { WNDCLASSEX wc; DEVMODE dmscreensettings; int posX, posY; bool result; // get external pointer to this object ApplicationHandle = this; // get instance of the current application hinstance = GetModuleHandle(NULL); // give the application name appName = L"Atlas Engine"; // setup the windows class 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.hIconSm = wc.hIcon; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = appName; wc.cbSize = sizeof(WNDCLASSEX); // register the window class RegisterClassEx(&wc); // create temporary window for OPENGL hwnd = CreateWindowEx(WS_EX_APPWINDOW, appName, appName, WS_POPUP, 0, 0, 800, 600, NULL, NULL, hinstance, NULL); if(hwnd == NULL) return false; // dont show the window ShowWindow(hwnd, SW_HIDE); // initialize temporary opengl window to load extensions result = opengl->initializeExtensions(hwnd); if(!result) { MessageBox(hwnd, L"Failed to initialize the OpenGL extensions", L"Error", MB_OK); return false; } // release the temporary window DestroyWindow(hwnd); hwnd = NULL; // determine resolution of the client's desktop screen width = GetSystemMetrics(SM_CXSCREEN); height = GetSystemMetrics(SM_CYSCREEN); // setup the screen settings depending if it is on Fullscreen/Windowed mode if(FULL_SCREEN) { // if fulscreen, set the screen to maximum size memset(&dmscreensettings, 0, sizeof(dmscreensettings)); dmscreensettings.dmSize = sizeof(dmscreensettings); dmscreensettings.dmPelsWidth = (unsigned long)width; dmscreensettings.dmPelsHeight = (unsigned long)height; dmscreensettings.dmBitsPerPel = 32; dmscreensettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // change display settings to full screen ChangeDisplaySettings(&dmscreensettings, CDS_FULLSCREEN); // set position of window posX = posY = 0; } else { // windowed dimensions width = 800; height = 600; // place window in the middle of screen posX = (GetSystemMetrics(SM_CXSCREEN) - width)/2; posY = (GetSystemMetrics(SM_CYSCREEN) - height)/2; } // create window // OVERLAPPED - for a window with border & controls // POPUP - for a window without border hwnd = CreateWindowEx(WS_EX_APPWINDOW, appName, appName, WS_OVERLAPPEDWINDOW, posX, posY, width, height, NULL, NULL, hinstance, NULL); if(hwnd == NULL) return false; // initialize opengl now result = opengl->initializeOpenGL(hwnd, width, height, SCREEN_DEPTH, SCREEN_NEAR, VSYNC_ENABLED); if(!result) { MessageBox(hwnd, L"Failed to initialize OpenGL, make sure your video card supports OpenGL4.0", L"Error", MB_OK); return false; } // bring the window up on the screen and focus ShowWindow(hwnd, SW_SHOW); SetForegroundWindow(hwnd); SetFocus(hwnd); // hide the mouse ShowCursor(false); return true; }
BOOL OpenGLInterface::CreateGLWindow( LPCWSTR title, int width, int height, int bits, bool fullscreenflag ) { GLuint PixelFormat; WNDCLASS wc; DWORD dwExStyle; DWORD dwStyle; RECT WindowRect; // Grabs Rectangle Upper Left / Lower Right Values WindowRect.left=(long)0; // Óñòàíîâèòü ëåâóþ ñîñòàâëÿþùóþ â 0 WindowRect.right=(long)width; // Óñòàíîâèòü ïðàâóþ ñîñòàâëÿþùóþ â Width WindowRect.top=(long)0; // Óñòàíîâèòü âåðõíþþ ñîñòàâëÿþùóþ â 0 WindowRect.bottom=(long)height; // Óñòàíîâèòü íèæíþþ ñîñòàâëÿþùóþ â Height fullscreen = fullscreenflag; // Óñòàíàâëèâàåì çíà÷åíèå ãëîáàëüíîé ïåðåìåííîé fullscreen hInstance = GetModuleHandle(NULL); // Ñ÷èòàåì äåñêðèïòîð íàøåãî ïðèëîæåíèÿ wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Ïåðåðèñóåì ïðè ïåðåìåùåíèè è ñîçäà¸ì ñêðûòûé DC wc.lpfnWndProc = &OpenGLInterface::InitialWndProc; // Ïðîöåäóðà îáðàáîòêè ñîîáùåíèé wc.cbClsExtra = 0; // Íåò äîïîëíèòåëüíîé èíôîðìàöèè äëÿ îêíà wc.cbWndExtra = 0; // Íåò äîïîëíèòåëüíîé èíôîðìàöèè äëÿ îêíà wc.hInstance = hInstance; // Óñòàíàâëèâàåì äåñêðèïòîð wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Çàãðóæàåì èêîíêó ïî óìîë÷àíèþ wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Çàãðóæàåì óêàçàòåëü ìûøêè wc.hbrBackground = NULL; // Ôîí íå òðåáóåòñÿ äëÿ GL wc.lpszMenuName = NULL; // Ìåíþ â îêíå íå áóäåò wc.lpszClassName = L"OpenGL"; // Óñòàíàâëèâàåì èìÿ êëàññó if( !RegisterClass( &wc ) ) { MessageBox( NULL, L"Failed To Register The Window Class.", L"ERROR", MB_OK | MB_ICONEXCLAMATION ); return false; // Âûõîä è âîçâðàùåíèå ôóíêöèåé çíà÷åíèÿ false } if( fullscreen ) { DEVMODE dmScreenSettings; // Ðåæèì óñòðîéñòâà memset( &dmScreenSettings, 0, sizeof( dmScreenSettings ) ); // Î÷èñòêà äëÿ õðàíåíèÿ óñòàíîâîê dmScreenSettings.dmSize=sizeof( dmScreenSettings ); // Ðàçìåð ñòðóêòóðû Devmode dmScreenSettings.dmPelsWidth = width; // Øèðèíà ýêðàíà dmScreenSettings.dmPelsHeight = height; // Âûñîòà ýêðàíà dmScreenSettings.dmBitsPerPel = bits; // Ãëóáèíà öâåòà dmScreenSettings.dmFields= DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT;// Ðåæèì Ïèêñåëÿ // Ïûòàåìñÿ óñòàíîâèòü âûáðàííûé ðåæèì è ïîëó÷èòü ðåçóëüòàò. Ïðèìå÷àíèå: CDS_FULLSCREEN óáèðàåò ïàíåëü óïðàâëåíèÿ. if( ChangeDisplaySettings( &dmScreenSettings, CDS_FULLSCREEN ) != DISP_CHANGE_SUCCESSFUL ) { if( MessageBox( NULL, L"The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?", L"NeHe GL", MB_YESNO | MB_ICONEXCLAMATION) == IDYES ) { fullscreen = false; } else { MessageBox( NULL, L"Program Will Now Close.", L"ERROR", MB_OK | MB_ICONSTOP ); return false; } } } if(fullscreen) { dwExStyle = WS_EX_APPWINDOW; // Ðàñøèðåííûé ñòèëü îêíà dwStyle = WS_POPUP; // Îáû÷íûé ñòèëü îêíà ShowCursor( true ); } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // Ðàñøèðåííûé ñòèëü îêíà dwStyle = WS_OVERLAPPEDWINDOW; // Îáû÷íûé ñòèëü îêíà } AdjustWindowRectEx( &WindowRect, dwStyle, false, dwExStyle ); if( !( hWnd = CreateWindowEx( dwExStyle, // Ðàñøèðåííûé ñòèëü äëÿ îêíà _T("OpenGL"), // Èìÿ êëàññà title, // Çàãîëîâîê îêíà WS_CLIPSIBLINGS | // Òðåáóåìûé ñòèëü äëÿ îêíà WS_CLIPCHILDREN | // Òðåáóåìûé ñòèëü äëÿ îêíà dwStyle, // Âûáèðàåìûå ñòèëè äëÿ îêíà 0, 0, // Ïîçèöèÿ îêíà WindowRect.right-WindowRect.left, // Âû÷èñëåíèå ïîäõîäÿùåé øèðèíû WindowRect.bottom-WindowRect.top, // Âû÷èñëåíèå ïîäõîäÿùåé âûñîòû NULL, // Íåò ðîäèòåëüñêîãî NULL, // Íåò ìåíþ hInstance, // Äåñêðèïòîð ïðèëîæåíèÿ this ) ) ) { // Íå ïåðåäà¸ì íè÷åãî äî WM_CREATE (???) KillGLWindow(); // Âîññòàíîâèòü ýêðàí MessageBox( NULL, L"Window Creation Error.", L"ERROR", MB_OK | MB_ICONEXCLAMATION ); return false; // Âåðíóòü false } static PIXELFORMATDESCRIPTOR pfd= // pfd ñîîáùàåò Windows êàêèì áóäåò âûâîä íà ýêðàí êàæäîãî ïèêñåëÿ { sizeof(PIXELFORMATDESCRIPTOR), // Ðàçìåð äåñêðèïòîðà äàííîãî ôîðìàòà ïèêñåëåé 1, // Íîìåð âåðñèè PFD_DRAW_TO_WINDOW | // Ôîðìàò äëÿ Îêíà PFD_SUPPORT_OPENGL | // Ôîðìàò äëÿ OpenGL PFD_DOUBLEBUFFER, // Ôîðìàò äëÿ äâîéíîãî áóôåðà PFD_TYPE_RGBA, // Òðåáóåòñÿ RGBA ôîðìàò bits, // Âûáèðàåòñÿ áèò ãëóáèíû öâåòà 0, 0, 0, 0, 0, 0, // Èãíîðèðîâàíèå öâåòîâûõ áèòîâ 0, // Íåò áóôåðà ïðîçðà÷íîñòè 0, // Ñäâèãîâûé áèò èãíîðèðóåòñÿ 0, // Íåò áóôåðà íàêîïëåíèÿ 0, 0, 0, 0, // Áèòû íàêîïëåíèÿ èãíîðèðóþòñÿ 32, // 32 áèòíûé Z-áóôåð (áóôåð ãëóáèíû) 0, // Íåò áóôåðà òðàôàðåòà 0, // Íåò âñïîìîãàòåëüíûõ áóôåðîâ PFD_MAIN_PLANE, // Ãëàâíûé ñëîé ðèñîâàíèÿ 0, // Çàðåçåðâèðîâàíî 0, 0, 0 // Ìàñêè ñëîÿ èãíîðèðóþòñÿ }; if( !( hDC = GetDC( hWnd ) ) ) { // Ìîæåì ëè ìû ïîëó÷èòü Êîíòåêñò Óñòðîéñòâà? KillGLWindow(); // Âîññòàíîâèòü ýêðàí MessageBox( NULL, L"Can't Create A GL Device Context.", L"ERROR", MB_OK | MB_ICONEXCLAMATION ); return false; // Âåðíóòü false } if( !( PixelFormat = ChoosePixelFormat( hDC, &pfd ) ) ) // Íàéäåí ëè ïîäõîäÿùèé ôîðìàò ïèêñåëÿ? { KillGLWindow(); // Âîññòàíîâèòü ýêðàí MessageBox( NULL, L"Can't Find A Suitable PixelFormat.", L"ERROR", MB_OK | MB_ICONEXCLAMATION ); return false; // Âåðíóòü false } if( !SetPixelFormat( hDC, PixelFormat, &pfd ) ) // Âîçìîæíî ëè óñòàíîâèòü Ôîðìàò Ïèêñåëÿ? { KillGLWindow(); // Âîññòàíîâèòü ýêðàí MessageBox( NULL, L"Can't Set The PixelFormat.", L"ERROR", MB_OK | MB_ICONEXCLAMATION ); return false; // Âåðíóòü false } if( !( hRC = wglCreateContext( hDC ) ) ) // Âîçìîæíî ëè óñòàíîâèòü Êîíòåêñò Ðåíäåðèíãà? { KillGLWindow(); // Âîññòàíîâèòü ýêðàí MessageBox( NULL, L"Can't Create A GL Rendering Context.", L"ERROR", MB_OK | MB_ICONEXCLAMATION); return false; // Âåðíóòü false } if( !wglMakeCurrent( hDC, hRC ) ) // Ïîïðîáîâàòü àêòèâèðîâàòü Êîíòåêñò Ðåíäåðèíãà { KillGLWindow(); // Âîññòàíîâèòü ýêðàí MessageBox( NULL, L"Can't Activate The GL Rendering Context.", L"ERROR", MB_OK | MB_ICONEXCLAMATION ); return false; // Âåðíóòü false } ShowWindow( hWnd, SW_SHOW ); // Ïîêàçàòü îêíî SetForegroundWindow( hWnd ); // Ñëåãêà ïîâûñèì ïðèîðèòåò SetFocus( hWnd ); // Óñòàíîâèòü ôîêóñ êëàâèàòóðû íà íàøå îêíî ReSizeGLScene( width, height ); // Íàñòðîèì ïåðñïåêòèâó äëÿ íàøåãî OpenGL ýêðàíà. if( !InitGL() ) // Èíèöèàëèçàöèÿ òîëüêî ÷òî ñîçäàííîãî îêíà { KillGLWindow(); // Âîññòàíîâèòü ýêðàí MessageBox( NULL, _T("Initialization Failed."), _T("ERROR"), MB_OK | MB_ICONEXCLAMATION ); return false; // Âåðíóòü false } return true; }
void PlatformRestoreDesktopDisplayMode() { ChangeDisplaySettings(NULL, 0); }
static void RestoreQ2Settings (void) { if (ChangeDisplaySettings( &fullScreenMode, CDS_FULLSCREEN ) != DISP_CHANGE_SUCCESSFUL ) PrintWinError("Couldn't restore Quake 2 display settings - ChangeDisplaySettings", true); }
static void RestoreDesktopSettings (void) { if (ChangeDisplaySettings( &originalDesktopMode, CDS_FULLSCREEN ) != DISP_CHANGE_SUCCESSFUL ) PrintWinError("Couldn't restore desktop display settings - ChangeDisplaySettings", true); }
bool GameSystem::InitializeWindows(int& screenWidth, int& screenHeight) { WNDCLASSEX wndClass = { 0 }; DEVMODE dmScreenSettings; int posX, posY; ApplicationHandle = this; m_hInstance = GetModuleHandle(NULL); m_applicationName = L"Cavalcade"; wndClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wndClass.lpfnWndProc = WndProc; wndClass.cbClsExtra = 0; wndClass.cbWndExtra = 0; wndClass.hInstance = m_hInstance; wndClass.hIcon = LoadIcon(NULL, IDI_WINLOGO); wndClass.hIconSm = wndClass.hIcon; wndClass.hCursor = LoadCursor(NULL, IDC_ARROW); wndClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wndClass.lpszMenuName = 0; wndClass.lpszClassName = m_applicationName; wndClass.cbSize = sizeof(WNDCLASSEX); RegisterClassEx(&wndClass); screenWidth = GetSystemMetrics(SM_CXSCREEN); screenHeight = GetSystemMetrics(SM_CYSCREEN); //RECT rc; if (FULLSCREEN_ENABLED) { /* rc.top = 0; rc.left = 0; rc.right = screenWidth; rc.bottom = screenHeight; AdjustWindowRect(&rc, WS_EX_APPWINDOW, FALSE); m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP, CW_USEDEFAULT, CW_USEDEFAULT, screenWidth, screenHeight, NULL, NULL, m_hInstance, NULL); */ memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); //ZeroMemory(&dmScreenSettings, sizeof(dmScreenSettings)); dmScreenSettings.dmSize = sizeof(dmScreenSettings); //dmScreenSettings.dmPosition = dmPos; // Use for multi-monitor support dmScreenSettings.dmPelsWidth = (unsigned long)screenWidth; dmScreenSettings.dmPelsHeight = (unsigned long)screenHeight; dmScreenSettings.dmBitsPerPel = 32; dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN); posX = 0; posY = 0; } else { /* rc.top = 0; rc.left = 0; rc.right = 800; rc.bottom = 600; AdjustWindowRect(&rc, WS_OVERLAPPEDWINDOW, FALSE); m_hwnd = CreateWindowEx(WS_EX_OVERLAPPEDWINDOW, m_applicationName, m_applicationName, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP, CW_USEDEFAULT, CW_USEDEFAULT, rc.right, rc.bottom, NULL, NULL, m_hInstance, NULL); */ screenWidth = 800; screenHeight = 600; posX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth) / 2; posY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2; } m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP, posX, posY, screenWidth, screenHeight, NULL, NULL, m_hInstance, NULL); if (!m_hwnd) { MessageBox(m_hwnd, L"Error creating window.\n", L"Error", MB_OK); return false; } // Register raw input devices immediately after creating the window RAWINPUTDEVICE rid[2]; // Keyboard rid[0].usUsagePage = 1; rid[0].usUsage = 6; rid[0].dwFlags = 0; // Change to RIDEV_NOLEGACY when ESC supported rid[0].hwndTarget = NULL; // Mouse rid[1].usUsagePage = 1; rid[1].usUsage = 2; rid[1].dwFlags = RIDEV_NOLEGACY; rid[1].hwndTarget = NULL; if (RegisterRawInputDevices(rid,2,sizeof(RAWINPUTDEVICE))==FALSE) { return false; // Handle error; call GetLastError for details } ShowWindow(m_hwnd, SW_SHOW); SetForegroundWindow(m_hwnd); SetFocus(m_hwnd); SetCapture(m_hwnd); ShowCursor(true); return true; }
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag) { GLuint PixelFormat; // 保存查找匹配的结果 WNDCLASS wc; // 窗口类结构 DWORD dwExStyle; // 扩展窗口风格 DWORD dwStyle; // 窗口风格 RECT WindowRect; // 取得矩形的左上角和右下角的坐标值 WindowRect.left=(long)0; // 将Left 设为 0 WindowRect.right=(long)width; // 将Right 设为要求的宽度 WindowRect.top=(long)0; // 将Top 设为 0 WindowRect.bottom=(long)height; // 将Bottom 设为要求的高度 fullscreen=fullscreenflag; // 设置全局全屏标志 hInstance = GetModuleHandle(NULL); // 取得我们窗口的实例 wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC;// 移动时重画,并为窗口取得DC wc.lpfnWndProc = (WNDPROC) WndProc; // 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; // GL不需要背景 wc.lpszMenuName = NULL; // 不需要菜单 wc.lpszClassName = "OpenG"; // 设定类名字 if (!RegisterClass(&wc)) // 尝试注册窗口类 { MessageBox(NULL, "注册窗口失败", "错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 退出并返回FALSE } if (fullscreen) // 要尝试全屏模式吗? { DEVMODE dmScreenSettings; // 设备模式 memset(&dmScreenSettings,0,sizeof(dmScreenSettings));// 确保内存清空为零 dmScreenSettings.dmSize=sizeof(dmScreenSettings);// Devmode 结构的大小 dmScreenSettings.dmPelsWidth = width; // 所选屏幕宽度 dmScreenSettings.dmPelsHeight = height; // 所选屏幕高度 dmScreenSettings.dmBitsPerPel = bits; // 每象素所选的色彩深度 dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; // 尝试设置显示模式并返回结果。注: CDS_FULLSCREEN 移去了状态条。 if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { // 若模式失败,提供两个选项:退出或在窗口内运行。 if (MessageBox(NULL, "全屏模式在当前显卡上设置失败!\n使用窗口模式?", "NeHe G",MB_YESNO|MB_ICONEXCLAMATION)==IDYES) { fullscreen=FALSE; // 选择窗口模式(Fullscreen=FALSE) } else { // 弹出一个对话框,告诉用户程序结束 MessageBox(NULL, "程序将被关闭", "错误",MB_OK|MB_ICONSTOP); return FALSE; // 退出并返回 FALSE } } } if (fullscreen) // 仍处于全屏模式吗? { dwExStyle=WS_EX_APPWINDOW; // 扩展窗体风格 dwStyle=WS_POPUP; // 窗体风格 ShowCursor(FALSE); // 隐藏鼠标指针 } else { dwExStyle=WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; // 扩展窗体风格 dwStyle=WS_OVERLAPPEDWINDOW; // 窗体风格 } AdjustWindowRectEx(&WindowRect, dwStyle, FALSE, dwExStyle);// 调整窗口达到真正要求的大小 if (!(hWnd=CreateWindowEx( dwExStyle, // 扩展窗体风格 "OpenG", // 类名字 title, // 窗口标题 WS_CLIPSIBLINGS | // 必须的窗体风格属性 WS_CLIPCHILDREN | // 必须的窗体风格属性 dwStyle, // 选择的窗体属性 0, 0, // 窗口位置 WindowRect.right-WindowRect.left, // 计算调整好的窗口宽度 WindowRect.bottom-WindowRect.top, // 计算调整好的窗口高度 NULL, // 无父窗口 NULL, // 无菜单 hInstance, // 实例 NULL))) // 不向WM_CREATE传递任何东东 { KillGLWindow(); // 重置显示区 MessageBox(NULL, "不能创建一个窗口设备描述表", "错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 FALSE } static PIXELFORMATDESCRIPTOR pfd= // /pfd 告诉窗口我们所希望的东东,即窗口使用的像素格式 { sizeof(PIXELFORMATDESCRIPTOR), // 上述格式描述符的大小 1, // 版本号 PFD_DRAW_TO_WINDOW | // 格式支持窗口 PFD_SUPPORT_OPENGL | // 格式必须支持OpenGL PFD_DOUBLEBUFFER, // 必须支持双缓冲 PFD_TYPE_RGBA, // 申请 RGBA 格式 bits, // 选定色彩深度 0, 0, 0, 0, 0, 0, // 忽略的色彩位 0, // 无Alpha缓存 0, // 忽略Shift Bit 0, // 无累加缓存 0, 0, 0, 0, // 忽略聚集位 16, // 16位 Z-缓存 (深度缓存) 0, // 无蒙板缓存 0, // 无辅助缓存 PFD_MAIN_PLANE, // 主绘图层 0, // Reserved 0, 0, 0 // 忽略层遮罩 }; if (!(hDC=GetDC(hWnd))) // 取得设备描述表了么? { KillGLWindow(); // 重置显示区 MessageBox(NULL, "不能创建一种相匹配的像素格式", "错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 FALSE } if (!(PixelFormat=ChoosePixelFormat(hDC,&pfd)))// Windows 找到相应的象素格式了吗? { KillGLWindow(); // 重置显示区 MessageBox(NULL, "不能设置像素格式", "错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 FALSE } if(!SetPixelFormat(hDC,PixelFormat,&pfd)) // 能够设置象素格式么? { KillGLWindow(); // 重置显示区 MessageBox(NULL, "不能设置像素格式", "错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 FALSE } if (!(hRC=wglCreateContext(hDC))) // 能否取得着色描述表? { KillGLWindow(); // 重置显示区 MessageBox(NULL, "不能创建OpenGL渲染描述表", "错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 FALSE } if (!(hRC=wglCreateContext(hDC))) // 能否取得着色描述表? { KillGLWindow(); // 重置显示区 MessageBox(NULL, "不能创建OpenGL渲染描述表", "错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 FALSE } if(!wglMakeCurrent(hDC,hRC)) // 尝试激活着色描述表 { KillGLWindow(); // 重置显示区 MessageBox(NULL, "不能激活当前的OpenGL渲然描述表", "错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 FALSE } ShowWindow(hWnd,SW_SHOW); // 显示窗口 SetForegroundWindow(hWnd); // 略略提高优先级 SetFocus(hWnd); // 设置键盘的焦点至此窗口 ReSizeGLScene(width, height); // 设置透视 GL 屏幕 if (!InitGL()) // 初始化新建的GL窗口 { KillGLWindow(); // 重置显示区 MessageBox(NULL, "Initialization Failed.", "ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 FALSE } return TRUE; // 成功 }
// return to desktop at original resolution void Window::endFullScreen() { ChangeDisplaySettings(NULL, 0); }
void SysRecoverDisplayMode() { ChangeDisplaySettings( NULL, 0 ); }
LRESULT CALLBACK WndProc( HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { RECT Screen; // используется позднее для размеров окна GLuint PixelFormat; static PIXELFORMATDESCRIPTOR pfd= { sizeof(PIXELFORMATDESCRIPTOR), // Размер этой структуры 1, // Номер версии (?) PFD_DRAW_TO_WINDOW |// Формат для Окна PFD_SUPPORT_OPENGL |// Формат для OpenGL PFD_DOUBLEBUFFER,// Формат для двойного буфера PFD_TYPE_RGBA, // Требуется RGBA формат 16, // Выбор 16 бит глубины цвета 0, 0, 0, 0, 0, 0,// Игнорирование цветовых битов (?) 0, // нет буфера прозрачности 0, // Сдвиговый бит игнорируется (?) 0, // Нет буфера аккумуляции 0, 0, 0, 0, // Биты аккумуляции игнорируются (?) 16, // 16 битный Z-буфер (буфер глубины) 0, // Нет буфера траффарета 0, // Нет вспомогательных буферов (?) PFD_MAIN_PLANE, // Главный слой рисования 0, // Резерв (?) 0, 0, 0 // Маски слоя игнорируются (?) }; switch (message) // Тип сообщения { case WM_CREATE: hDC = GetDC(hWnd); // Получить контекст устройства для окна PixelFormat = ChoosePixelFormat(hDC, &pfd); // Найти ближайшее совпадение для нашего формата пикселов if (!PixelFormat) { MessageBox(0,"Can't Find A Suitable PixelFormat.","Error",MB_OK|MB_ICONERROR); PostQuitMessage(0); // Это сообщение говорит, что программа должна завершится break; // Предтовращение повтора кода } if(!SetPixelFormat(hDC,PixelFormat,&pfd)) { MessageBox(0,"Can't Set The PixelFormat.","Error",MB_OK|MB_ICONERROR); PostQuitMessage(0); break; } hRC = wglCreateContext(hDC); if(!hRC) { MessageBox(0,"Can't Create A GL Rendering Context.","Error",MB_OK|MB_ICONERROR); PostQuitMessage(0); break; } if(!wglMakeCurrent(hDC, hRC)) { MessageBox(0,"Can't activate GLRC.","Error",MB_OK|MB_ICONERROR); PostQuitMessage(0); break; } GetClientRect(hWnd, &Screen); InitGL(Screen.right, Screen.bottom); break; case WM_DESTROY: case WM_CLOSE: ChangeDisplaySettings(NULL, 0); wglMakeCurrent(hDC,NULL); wglDeleteContext(hRC); ReleaseDC(hWnd,hDC); PostQuitMessage(0); break; case WM_KEYDOWN: keys[wParam] = TRUE; break; case WM_KEYUP: keys[wParam] = FALSE; break; case WM_SIZE: ReSizeGLScene(LOWORD(lParam),HIWORD(lParam)); break; default: return (DefWindowProc(hWnd, message, wParam, lParam)); } return (0); }
bool SkOSWindow::makeFullscreen() { if (fFullscreen) { return true; } #if SK_SUPPORT_GPU if (fHGLRC) { this->detachGL(); } #endif // SK_SUPPORT_GPU // This is hacked together from various sources on the web. It can certainly be improved and be // made more robust. // Save current window/resolution information. We do this in case we ever implement switching // back to windowed mode. fSavedWindowState.fZoomed = SkToBool(IsZoomed((HWND)fHWND)); if (fSavedWindowState.fZoomed) { SendMessage((HWND)fHWND, WM_SYSCOMMAND, SC_RESTORE, 0); } fSavedWindowState.fStyle = GetWindowLong((HWND)fHWND, GWL_STYLE); fSavedWindowState.fExStyle = GetWindowLong((HWND)fHWND, GWL_EXSTYLE); GetWindowRect((HWND)fHWND, &fSavedWindowState.fRect); DEVMODE currScreenSettings; memset(&currScreenSettings,0,sizeof(currScreenSettings)); currScreenSettings.dmSize = sizeof(currScreenSettings); EnumDisplaySettings(NULL, ENUM_CURRENT_SETTINGS, &currScreenSettings); fSavedWindowState.fScreenWidth = currScreenSettings.dmPelsWidth; fSavedWindowState.fScreenHeight = currScreenSettings.dmPelsHeight; fSavedWindowState.fScreenBits = currScreenSettings.dmBitsPerPel; fSavedWindowState.fHWND = fHWND; // Try different sizes to find an allowed setting? Use ChangeDisplaySettingsEx? static const int kWidth = 1280; static const int kHeight = 1024; DEVMODE newScreenSettings; memset(&newScreenSettings, 0, sizeof(newScreenSettings)); newScreenSettings.dmSize = sizeof(newScreenSettings); newScreenSettings.dmPelsWidth = kWidth; newScreenSettings.dmPelsHeight = kHeight; newScreenSettings.dmBitsPerPel = 32; newScreenSettings.dmFields = DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; if (ChangeDisplaySettings(&newScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { return false; } RECT WindowRect; WindowRect.left = 0; WindowRect.right = kWidth; WindowRect.top = 0; WindowRect.bottom = kHeight; ShowCursor(FALSE); AdjustWindowRectEx(&WindowRect, WS_POPUP, FALSE, WS_EX_APPWINDOW); HWND fsHWND = CreateWindowEx( WS_EX_APPWINDOW, fWinInit.fClass, NULL, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP, 0, 0, WindowRect.right-WindowRect.left, WindowRect.bottom-WindowRect.top, NULL, NULL, fWinInit.fInstance, NULL ); if (!fsHWND) { return false; } // Hide the old window and set the entry in the global mapping for this SkOSWindow to the // new HWND. ShowWindow((HWND)fHWND, SW_HIDE); gHwndToOSWindowMap.remove(fHWND); fHWND = fsHWND; gHwndToOSWindowMap.set(fHWND, this); this->updateSize(); fFullscreen = true; return true; }
void SystemClass::InitializeWindows(int& screenWidth, int& screenHeight) { WNDCLASSEX wc; DEVMODE dmScreenSettings; int posX, posY; // Get an external pointer to this object. ApplicationHandle = this; // Get the instance of this application. m_hinstance = GetModuleHandle(NULL); // Give the application a name. m_applicationName = L"Engine"; // Setup the windows class with default settings. wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = m_hinstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hIconSm = wc.hIcon; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); wc.lpszMenuName = NULL; wc.lpszClassName = m_applicationName; wc.cbSize = sizeof(WNDCLASSEX); // Register the window class. RegisterClassEx(&wc); // Determine the resolution of the clients desktop screen. screenWidth = GetSystemMetrics(SM_CXSCREEN); screenHeight = GetSystemMetrics(SM_CYSCREEN); // Setup the screen settings depending on whether it is running in full screen or in windowed mode. if(FULL_SCREEN) { // If full screen set the screen to maximum size of the users desktop and 32bit. memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); dmScreenSettings.dmSize = sizeof(dmScreenSettings); dmScreenSettings.dmPelsWidth = (unsigned long)screenWidth; dmScreenSettings.dmPelsHeight = (unsigned long)screenHeight; dmScreenSettings.dmBitsPerPel = 32; dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // Change the display settings to full screen. ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN); // Set the position of the window to the top left corner. posX = posY = 0; } else { // If windowed then set it to 800x600 resolution. screenWidth = 800; screenHeight = 600; // Place the window in the middle of the screen. posX = (GetSystemMetrics(SM_CXSCREEN) - screenWidth) / 2; posY = (GetSystemMetrics(SM_CYSCREEN) - screenHeight) / 2; } // Create the window with the screen settings and get the handle to it. m_hwnd = CreateWindowEx(WS_EX_APPWINDOW, m_applicationName, m_applicationName, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP, posX, posY, screenWidth, screenHeight, NULL, NULL, m_hinstance, NULL); // Bring the window up on the screen and set it as main focus. ShowWindow(m_hwnd, SW_SHOW); SetForegroundWindow(m_hwnd); SetFocus(m_hwnd); // Hide the mouse cursor. ShowCursor(false); return; }
/* ** GLimp_SetMode */ rserr_t GLimp_SetMode ( int *pwidth, int *pheight, int mode, qboolean fullscreen ) { int width, height; const char *win_fs[] = { "W", "FS" }; VID_Printf( PRINT_ALL, "Initializing OpenGL display\n"); VID_Printf (PRINT_ALL, "...setting mode %d:", mode ); if ( !VID_GetModeInfo( &width, &height, mode ) ) { VID_Printf( PRINT_ALL, " invalid mode\n" ); return rserr_invalid_mode; } VID_Printf( PRINT_ALL, " %dx%d %s\n", width, height, win_fs[fullscreen] ); // destroy the existing window if (glw_state.hWnd) { GLimp_Shutdown (); } // do a CDS if needed if ( fullscreen ) { DEVMODE dm; VID_Printf( PRINT_ALL, "...attempting fullscreen\n" ); memset( &dm, 0, sizeof( dm ) ); dm.dmSize = sizeof( dm ); dm.dmPelsWidth = width; dm.dmPelsHeight = height; dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT; if ( r_bitdepth->value != 0 ) { dm.dmBitsPerPel = r_bitdepth->value; dm.dmFields |= DM_BITSPERPEL; VID_Printf( PRINT_ALL, "...using r_bitdepth of %d\n", ( int ) r_bitdepth->value ); } else { HDC hdc = GetDC( NULL ); int bitspixel = GetDeviceCaps( hdc, BITSPIXEL ); VID_Printf( PRINT_ALL, "...using desktop display depth of %d\n", bitspixel ); ReleaseDC( 0, hdc ); } VID_Printf( PRINT_ALL, "...calling CDS: " ); if ( ChangeDisplaySettings( &dm, CDS_FULLSCREEN ) == DISP_CHANGE_SUCCESSFUL ) { *pwidth = width; *pheight = height; gl_state.fullscreen = true; VID_Printf( PRINT_ALL, "ok\n" ); if ( !VID_CreateWindow (width, height, true) ) return rserr_invalid_mode; return rserr_ok; } else { *pwidth = width; *pheight = height; VID_Printf( PRINT_ALL, "failed\n" ); VID_Printf( PRINT_ALL, "...calling CDS assuming dual monitors:" ); dm.dmPelsWidth = width * 2; dm.dmPelsHeight = height; dm.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT; if ( r_bitdepth->value != 0 ) { dm.dmBitsPerPel = r_bitdepth->value; dm.dmFields |= DM_BITSPERPEL; } /* ** our first CDS failed, so maybe we're running on some weird dual monitor ** system */ if ( ChangeDisplaySettings( &dm, CDS_FULLSCREEN ) != DISP_CHANGE_SUCCESSFUL ) { VID_Printf( PRINT_ALL, " failed\n" ); VID_Printf( PRINT_ALL, "...setting windowed mode\n" ); ChangeDisplaySettings( 0, 0 ); *pwidth = width; *pheight = height; gl_state.fullscreen = false; if ( !VID_CreateWindow (width, height, false) ) return rserr_invalid_mode; return rserr_invalid_fullscreen; } else { VID_Printf( PRINT_ALL, " ok\n" ); if ( !VID_CreateWindow (width, height, true) ) return rserr_invalid_mode; gl_state.fullscreen = true; return rserr_ok; } } } else { VID_Printf( PRINT_ALL, "...setting windowed mode\n" ); ChangeDisplaySettings( 0, 0 ); *pwidth = width; *pheight = height; gl_state.fullscreen = false; if ( !VID_CreateWindow (width, height, false) ) return rserr_invalid_mode; } return rserr_ok; }
void SystemClass::InitializeWindows(int &_ScreenWidth, int &_ScreenHeight) { WNDCLASSEX WindowClass; DEVMODE ScreenSettings; int PosX, PosY; ApplicationHandle = this; m_Instance = GetModuleHandle(NULL); m_ApplicationName = L"Project Potato"; WindowClass.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; WindowClass.lpfnWndProc = WndProc; WindowClass.cbClsExtra = 0; WindowClass.cbWndExtra = 0; WindowClass.hInstance = m_Instance; WindowClass.hIcon = LoadIcon(NULL, IDI_WINLOGO); WindowClass.hIconSm = WindowClass.hIcon; WindowClass.hCursor = LoadCursor(NULL, IDC_ARROW); WindowClass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); WindowClass.lpszMenuName = NULL; WindowClass.lpszClassName = m_ApplicationName; WindowClass.cbSize = sizeof(WNDCLASSEX); RegisterClassEx(&WindowClass); _ScreenWidth = GetSystemMetrics(SM_CXSCREEN); _ScreenHeight = GetSystemMetrics(SM_CYSCREEN); if(FULL_SCREEN) { memset(&ScreenSettings, 0, sizeof(ScreenSettings)); ScreenSettings.dmSize = sizeof(ScreenSettings); ScreenSettings.dmPelsWidth = (unsigned long)_ScreenWidth; ScreenSettings.dmPelsHeight = (unsigned long)_ScreenHeight; ScreenSettings.dmBitsPerPel = 32; ScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; ChangeDisplaySettings(&ScreenSettings, CDS_FULLSCREEN); PosX = PosY = 0; } else { _ScreenWidth = 800; _ScreenHeight = 600; PosX = (GetSystemMetrics(SM_CXSCREEN) - _ScreenWidth) / 2; PosY = (GetSystemMetrics(SM_CYSCREEN) - _ScreenHeight) / 2; } m_WindowHandle = CreateWindowEx(WS_EX_APPWINDOW, m_ApplicationName, m_ApplicationName, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | WS_POPUP, PosX, PosY, _ScreenWidth, _ScreenHeight, NULL,NULL, m_Instance, NULL); ShowWindow(m_WindowHandle, SW_SHOW); SetForegroundWindow(m_WindowHandle); SetFocus(m_WindowHandle); ShowCursor(false); }
void GLimp_Shutdown( void ) { //Knightmare- added Vic's hardware gamma ramp if ( !r_ignorehwgamma->value ) { if( qwglSetDeviceGammaRamp3DFX ) { WORD newramp[3*256]; int j; for( j = 0; j < 256; j++ ) { newramp[j+0] = original_ramp[0][j]; newramp[j+256] = original_ramp[1][j]; newramp[j+512] = original_ramp[2][j]; } qwglSetDeviceGammaRamp3DFX ( glw_state.hDC, newramp ); } else { SetDeviceGammaRamp (glw_state.hDC, original_ramp); } } //end Knightmare if ( qwglMakeCurrent && !qwglMakeCurrent( NULL, NULL ) ) VID_Printf( PRINT_ALL, "ref_gl::R_Shutdown() - wglMakeCurrent failed\n"); if ( glw_state.hGLRC ) { if ( qwglDeleteContext && !qwglDeleteContext( glw_state.hGLRC ) ) VID_Printf( PRINT_ALL, "ref_gl::R_Shutdown() - wglDeleteContext failed\n"); glw_state.hGLRC = NULL; } if (glw_state.hDC) { if ( !ReleaseDC( glw_state.hWnd, glw_state.hDC ) ) VID_Printf( PRINT_ALL, "ref_gl::R_Shutdown() - ReleaseDC failed\n" ); glw_state.hDC = NULL; } if (glw_state.hWnd) { //Knightmare- remove leftover button on taskbar ShowWindow (glw_state.hWnd, SW_HIDE); //end Knightmare DestroyWindow ( glw_state.hWnd ); glw_state.hWnd = NULL; } if ( glw_state.log_fp ) { fclose( glw_state.log_fp ); glw_state.log_fp = 0; } UnregisterClass (WINDOW_CLASS_NAME, glw_state.hInstance); if ( gl_state.fullscreen ) { ChangeDisplaySettings( 0, 0 ); gl_state.fullscreen = false; } }
/* ** GLimp_Shutdown ** ** This routine does all OS specific shutdown procedures for the OpenGL ** subsystem. */ void GLimp_Shutdown( void ) { // const char *strings[] = { "soft", "hard" }; const char *success[] = { "failed", "success" }; int retVal; // FIXME: Brian, we need better fallbacks from partially initialized failures if ( !qwglMakeCurrent ) { return; } ri.Printf( PRINT_ALL, "Shutting down OpenGL subsystem\n" ); // restore gamma. We do this first because 3Dfx's extension needs a valid OGL subsystem WG_RestoreGamma(); // set current context to NULL if ( qwglMakeCurrent ) { retVal = qwglMakeCurrent( NULL, NULL ) != 0; ri.Printf( PRINT_ALL, "...wglMakeCurrent( NULL, NULL ): %s\n", success[retVal] ); } // delete HGLRC if ( glw_state.hGLRC ) { retVal = qwglDeleteContext( glw_state.hGLRC ) != 0; ri.Printf( PRINT_ALL, "...deleting GL context: %s\n", success[retVal] ); glw_state.hGLRC = NULL; } // release DC if ( glw_state.hDC ) { retVal = ReleaseDC( g_wv.hWnd, glw_state.hDC ) != 0; ri.Printf( PRINT_ALL, "...releasing DC: %s\n", success[retVal] ); glw_state.hDC = NULL; } // destroy window if ( g_wv.hWnd ) { ri.Printf( PRINT_ALL, "...destroying window\n" ); ShowWindow( g_wv.hWnd, SW_HIDE ); DestroyWindow( g_wv.hWnd ); g_wv.hWnd = NULL; glw_state.pixelFormatSet = qfalse; } // close the r_logFile if ( glw_state.log_fp ) { fclose( glw_state.log_fp ); glw_state.log_fp = 0; } // reset display settings if ( glw_state.cdsFullscreen ) { ri.Printf( PRINT_ALL, "...resetting display\n" ); ChangeDisplaySettings( 0, 0 ); glw_state.cdsFullscreen = qfalse; } // shutdown QGL subsystem QGL_Shutdown(); memset( &glConfig, 0, sizeof( glConfig ) ); memset( &glState, 0, sizeof( glState ) ); }
////////////////////////////////////////////////////////////////////////////// // Program Entry Point ////////////////////////////////////////////////////////////////////////////// int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { ///////////////////////////////////////////// // Do any program wide Initialization here // Change display settings if(glRenderer.GetFullScreen() == GL_TRUE) { gDevMode.dmPelsHeight = glRenderer.GetHeight(); gDevMode.dmPelsWidth = glRenderer.GetWidth(); gDevMode.dmSize = sizeof(DEVMODE); gDevMode.dmFields = DM_PELSWIDTH | DM_PELSHEIGHT; if(ChangeDisplaySettings(&gDevMode, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { MessageBox(NULL, TEXT("Cannot change to selected desktop resolution."), NULL, MB_OK | MB_ICONSTOP); return -1; } } ///////////////////////////////////////////// // Create Main Window. WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wcex.lpfnWndProc = (WNDPROC)MainWndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = NULL; wcex.hCursor = (HCURSOR)LoadCursor(NULL, IDC_ARROW); wcex.hbrBackground = NULL; //(HBRUSH)GetStockObject(BLACK_BRUSH); wcex.lpszMenuName = NULL; wcex.lpszClassName = TEXT("OpenGLWin32Window"); // Should be unique wcex.hIconSm = NULL; if(RegisterClassEx(&wcex) == 0) return -1; // Select window styles UINT uiStyle,uiStyleX; if(glRenderer.GetFullScreen() == GL_TRUE) { uiStyle = WS_POPUP; uiStyleX = WS_EX_TOPMOST; } else { uiStyle = WS_OVERLAPPEDWINDOW; uiStyleX = NULL; } // Create the main 3D window ghMainWnd = CreateWindowEx(uiStyleX, wcex.lpszClassName, szGameName, uiStyle, 0, 0, glRenderer.GetWidth(), glRenderer.GetHeight(), NULL, NULL, hInstance, NULL); if (!ghMainWnd) return -1; // Make sure window manager stays hidden ShowWindow(ghMainWnd, SW_SHOW); UpdateWindow(ghMainWnd); //SetFocus(ghMainWnd); ///////////////////////////////////////////// // Message Pump - Use the form that goes idle and waits for // messages, not continually running. MSG msg; while(GetMessage(&msg, NULL, 0, 0)) { if(!TranslateMessage(&msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } ///////////////////////////////////////////// // Do any program wide shutdown here // Restore Display Settings if(glRenderer.GetFullScreen() == GL_TRUE) ChangeDisplaySettings(NULL, 0); // Return termination code return msg.wParam; }
void InitWindow(HINSTANCE hInstance) { // TODO: make it search all available configs and ask what to load from or something if(!cfg.LoadFromFile("default.cfg")) LogToFile("debug.log", "Failed to load config"); window_rect.left = 0; window_rect.right = cfg.scr_width; window_rect.top = 0; window_rect.bottom = cfg.scr_height; window_class.hInstance = hInstance; window_class.style = CS_VREDRAW | CS_HREDRAW | CS_OWNDC; window_class.lpfnWndProc = WndProc; window_class.cbClsExtra = 0; window_class.cbWndExtra = 0; window_class.hbrBackground = NULL; window_class.hIcon = LoadIcon(NULL, IDI_WINLOGO); window_class.hCursor = LoadCursor(NULL, IDC_ARROW); window_class.lpszMenuName = NULL; window_class.lpszClassName = "OpenOrionClass"; fullscreenflag = cfg.fullscreen; if(!RegisterClass(&window_class)) { MessageBox(NULL, "Failed to register window class", "RegisterClass() Error", MB_OK | MB_ICONEXCLAMATION); LogToFile("debug.log", "Failed to register window class"); PostQuitMessage(-1); } if(cfg.fullscreen) { memset(&dmScreenSettings, 0, sizeof(dmScreenSettings)); // Очистка для хранения установок dmScreenSettings.dmSize = sizeof(dmScreenSettings); // Размер структуры Devmode dmScreenSettings.dmPelsWidth = cfg.scr_width; // Ширина экрана dmScreenSettings.dmPelsHeight = cfg.scr_height; // Высота экрана dmScreenSettings.dmBitsPerPel = cfg.scr_bpp; // Глубина цвета dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // Режим Пикселя DWORD disp; disp = ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN); switch(disp) { case DISP_CHANGE_SUCCESSFUL: { fullscreenflag = true; ShowCursor(true); break; } case DISP_CHANGE_BADDUALVIEW: { fullscreenflag = false; ShowCursor(true); LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADDUALVIEW)"); MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADDUALVIEW", MB_OK | MB_ICONEXCLAMATION); break; } case DISP_CHANGE_BADFLAGS: { fullscreenflag = false; ShowCursor(true); LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADFLAGS)"); MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADFLAGS", MB_OK | MB_ICONEXCLAMATION); break; } case DISP_CHANGE_BADMODE: { fullscreenflag = false; ShowCursor(true); LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADMODE)"); MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADMODE", MB_OK | MB_ICONEXCLAMATION); break; } case DISP_CHANGE_BADPARAM: { fullscreenflag = false; ShowCursor(true); LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_BADPARAM)"); MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_BADPARAM", MB_OK | MB_ICONEXCLAMATION); break; } case DISP_CHANGE_FAILED: { fullscreenflag = false; ShowCursor(true); LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_FAILED)"); MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_FAILED", MB_OK | MB_ICONEXCLAMATION); break; } case DISP_CHANGE_NOTUPDATED: { fullscreenflag = false; ShowCursor(true); LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_NOTUPDATED)"); MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_NOTUPDATED", MB_OK | MB_ICONEXCLAMATION); break; } case DISP_CHANGE_RESTART: { fullscreenflag = false; ShowCursor(true); LogToFile("Failed to set fullscreen mode: error (DISP_CHANGE_RESTART)"); MessageBox(NULL, "Failed to set fullscreen mode", "DISP_CHANGE_RESTART", MB_OK | MB_ICONEXCLAMATION); break; } } } if(fullscreenflag) { dwExStyle = WS_EX_APPWINDOW; //dwStyle = WS_OVERLAPPED; dwStyle = WS_POPUP; } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPED; } AdjustWindowRectEx(&window_rect, dwStyle, false, dwExStyle); game_window = CreateWindowEx(dwExStyle, window_class.lpszClassName, GAMENAME, WS_CLIPSIBLINGS | WS_CLIPCHILDREN | dwStyle, GetSystemMetrics(0) - GetSystemMetrics(0)/2 - window_rect.right / 2, GetSystemMetrics(1) - GetSystemMetrics(1)/2 - window_rect.bottom / 2, window_rect.right - window_rect.left, window_rect.bottom - window_rect.top, NULL, NULL, hInstance, NULL); if(!game_window) { LogToFile("debug.log","Failed to create game window"); MessageBox(NULL, "Failed to create game window", "CreateWindowEx() Error", MB_OK | MB_ICONEXCLAMATION); PostQuitMessage(-1); } pfd.nSize = sizeof(PIXELFORMATDESCRIPTOR); pfd.nVersion = 1; pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; pfd.iPixelType = PFD_TYPE_RGBA; pfd.cDepthBits = 24; pfd.iLayerType = PFD_MAIN_PLANE; pfd.cColorBits = cfg.scr_bpp; hDC = GetDC(game_window); if(!hDC) { LogToFile("debug.log","Failed to create device context"); MessageBox(NULL, "Failed to create device context", "GetDC() Error", MB_OK | MB_ICONEXCLAMATION); PostQuitMessage(-1); } pf = ChoosePixelFormat(hDC, &pfd); if(!pf) { LogToFile("debug.log","Failed to choose pixel format"); MessageBox(NULL, "Failed to set pixel format", "ChoosePixelFormat() Error", MB_OK | MB_ICONEXCLAMATION); PostQuitMessage(-1); } if(!SetPixelFormat(hDC, pf, &pfd)) { LogToFile("debug.log","Failed to set pixel format"); MessageBox(NULL, "Failed to set pixel format", "SetPixelFormat() Error", MB_OK | MB_ICONEXCLAMATION); PostQuitMessage(-1); } hRC = wglCreateContext(hDC); if(!hRC) { LogToFile("debug.log","Failed to create rendering context"); MessageBox(NULL, "Failed to create rendering context", "wglCreateContext() Error", MB_OK | MB_ICONEXCLAMATION); PostQuitMessage(-1); } if(!wglMakeCurrent(hDC, hRC)) { LogToFile("debug.log","Failed to make current context"); MessageBox(NULL, "Failed to make current context", "wglMakeCurrent() Error", MB_OK | MB_ICONEXCLAMATION); PostQuitMessage(-1); } ShowWindow(game_window, SW_SHOW); SetForegroundWindow(game_window); SetFocus(game_window); }
//================================================================================================== int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) //================================================================================================== { WNDCLASSEX windowClass; // window class HWND hwnd; // window handle MSG msg; // message bool done; // flag saying when our app is complete // MessageBox(NULL, "LeftButton+Mouse Move : zoom\nRightButton+Mouse Move : pan\nLeftButton+RightButton+Mouse Move : rotate\nESC : Exit\n\nAuthor: Dongsoo Han\nDate:2/20/08\nemail:[email protected]", "How to control camera", MB_OK); g_hInstance = hInstance; // fill out the window class structure windowClass.cbSize = sizeof(WNDCLASSEX); windowClass.style = CS_HREDRAW | CS_VREDRAW; windowClass.lpfnWndProc = WndProc; windowClass.cbClsExtra = 0; windowClass.cbWndExtra = 0; windowClass.hInstance = hInstance; windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); // default icon windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); // default arrow windowClass.hbrBackground = NULL; // don't need background windowClass.lpszMenuName = NULL; // no menu windowClass.lpszClassName = g_ClassName; windowClass.hIconSm = LoadIcon(NULL, IDI_WINLOGO); // windows logo small icon // register the windows class if (!RegisterClassEx(&windowClass)) return 0; //////////////////////////////////////////////////// // For fullscreen mode //////////////////////////////////////////////////// // if we're in fullscreen mode, set the display up for it if (g_isFullscreen) { // set up the device mode structure DEVMODE screenSettings; memset(&screenSettings,0,sizeof(screenSettings)); screenSettings.dmSize = sizeof(screenSettings); screenSettings.dmPelsWidth = width; // screen width screenSettings.dmPelsHeight = height; // screen height screenSettings.dmBitsPerPel = bits; // bits per pixel screenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; // attempt to switch to the resolution and bit depth we've selected if (ChangeDisplaySettings(&screenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { // if we can't get fullscreen, let them choose to quit or try windowed mode if (MessageBox(NULL, "Cannot run in the fullscreen mode at the selected resolution\n" "on your video card. Try windowed mode instead?", "OpenGL Game Programming", MB_YESNO | MB_ICONEXCLAMATION) == IDYES) { g_isFullscreen = FALSE; } else { return FALSE; } } } DWORD dwExStyle; DWORD dwStyle; // if we're still in fullscreen mode, set the window style appropriately if (g_isFullscreen) { dwExStyle = WS_EX_APPWINDOW; dwStyle = WS_POPUP; // simple window with no borders or title bar //ShowCursor(FALSE); // hide the cursor for now } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPEDWINDOW; //dwStyle = WS_POPUP; width = 900; height = 700; } // set up the window we're rendering to so that the top left corner is at (0,0) // and the bottom right corner is (height,width) RECT windowRect; windowRect.left = 0; windowRect.right = (LONG) width; windowRect.top = 0; windowRect.bottom = (LONG) height; // change the size of the rect to account for borders, etc. set by the style AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle); hwnd = CreateWindowEx(dwExStyle, // extended style (LPCTSTR)g_ClassName, // class name (LPCTSTR)g_WindowName, // app name dwStyle | // window style WS_CLIPCHILDREN | // required for WS_CLIPSIBLINGS, // using OpenGL 0, 0, // x,y coordinate windowRect.right - windowRect.left, // width windowRect.bottom - windowRect.top, // height NULL, // handle to parent NULL, // handle to menu hInstance, // application instance NULL); // no extra params if (!hwnd) { KillGLWindow(); MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; } if (!(g_hDC = GetDC(hwnd))) { KillGLWindow(); MessageBox(NULL,"Can't Create A GL Device Context.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; } SetupPixelFormat(g_hDC); // call our pixel format setup function // create rendering context and make it current g_hRC = wglCreateContext(g_hDC); wglMakeCurrent(g_hDC, g_hRC); g_hWnd = hwnd; ShowWindow(hwnd, SW_SHOW); // display the window UpdateWindow(hwnd); // update the window done = false; // intialize the loop condition variable Initialize(); // main message loop while (!done) { if(PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { if (msg.message == WM_QUIT) // do we receive a WM_QUIT message? { done = TRUE; // if so, time to quit the application } else { TranslateMessage(&msg); // translate and dispatch to event queue DispatchMessage(&msg); } } else { if(g_bEnd) done = TRUE; if(g_active) RenderFunc(); // display Frame/Second rate.. GetFPS(); glFlush(); SwapBuffers(g_hDC); // bring backbuffer to foreground } } KillGLWindow(); return msg.wParam; }
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 }
/* Main, in this program, is a more broad instantiation of the window. The global pointer now becomes an object of the CGFxOpenGL rendering class; the generalities of the window are established here, whereas above the details were specified. Most of this code is provided by the Windows.h file, therefore this section deals with setting values. Device content and rendering content are set, and appropriate CGFxOpenGL methods are called to draw the piano and/or set up the camera. */ int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nShowCmd) { WNDCLASSEX windowClass; //window class HWND hwnd; //window handle MSG msg; //message DWORD dwExStyle; //window extended style DWORD dwStyle; //window style RECT windowRect; g_glRender = new CGFxOpenGL; windowRect.left=(long)0; windowRect.right=(long)windowWidth; //set right val to requested width windowRect.top=(long)0; windowRect.bottom=(long)windowHeight; //set bottom val to requesetd height //fill out window class struct windowClass.cbSize =sizeof(WNDCLASSEX); windowClass.style =CS_HREDRAW | CS_VREDRAW; windowClass.lpfnWndProc =MainWindowProc; windowClass.cbClsExtra =0; windowClass.cbWndExtra =0; windowClass.hInstance =hInstance; windowClass.hIcon =LoadIcon(NULL, IDI_APPLICATION); //default icon windowClass.hCursor =LoadCursor(NULL, IDC_ARROW); //default cursor windowClass.hbrBackground=NULL; windowClass.lpszMenuName=NULL; windowClass.lpszClassName= L"Capstone"; windowClass.hIconSm =LoadIcon(NULL, IDI_WINLOGO); //register window class if(!RegisterClassEx(&windowClass)) return 0; if(fullscreen) { DEVMODE dmScreenSettings; memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); dmScreenSettings.dmSize = sizeof(dmScreenSettings); dmScreenSettings.dmPaperWidth =windowWidth; dmScreenSettings.dmPanningHeight = windowHeight; dmScreenSettings.dmBitsPerPel = windowBits; //bits per pixel dmScreenSettings.dmFields = DM_BITSPERPEL | DM_PELSWIDTH | DM_PELSHEIGHT; if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { //setting display mode failed, switch to windowed MessageBox(NULL, L"Failed", NULL, MB_OK); fullscreen = FALSE; } } if(fullscreen) { dwExStyle = WS_EX_APPWINDOW; dwStyle = WS_POPUP; ShowCursor(FALSE); } else { dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; dwStyle = WS_OVERLAPPEDWINDOW; } //adjust window to true requested size AdjustWindowRectEx(&windowRect, dwStyle, FALSE, dwExStyle); //class registered, create window hwnd = CreateWindowEx(NULL, //extended style L"Capstone", //class name L"Portable Piano", //app name dwStyle | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0,0, //x,y coordinate windowRect.right - windowRect.left, windowRect.bottom - windowRect.top, NULL, //handle to parent NULL, //handle to menu hInstance, //app instance NULL); //no extras hDC = GetDC(hwnd); //check if window creation failed (hwnd = NULL) if(!hwnd) return 0; ShowWindow(hwnd, SW_SHOW); UpdateWindow(hwnd); g_glRender->Init(); /* This is the execution loop; as long as the user does not exit the application, it will continually run. */ while(!exiting) { g_glRender->Render(curPos.x, curPos.y, 0); g_glRender->Prepare(); SwapBuffers(hDC); while (PeekMessage (&msg, NULL, 0, 0, PM_NOREMOVE)) { if(!GetMessage (&msg, NULL, 0, 0)) { exiting = true; break; } TranslateMessage (&msg); DispatchMessage (&msg); } } delete g_glRender; if(fullscreen) { ChangeDisplaySettings(NULL, 0); ShowCursor(TRUE); } return (int)msg.wParam; }