int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure BOOL done=FALSE; // Bool Variable To Exit Loop int lastTime = timeGetTime(); int thisTime; try { // Use exception handling // Ask The User Which Screen Mode They Prefer if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO) { fullscreen=FALSE; // Windowed Mode } // Create Our OpenGL Window if (!CreateGLWindow("The Basic Font API",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } while(!done) // Loop That Runs While done=FALSE { static int frame = 0; static float fpsTime = 0.0; thisTime = timeGetTime(); float elapsedTime = (float)(thisTime - lastTime)/1000; fpsTime+= elapsedTime; if(fpsTime > FPS_INTERVAL) { // displayTitle and Frame //DisplayTitle(hwnd, frame/fpsTime); static char message[255]; sprintf(message, "%s FPS: %.0f ","Font API without VBO" , frame/fpsTime); // change Font API to title bar text SetWindowText(hWnd, message); frame = 0; fpsTime -= FPS_INTERVAL; } lastTime = thisTime; if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=TRUE; // If So done=TRUE } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received? { done=TRUE; // ESC or DrawGLScene Signalled A Quit } else // Not Time To Quit, Update Screen { SwapBuffers(hDC); // Swap Buffers (Double Buffering) } if (keys[VK_F1]) // Is F1 Being Pressed? { keys[VK_F1]=FALSE; // If So Make Key FALSE KillGLWindow(); // Kill Our Current Window fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode // Recreate Our OpenGL Window if (!CreateGLWindow("Basic Font API",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } } } frame++; } // Shutdown KillGLWindow(); // Kill The Window //catch any exceptions that where thrown } catch (std::exception &e) { MessageBox(NULL,e.what(),"CAUGHT AN EXCEPTION",MB_OK | MB_ICONINFORMATION); } return (msg.wParam); // Exit The Program }
// 创建Render环境 int RenderClass::CreaterRender(const wchar_t *windows_name) { 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 设为要求的高度 hinstance_ = GetModuleHandle(NULL); // 取得我们窗口的实例 wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // 移动时重画,并为窗口取得DC wc.lpfnWndProc = (WNDPROC) window_sun_proc_; // 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 = L"OpenGL"; // 设定类名字 if (!RegisterClass(&wc)) // 尝试注册窗口类 { MessageBox(NULL,L"注册窗口失败",L"错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 退出并返回FALSE } if (full) // 要尝试全屏模式吗? { DEVMODE dmScreenSettings; // 设备模式 memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); // 确保内存清空为零 dmScreenSettings.dmSize=sizeof(dmScreenSettings); // Devmode 结构的大小 dmScreenSettings.dmPelsWidth = width_; // 所选屏幕宽度 dmScreenSettings.dmPelsHeight = height_; // 所选屏幕高度 dmScreenSettings.dmBitsPerPel = 32; // 每象素所选的色彩深度 dmScreenSettings.dmFields=DM_BITSPERPEL|DM_PELSWIDTH|DM_PELSHEIGHT; // 尝试设置显示模式并返回结果。注: CDS_FULLSCREEN 移去了状态条。 if (ChangeDisplaySettings(&dmScreenSettings,CDS_FULLSCREEN)!=DISP_CHANGE_SUCCESSFUL) { // 若模式失败,提供两个选项:退出或在窗口内运行。 if (MessageBox(NULL,L"全屏模式在当前显卡上设置失败!\n使用窗口模式?",L" G",MB_YESNO|MB_ICONEXCLAMATION)==IDYES) { full=FALSE; // 选择窗口模式(Fullscreen=FALSE) } else { // 弹出一个对话框,告诉用户程序结束 MessageBox(NULL,L"程序将被关闭",L"错误",MB_OK|MB_ICONSTOP); return FALSE; // 退出并返回 FALSE } } } if (full) // 仍处于全屏模式吗? { 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, // 扩展窗体风格 L"OpenGL", // 类名字 windows_name, // 窗口标题 WS_CLIPSIBLINGS | // 必须的窗体风格属性 WS_CLIPCHILDREN | // 必须的窗体风格属性 dwStyle, // 选择的窗体属性 0, 0, // 窗口位置 WindowRect.right-WindowRect.left, // 计算调整好的窗口宽度 WindowRect.bottom-WindowRect.top, // 计算调整好的窗口高度 NULL, // 无父窗口 NULL, // 无菜单 hinstance_, // 实例 NULL))) // 不向WM_CREATE传递任何东东 { KillGLWindow(); // 重置显示区 MessageBox(NULL,L"不能创建一个窗口设备描述表",L"错误",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 格式 32, // 选定色彩深度 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,L"不能创建一种相匹配的像素格式",L"错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 FALSE } if (!(PixelFormat=ChoosePixelFormat(hdc,&pfd))) // Windows 找到相应的象素格式了吗? { KillGLWindow(); // 重置显示区 MessageBox(NULL,L"不能设置像素格式",L"错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 FALSE } if(!SetPixelFormat(hdc,PixelFormat,&pfd)) // 能够设置象素格式么? { KillGLWindow(); // 重置显示区 MessageBox(NULL,L"不能设置像素格式",L"错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 FALSE } if (!(hrc=wglCreateContext(hdc))) // 能否取得着色描述表? { KillGLWindow(); // 重置显示区 MessageBox(NULL,L"不能创建OpenGL渲染描述表",L"错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 FALSE } if(!wglMakeCurrent(hdc,hrc)) // 尝试激活着色描述表 { KillGLWindow(); // 重置显示区 MessageBox(NULL,L"不能激活当前的OpenGL渲然描述表",L"错误",MB_OK|MB_ICONEXCLAMATION); return FALSE; // 返回 FALSE } ShowWindow(hwnd_,SW_SHOW); // 显示窗口 SetForegroundWindow(hwnd_); // 略略提高优先级 SetFocus(hwnd_); // 设置键盘的焦点至此窗口 ChangeWindowSize(width_, height_); // 设置透视 GL 屏幕 glewExperimental = GL_TRUE; GLenum err = glewInit(); // 初始化glew库,必须在glutCreateWindow之后调用 if(err != GLEW_OK) // 初始化不成功? { std::cout << "glewInit 失败, 退出程序." << std::endl; exit(EXIT_FAILURE); // 退出程序 } glClearColor(0.6f, 0.4f, 0.7f, 1.0f); //开启混合 glEnable(GL_BLEND); //设置混合模式 glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA); //质量最佳 glPolygonMode(GL_FRONT, GL_NICEST); return 0; }
bool CoreWindow::createWindow(int x, int y, int width, int height, const TCHAR* title, bool fullscreenmode) { WNDCLASS wc; HWND hWnd; DWORD dwExStyle; DWORD dwStyle; RECT WindowRect; WindowRect.left = 0; WindowRect.right = width; WindowRect.top = 0; WindowRect.bottom = height; dwExStyle = WS_EX_APPWINDOW | WS_EX_WINDOWEDGE; if (fullscreenmode) dwStyle = WS_POPUPWINDOW | WS_MAXIMIZE; else dwStyle = WS_OVERLAPPEDWINDOW | WS_CLIPCHILDREN | WS_CLIPSIBLINGS; AdjustWindowRect(&WindowRect, dwStyle, FALSE); if (!GetClassInfo(GetModuleHandle(NULL), _TX("CoreWindow_wgl"), &wc)) { // memset(&wcx, 0, sizeof(WNDCLASSEX)); // wcx.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (WNDPROC) CoreWindow::BaseWndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = GetModuleHandle(NULL); wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = 0; wc.lpszClassName = _TX("CoreWindow_wgl"); if (!RegisterClass(&wc)) { MessageBox(NULL,_TX("Failed To Register The Window Class."),_TX("ERROR"),MB_OK|MB_ICONEXCLAMATION); ExitProcess(0); return FALSE; } } hWnd = CreateWindowEx(dwExStyle, _TX("CoreWindow_wgl"), title, dwStyle, x, y, WindowRect.right - WindowRect.left, WindowRect.bottom - WindowRect.top, NULL, NULL, GetModuleHandle(NULL), (void*)this);//BaseWndProcにthisを渡してやる if (!hWnd) { KillGLWindow(); MessageBox(NULL,_TX("Window Creation Error."),_TX("ERROR"),MB_OK|MB_ICONEXCLAMATION); ExitProcess(0); return FALSE; } // ウィンドウハンドルとCWindowBaseオブジェクトを結びつける SetProp(hWnd, _TX("CoreWindow_wgl"), (HANDLE)this); m_hWnd = hWnd; if (!g_mainWin) g_mainWin = this; return TRUE; }
int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; BOOL done=FALSE; // Ask The User Which Screen Mode They Prefer if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO) { fullscreen=FALSE; // Windowed Mode } // Create Our OpenGL Window if (!CreateGLWindow("NeHe's Solid Object Tutorial",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } while(!done) { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) { if (msg.message==WM_QUIT) { done=TRUE; } else { TranslateMessage(&msg); DispatchMessage(&msg); } } else // If There Are No Messages { // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received? { done=TRUE; } else { SwapBuffers(hDC); } if (keys[VK_F1]) { keys[VK_F1]=FALSE; KillGLWindow(); fullscreen=!fullscreen; // Recreate Our OpenGL Window if (!CreateGLWindow("NeHe's Solid Object Tutorial",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } } } } // Shutdown KillGLWindow(); // Kill The Window return (msg.wParam); // Exit The Program }
int WINAPI WinMain(HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure BOOL done = FALSE; // Bool Variable To Exit Loop // Ask The User Which Screen Mode They Prefer if (MessageBox(NULL, "Would You Like To Run In Fullscreen Mode?", "Start FullScreen?", MB_YESNO | MB_ICONQUESTION) == IDNO) { fullscreen = FALSE; // Windowed Mode } // Create Our OpenGL Window if (!CreateGLWindow("Tom Stanis & NeHe's Blending Tutorial", 640, 480, 16, fullscreen)) { return 0; // Quit If Window Was Not Created } while (!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) // Is There A Message Waiting? { if (msg.message == WM_QUIT) // Have We Received A Quit Message? { done = TRUE; // If So done=TRUE } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received? { done = TRUE; // ESC or DrawGLScene Signalled A Quit } else // Not Time To Quit, Update Screen { SwapBuffers(hDC); // Swap Buffers (Double Buffering) if (keys['L'] && !lp) { lp = TRUE; light = !light; if (!light) { glDisable(GL_LIGHTING); } else { glEnable(GL_LIGHTING); } } if (!keys['L']) { lp = FALSE; } if (keys['F'] && !fp) { fp = TRUE; filter += 1; if (filter>2) { filter = 0; } } if (!keys['F']) { fp = FALSE; } if (keys[VK_PRIOR]) { z -= 0.02f; } if (keys[VK_NEXT]) { z += 0.02f; } if (keys[VK_UP]) { xspeed -= 0.01f; } if (keys[VK_DOWN]) { xspeed += 0.01f; } if (keys[VK_RIGHT]) { yspeed += 0.01f; } if (keys[VK_LEFT]) { yspeed -= 0.01f; } // Blending Code Starts Here if (keys['B'] && !bp) { bp = TRUE; blend = !blend; if (blend) { glEnable(GL_BLEND); // Turn Blending On glDisable(GL_DEPTH_TEST); // Turn Depth Testing Off } else { glDisable(GL_BLEND); // Turn Blending Off glEnable(GL_DEPTH_TEST); // Turn Depth Testing On } } if (!keys['B']) { bp = FALSE; } // Blending Code Ends Here if (keys[VK_F1]) // Is F1 Being Pressed? { keys[VK_F1] = FALSE; // If So Make Key FALSE KillGLWindow(); // Kill Our Current Window fullscreen = !fullscreen; // Toggle Fullscreen / Windowed Mode // Recreate Our OpenGL Window if (!CreateGLWindow("Tom Stanis & NeHe's Blending Tutorial", 640, 480, 16, fullscreen)) { return 0; // Quit If Window Was Not Created } } } } } // Shutdown KillGLWindow(); // Kill The Window return (msg.wParam); // Exit The Program }
BOOL OpenGLWindow::CreateGLWindow() { 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 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 = &OpenGLWindow::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 = (LPCWSTR)"OpenGL"; // Set The Class Name ::TlsSetValue(s_tlsIndex, this); if (!RegisterClass(&wc)) // Attempt To Register The Window Class { MessageBox(NULL,(LPCWSTR)"Failed To Register The Window Class.", (LPCWSTR)"ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } 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 (LPCWSTR)"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,(LPCWSTR)"Window Creation Error.",(LPCWSTR)"ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } DeleteMenu(GetSystemMenu(hWnd, false), SC_CLOSE, MF_BYCOMMAND); //Deactivate Closing by x-Button 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,(LPCWSTR)"Can't Create A GL Device Context.",(LPCWSTR)"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,(LPCWSTR)"Can't Find A Suitable PixelFormat.",(LPCWSTR)"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,(LPCWSTR)"Can't Set The PixelFormat.",(LPCWSTR)"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,(LPCWSTR)"Can't Create A GL Rendering Context.",(LPCWSTR)"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,(LPCWSTR)"Can't Activate The GL Rendering Context.",(LPCWSTR)"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(); // Set Up Our Perspective GL Screen if (!InitGL()) // Initialize Our Newly Created GL Window { KillGLWindow(); // Reset The Display MessageBox(NULL,(LPCWSTR)"Initialization Failed.",(LPCWSTR)"ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } return TRUE; // Success }
int WINAPI WinMain( HINSTANCE hInstance, // 当前窗口实例 HINSTANCE hPrevInstance, // 前一个窗口实例 LPSTR lpCmdLine, // 命令行参数 int nCmdShow) // 窗口显示状态 { MSG msg; // Windowsx消息结构 BOOL done=FALSE; // 用来退出循环的Bool 变量 // 提示用户选择运行模式 if (MessageBox(NULL,"你想在全屏模式下运行么?", "设置全屏模式",MB_YESNO|MB_ICONQUESTION)==IDNO) { fullscreen=FALSE; // FALSE为窗口模式 } // 创建OpenGL窗口 if (!CreateGLWindow("OpenGL程序加速样例",640,480,16,fullscreen)) { return 0; // 失败退出 } while(!done) // 保持循环直到 done=TRUE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE))// 有消息在等待吗? { if (msg.message==WM_QUIT) // 收到退出消息? { done=TRUE; // 是,则done=TRUE } else // 不是,处理窗口消息 { TranslateMessage(&msg); // 翻译消息 DispatchMessage(&msg); // 发送消息 } } else // 如果没有消息 { // 绘制场景。监视ESC键和来自DrawGLScene()的退出消息 if (active) // 程序激活的么? { if (keys[VK_ESCAPE]) // ESC 按下了么? { done=TRUE; // ESC 发出退出信号 } else // 不是退出的时候,刷新屏幕 { DrawGLScene(); // 绘制场景 SwapBuffers(hDC); // 交换缓存 (双缓存) if (keys[VK_LEFT]) // 左键是否按下 { yrot-=0.2f; // 如果是,向左旋转 } if (keys[VK_RIGHT]) // 右键是否按下 { yrot+=0.2f; // 如果是向右旋转 } if (keys[VK_UP]) // 上键是否按下 { xrot-=0.2f; // 如果是向上旋转 } if (keys[VK_DOWN]) // 下键是否按下 { xrot+=0.2f; // 如果是向下旋转 } } } if (keys[VK_F1]) // F1键按下了么? { keys[VK_F1]=FALSE; // 若是,使对应的Key数组中的值为 FALSE KillGLWindow(); // 销毁当前的窗口 fullscreen=!fullscreen; // 切换 全屏 / 窗口 模式 // 重建 OpenGL 窗口(修改) if (!CreateGLWindow("OpenGL旋转实例",640,480,16,fullscreen)) { return 0; // 如果窗口未能创建,程序退出 } } } } // 关闭程序 KillGLWindow(); // 销毁窗口 return (msg.wParam); // 退出程序 }
BOOL CreateGLWindow(HWND hWnd, HDC *phDC, HGLRC *phRC) { GLuint nPixelFormat; // Holds The Results After Searching For A Match RECT rect; 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 0, // 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 (!(*phDC = GetDC(hWnd))) // Did We Get A Device Context? { KillGLWindow(hWnd, *phDC, *phRC); // Reset The Display MessageBox(hWnd, _T("Can't Create A GL Device Context."), _T("ERROR"), MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(nPixelFormat = ChoosePixelFormat(*phDC, &pfd)))// Did Windows Find A Matching Pixel Format? { KillGLWindow(hWnd, *phDC, *phRC); // Reset The Display MessageBox(hWnd, _T("Can't Find A Suitable PixelFormat."), _T("ERROR"), MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!SetPixelFormat(*phDC, nPixelFormat, &pfd)) // Are We Able To Set The Pixel Format? { KillGLWindow(hWnd, *phDC, *phRC); // Reset The Display MessageBox(hWnd, _T("Can't Set The PixelFormat."), _T("ERROR"), MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!(*phRC = wglCreateContext(*phDC))) // Are We Able To Get A Rendering Context? { KillGLWindow(hWnd, *phDC, *phRC); // Reset The Display MessageBox(hWnd, _T("Can't Create A GL Rendering Context."), _T("ERROR"), MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (!wglMakeCurrent(*phDC, *phRC)) // Try To Activate The Rendering Context { KillGLWindow(hWnd, *phDC, *phRC); // Reset The Display MessageBox(hWnd, _T("Can't Activate The GL Rendering Context."), _T("ERROR"), MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } GetClientRect(hWnd, &rect); ReSizeGLScene(rect.right, rect.bottom); // Set Up Our Perspective GL Screen if (!InitGL()) // Initialize Our Newly Created GL Window { KillGLWindow(hWnd, *phDC, *phRC); // Reset The Display MessageBox(hWnd, _T("Initialization Failed."), _T("ERROR"), MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } return TRUE; // Success }
EXTERN_C LONG WINAPI ScreenSaverProc( HWND hWnd, // Handle For This Window UINT uMsg, // Message For This Window WPARAM wParam, // Additional Message Information LPARAM lParam) // Additional Message Information { static HDC hDC = NULL; // Private GDI Device Context static HGLRC hRC = NULL; // Permanent Rendering Context static int nState; static int nFrames; switch (uMsg) // Check For Windows Messages { case WM_CREATE: { // Load settings CCuckooSettings settings; settings.Load(); // Load clock switch (settings.GetClockType()) { case 2: // Mickey g_pClock = new CClockMickey; break; case 1: // Wesminster g_pClock = new CClockWestminster; break; case 0: // Cuckoo g_pClock = new CClockCuckoo; break; default: // Error MessageBox(hWnd, _T("Unknown clock: Please configure the screen saver.\n\nHorloge inconnue: Veuillez reconfigurer l'écran de veille."), _T("Cuckoo"), MB_ICONEXCLAMATION); return -1; } if (g_pClock == NULL) { MessageBox(hWnd, _T("Not enought memory to load the clock."), _T("Cuckoo"), MB_ICONERROR); return -1; } // Initialize OpenGL on hWnd. if (!CreateGLWindow(hWnd, &hDC, &hRC)) return -1; // Starting state nState = STATE_SWAP_TEST; // Set timers SetTimer(hWnd, 1, 10, NULL); return 0; } case WM_DESTROY: // Timers KillTimer(hWnd, 1); // Clock if (g_pClock != NULL) { delete g_pClock; g_pClock = NULL; } // OpenGL KillGLWindow(hWnd, hDC, hRC); return 0; case WM_TIMER: switch (nState) { case STATE_SWAP_TEST: // Check if SwapBuffers() swap or copy back to front if (IsSwapBufferCopyingBackToFront(hDC)) g_pClock->SetSwapBufferMode(CClock::COPY_BACK_TO_FRONT); else g_pClock->SetSwapBufferMode(CClock::SWAP_BACK_AND_FRONT); nState++; break; case STATE_INIT_CLOCK: { // Load settings CCuckooSettings settings; settings.Load(); // Clock g_pClock->EnableSounds(settings.HasTicTacSound(), settings.BellsOnHours(), settings.BellsOnHalfHours(), settings.BellsOnQuartHours()); g_pClock->Init(); // Precise timing g_swTimer.Init(); g_swTimer.Start(); // Frame counter nFrames = 0; nState++; break; } case STATE_RENDER: // Met à jour l'heure if (++nFrames > 4) { nFrames = 0; g_pClock->UpdateTime(); } // Affiche la scène DrawGLScene(); glFlush(); SwapBuffers(hDC); break; } return 0; case WM_SYSCOMMAND: if (wParam == SC_MONITORPOWER) { // Load settings CCuckooSettings settings; settings.Load(); if (settings.IsDisabledOnMonitorTurnOff()) PostQuitMessage(0); } } // Pass All Unhandled Messages To DefScreenSaverProc return DefScreenSaverProc(hWnd, uMsg, wParam, lParam); }
int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure BOOL done=FALSE; // Bool Variable To Exit Loop // Ask The User Which Screen Mode They Prefer fullscreen=true; // Fullscreen Mode if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO) { fullscreen=false; } // Create Our OpenGL Window if (!CreateGLWindow("Zombie City!",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } for(int i=0; i<256; ++i) { keys[i] = 0; } i_tick = float(GetTickCount()); //Set i_tick to the new tick count - so the difference does not exponentially increase while(!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=TRUE; // If So done=TRUE } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { do { } while (( GetTickCount() - i_tick ) < 10 ); framelength = (GetTickCount() - i_tick) * GAMESPEED; //When the frame starts, find out how many 'ticks' have occurred since the last frame if(framelength > 10.0f) framelength = 10.0f; leveltime += int(GetTickCount() - i_tick); i_tick = float(GetTickCount()); //Set i_tick to the new tick count - so the difference does not exponentially increase i_frame+=1; if ((i_tick_2 + 1000) < GetTickCount()) { i_frame_rate = i_frame; i_frame=0; i_tick_2 = float(GetTickCount()); }; update(); // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received? { done=TRUE; // ESC or DrawGLScene Signalled A Quit } else // Not Time To Quit, Update Screen { SwapBuffers(hDC); // Swap Buffers (Double Buffering) } if (keys[VK_F1]) // Is F1 Being Pressed? { keys[VK_F1]=FALSE; // If So Make Key FALSE KillGLWindow(); // Kill Our Current Window fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode // Recreate Our OpenGL Window if (!CreateGLWindow("Zombie City",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } } } if(end) done=true; } // Shutdown KillGLWindow(); // Kill The Window return (msg.wParam); // Exit The Program }
/******************* WIN32 FUNCTIONS ***************************/ int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure bool done=false; // Bool Variable To Exit Loop StartGame n = StartGame(); activityManager.push(&n); console.Open(); // Create Our OpenGL Window if (!CreateGLWindow("OpenGL Win32 Example",screenWidth,screenHeight)) { return 0; // Quit If Window Was Not Created } Clock clock; double timeSinceLastUpdate = 0.0; Clock fpsCounterClock; double fpsCounterTime = 0.0; int fpsCounter = 0; clock.start(); fpsCounterClock.start(); //*******************************************GAME LOOP***********************************************************// while(!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=true; // If So done=TRUE } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { if(keys[VK_ESCAPE]) done = true; if (!keys[VK_RETURN]){ fpsCounterTime += fpsCounterClock.restart(); timeSinceLastUpdate += clock.restart(); while (timeSinceLastUpdate > TIME_PER_FRAME) { fpsCounter++; timeSinceLastUpdate -= TIME_PER_FRAME; update(TIME_PER_FRAME); } if (fpsCounterTime > 1){ #ifdef displayFPS std::cout<<"\t\t\t\t\tFPS: "<<fpsCounter<<std::endl; #endif fpsCounterTime = 0; fpsCounter = 0; } } display(); // Draw The Scene SwapBuffers(hDC); // Swap Buffers (Double Buffering) } } console.Close(); // Shutdown KillGLWindow(); // Kill The Window return (int)(msg.wParam); // Exit The Program }
int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure BOOL done=FALSE; // Bool Variable To Exit Loop // Ask The User Which Screen Mode They Prefer if (MessageBox(NULL,L"Would You Like To Run In Fullscreen Mode?", L"Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO) { fullscreen=FALSE; // Windowed Mode } // Create Our OpenGL Window if (!CreateGLWindow(L"Flythrough!",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } while(!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=TRUE; // If So done=TRUE } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received? { done=TRUE; // ESC or DrawGLScene Signalled A Quit } else // Not Time To Quit, Update Screen { SwapBuffers(hDC); // Swap Buffers (Double Buffering) if (keys['L'] && !lp) { lp=TRUE; light=!light; if (!light) { glDisable(GL_LIGHTING); } else { glEnable(GL_LIGHTING); } } if (!keys['L']) { lp=FALSE; } /*if (keys['F'] && !fp) // Filter toggle { fp=TRUE; filter+=1; if (filter>2) { filter=0; } } if (!keys['F']) { fp=FALSE; }*/ if (keys[VK_PRIOR])//strafe up { posy += 0.2f; looky += 0.2f; } if (keys[VK_NEXT])//strafe down { posy -= 0.2f; looky -= 0.2f; } if (keys[VK_UP])//look up { myCamera.RotateCamera(0.0f,0.03f); //looky += 0.2f; //xspeed-=0.1f; } if (keys[VK_DOWN])//look down { myCamera.RotateCamera(0.0f,-0.03f); //looky -= 0.2f; //xspeed+=0.1f; } if (keys[VK_RIGHT])//look right { myCamera.RotateCamera(0.03f,0.0f); //lookx -= 0.5f; //yspeed+=0.1f; } if (keys[VK_LEFT])//look left { myCamera.RotateCamera(-0.03f,0.0f); lookx += 0.5f; //yspeed-=0.1f; } if (keys['W'])//forward { velocity += 1; /*posz +=0.5f; lookz +=0.5f;*/ } if (keys['S']) //backward { velocity -= 1; /*posz -=0.5f; lookz -=0.5f;*/ } if (keys['A'])//strafe left { myCamera.SlideCamera(-10.0f,0.0f); /*posx +=0.2f; lookx += 0.2f;*/ } if (keys['D'])//strafe right { myCamera.SlideCamera(10.0f,0.0f); /*posx -=0.2f; lookx -= 0.2f;*/ } if (keys[VK_F1]) // Is F1 Being Pressed? { keys[VK_F1]=FALSE; // If So Make Key FALSE KillGLWindow(); // Kill Our Current Window fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode // Recreate Our OpenGL Window if (!CreateGLWindow(L"NeHe's Textures, Lighting & Keyboard Tutorial",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } } } if (keys[VK_F1]) // Is F1 Being Pressed? { keys[VK_F1]=FALSE; // If So Make Key FALSE KillGLWindow(); // Kill Our Current Window fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode // Recreate Our OpenGL Window if (!CreateGLWindow(L"NeHe's Rotation Tutorial",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } } } } // Shutdown KillGLWindow(); // Kill The Window return (msg.wParam); // Exit The Program }
//================================================================================================== 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(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 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 rctangle 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 } //Only a windowed style 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 }; //We need to get the device context from the frames handle //then maybe we can draw in the frame? if (!(hDC = GetDC(hWnd))) // Did we get a device context? //if (!(hDC = GetDC(Frame->))) { 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 }
/* This Code Creates Our OpenGL Window. Parameters Are: * * title - Title To Appear At The Top Of The Window * * width - Width Of The GL Window Or Full screen Mode * * height - Height Of The GL Window Or Full screen Mode * * bits - Number Of Bits To Use For Color (8/16/24/32) * * fullscreenflag - Use Full screen Mode (TRUE) Or Windowed Mode (FALSE) */ 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 g_bFullscreen = fullScreenFlag; // Set the global full screen flag hInstance = GetModuleHandle(NULL); // Grab an instance for out 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 = CLASSNAME; // Set the class name if (!RegisterClass(&wc)) // Attempt to register the window class { MessageBox(NULL, MSG_REGISTERCLASSFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } if (g_bFullscreen) { 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 failed, offer two options. Quit or use windowed mode. if (MessageBox(NULL, MSG_FULLSCREENNOTSUPPORT, ARTIST_NAME, MB_YESNO | MB_ICONEXCLAMATION) == IDYES) { g_bFullscreen = FALSE; // Windowed mode selected. Fullscreen = FALSE } else { // Pop up a message box letting user know the program is closing. MessageBox(NULL, MSG_PROGRAMNOTCLOSE, ERR_ERROR, MB_OK | MB_ICONSTOP); return FALSE; // Return FALSE } } } if (g_bFullscreen) // 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; // Windows 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 CLASSNAME, // Class name title, // Window title dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, // Defined 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))) // Don't pass anything to WM_CREATE { KillGLWindow(); // Reset the display MessageBox(NULL, MSG_CREATEWINDOWFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } static PIXELFORMATDESCRIPTOR pfd = // pfd tells widows how we want things to be { sizeof(PIXELFORMATDESCRIPTOR), // Size of this pixel format descriptor 1, // Version number PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, // Format must support window/opengl/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 DEPTHBUFFER, // 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, MSG_CREATEGLDCFAILED, ERR_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, MSG_FINDPIXELFORMATFAILED, ERR_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, MSG_SETPIXELFORMATFAILED, ERR_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, MSG_CREATEGLRCFAILED, ERR_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, MSG_ACTIVEGLRCFAILED, ERR_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, MSG_INITFAILED, ERR_ERROR, MB_OK | MB_ICONEXCLAMATION); return FALSE; // Return FALSE } return TRUE; // Success }
WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { //go and get the contents ImportREFile(); //start the windows loop MSG msg; // Windows message structure bool done = false; // bool variable to exit loop fullscreen = false; // Windowed mode // Create our OpenGL window if (!CreateGLWindow("Roadworks Estimator OpenGL Renderer",1024,768,16,fullscreen)) { return 0; // Quit if window was not created } while(!done) // Loop that runs while done = false { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is there a message waiting? { if (msg.message == WM_QUIT) // Have we received a quit message? { done = true; // If so done = true } else // If not, deal with window messages { TranslateMessage(&msg); // Translate the message DispatchMessage(&msg); // Dispatch the message } } else // If there are no messages { // Draw the scene. Watch for ESC key and quit messages from DrawGLScene() if (active) // Program active? { if (keys['W'] ) { translatez+=0.01f; } if (keys['S'] ) { translatez-=0.01f; } if (keys['A'] ) { rotatey+=0.01f; } if (keys['D'] ) { rotatey-=0.01f; } if (keys[VK_UP] ) { rotatex+=0.025f; } if (keys[VK_DOWN] ) { rotatex-=0.025f; } if (keys[VK_LEFT] ) { rotatez+=0.1f; } if (keys[VK_RIGHT] ) { rotatez-=0.1f; } if (keys[VK_F1] ) { wireframemode=!wireframemode; if(wireframemode) { WireframeMode(); Sleep(100); } else { TextureMode(); Sleep(100); } } if (keys[VK_ESCAPE]) // Was ESC pressed? { done = true; // ESC signalled a quit } // Not time to quit, Update screen if (isRClicked) // If Right Mouse Clicked, Reset All Rotations { Matrix3fSetIdentity(&LastRot); // Reset Rotation Matrix3fSetIdentity(&ThisRot); // Reset Rotation Matrix4fSetRotationFromMatrix3f(&Transform, &ThisRot); // Reset Rotation } if (!isDragging) // Not Dragging { if (isClicked) // First Click { isDragging = true; // Prepare For Dragging LastRot = ThisRot; // Set Last Static Rotation To Last Dynamic One ArcBall.click(&MousePt); // Update Start Vector And Prepare For Dragging } } if (isClicked) // Still Clicked, So Still Dragging { Quat4fT ThisQuat; ArcBall.drag(&MousePt, &ThisQuat); // Update End Vector And Get Rotation As Quaternion Matrix3fSetRotationFromQuat4f(&ThisRot, &ThisQuat); // Convert Quaternion Into Matrix3fT Matrix3fMulMatrix3f(&ThisRot, &LastRot); // Accumulate Last Rotation Into This One Matrix4fSetRotationFromMatrix3f(&Transform, &ThisRot); // Set Our Final Transform's Rotation From This One } else // No Longer Dragging isDragging = false; DrawGLScene(); // Draw the scene SwapBuffers(hDC); // Swap buffers (Double buffering) } } } // Shutdown KillGLWindow(); // Kill the window return (msg.wParam); // Exit the program }
int WINAPI WinMain(HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure BOOL bDone = FALSE; // Bool Variable To Exit Loop // Ask The User Which Screen Mode They Prefer if (MessageBox(NULL, MSG_RUNINFULLSCREEN, MSG_STARTFULLSCREEN, MB_YESNO | MB_ICONQUESTION) == IDNO) { g_bFullscreen = FALSE; // Windowed Mode } // Create Our OpenGL Window if (!CreateGLWindow(WINDOW_TITLE, WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_BIT, g_bFullscreen)) { return 0; // Quit If Window Was Not Created } while (!bDone) // Loop That Runs While done=FALSE { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) // Is There A Message Waiting? { if (msg.message == WM_QUIT) // Have We Received A Quit Message? { bDone = TRUE; // If So done=TRUE } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if (g_bActive) // Program Active? { if (g_bKeysArr[VK_ESCAPE]) // Was ESC Pressed? { bDone = TRUE; // ESC Signalled A Quit } else // Not Time To Quit, Update Screen { DrawGLScene(); // Draw The Scene SwapBuffers(hDC); // Swap Buffers (Double Buffering) } } if (g_bKeysArr[VK_F1]) // Is F1 Being Pressed? { g_bKeysArr[VK_F1] = FALSE; // If So Make Key FALSE KillGLWindow(); // Kill Our Current Window g_bFullscreen = !g_bFullscreen; // Toggle Full screen / Windowed Mode // Recreate Our OpenGL Window if (!CreateGLWindow(WINDOW_TITLE, WINDOW_WIDTH, WINDOW_HEIGHT, WINDOW_BIT, g_bFullscreen)) { return 0; // Quit If Window Was Not Created } } } } // Shutdown KillGLWindow(); // Kill The Window return (msg.wParam); // Exit The Program }
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; // 成功 }
BOOL CreateGLWindow(char* title, int width, int height, int bits, bool fullscreenflag) { GLuint PixelFormat; // Содержит результаты подбора глубины цвета WNDCLASS wc; // Структура классов Windows DWORD dwExStyle; // Расширенный стиль окна DWORD dwStyle; // Стиль окна RECT WindowRect; // Получает значения верхнего левого и нижнего правого углов прямоугольника WindowRect.left = (long)0; // Устанавливает значение лево (Left) в 0 WindowRect.right = (long)width; // Устанавливает значение право (Right) в требуемую ширину (Width) WindowRect.top = (long)0; // Устанавливает значение верх (Top) в 0 WindowRect.bottom = (long)height; // Устанавливает значение низ (Bottom) в требуемую высоту (Height) fullscreen = fullscreenflag; // Устанавливаем глобальный флвг Fullscreen hInstance = GetModuleHandle(NULL); // Захватываем Instance для нашего окна wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; // Перерисовываем по размеру, и получаем DC для окна. wc.lpfnWndProc = (WNDPROC) WndProc; // WndProc Handles Messages wc.cbClsExtra = 0; // Нет дополнительных данных окна wc.cbWndExtra = 0; // Нет дополнительных данных окна wc.hInstance = hInstance; // Установим Instance wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); // Згрузим иконку по умолчанию wc.hCursor = LoadCursor(NULL, IDC_ARROW); // Згрузим стрелку курсора wc.hbrBackground = NULL; // Фон для GL не требуется wc.lpszMenuName = NULL; // Нам не нужны меню wc.lpszClassName = "OpenGL"; // Установим имя класса if (!RegisterClass(&wc)) { // Попытаемся зарегистрировать класс окна MessageBox(NULL, "Failed To Register The Window Class.", "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 избавляется от кнопки стариGets Rid Of Start Bar. if (ChangeDisplaySettings(&dmScreenSettings, CDS_FULLSCREEN) != DISP_CHANGE_SUCCESSFUL) { // Если режиим не включился, предложим две возможности. Выйти или использовать оконный режим. 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; // Выбран оконный режим. Fullscreen = FALSE } else { // Показать сообщение, что приложение закончило работу. MessageBox(NULL, "Program Will Now Close.", "ERROR", 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, // Расширенный стиль для окна "OpenGL", // Наименование класса title, // Заголовок окна dwStyle | // Определенный стиль окна WS_CLIPSIBLINGS | // Требуемый стиль окна WS_CLIPCHILDREN, // Требуемый стиль окна 0, 0, // Местоположение окна WindowRect.right - WindowRect.left, // Вычисление ширины окна WindowRect.bottom - WindowRect.top, // Вычисление высоты окна NULL, // Нет родительского окна NULL, // Нет меню hInstance, // Instance NULL))) { // Не посылать сообщение по WM_CREATE KillGLWindow(); // Инициализация дисплея MessageBox(NULL, "Window Creation Error.", "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, // Биты накопления игнорируются 16, // 16битный Z-бувер (Буфер глубины) 0, // Нет буфера трафарета (stencil buffer) 0, // Нет вспомогательного буфера PFD_MAIN_PLANE, // Главная плоскость рисования 0, // Зарезервировано 0, 0, 0 // Слой масок игнорируется }; if (!(hDC = GetDC(hWnd))) { // Мы получили контекст устройства? KillGLWindow(); // Инициализация дисплея MessageBox(NULL, "Can't Create A GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Вернуть FALSE } if (!(PixelFormat = ChoosePixelFormat(hDC, &pfd))) { // Windows нашла соответствующий формат пикселя? KillGLWindow(); // Инициализация дисплея MessageBox(NULL, "Can't Find A Suitable PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Вернуть FALSE } if(!SetPixelFormat(hDC, PixelFormat, &pfd)) { // Мы можем установить формат пикселя? KillGLWindow(); // Инициализация дисплея MessageBox(NULL, "Can't Set The PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Вернуть FALSE } if (!(hRC = wglCreateContext(hDC))) { // Мы можем получить контекст изображения? KillGLWindow(); // Инициализация дисплея MessageBox(NULL, "Can't Create A GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Вернуть FALSE } if(!wglMakeCurrent(hDC, hRC)) { // Пытаемся активировать контекст изображения KillGLWindow(); // Инициализация дисплея MessageBox(NULL, "Can't Activate The GL Rendering Context.", "ERROR", 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; // Успешное завершение инициализациии }
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; WindowRect.right=(long)width; WindowRect.top=(long)0; WindowRect.bottom=(long)height; fullscreen=fullscreenflag; hInstance = GetModuleHandle(NULL); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (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; wc.lpszMenuName = NULL; wc.lpszClassName = "OpenGL"; if (!RegisterClass(&wc)) { MessageBox(NULL,"Failed To Register The Window Class.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; } if (fullscreen) { DEVMODE dmScreenSettings; memset(&dmScreenSettings,0,sizeof(dmScreenSettings)); dmScreenSettings.dmSize=sizeof(dmScreenSettings); dmScreenSettings.dmPelsWidth = width; dmScreenSettings.dmPelsHeight = height; dmScreenSettings.dmBitsPerPel = bits; 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) { 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); // Create The Window if (!(hWnd=CreateWindowEx( dwExStyle, "OpenGL", title, dwStyle | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0, 0, WindowRect.right-WindowRect.left, WindowRect.bottom-WindowRect.top, NULL, NULL, hInstance, NULL))) { KillGLWindow(); // Reset The Display MessageBox(NULL,"Window Creation Error.","ERROR",MB_OK|MB_ICONEXCLAMATION); return FALSE; // Return FALSE } static PIXELFORMATDESCRIPTOR pfd= { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, bits, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 0, 0, PFD_MAIN_PLANE, 0, 0, 0, 0 }; if (!(hDC=GetDC(hWnd))) { 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); SetForegroundWindow(hWnd); SetFocus(hWnd); ReSizeGLScene(width, height); 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 }
int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Предыдущий Instance LPSTR lpCmdLine, // Параметры командной строки int nCmdShow) { // Показать состояние окна MSG msg; // Структура сообщения окна BOOL done = FALSE; // Булевская переменная выхода из цикла // Запросим пользователя какой режим отображения он предпочитает if (MessageBox(NULL, "Would You Like To Run In Fullscreen Mode?", "Start FullScreen?", MB_YESNO | MB_ICONQUESTION) == IDNO) { fullscreen = FALSE; // Оконный режим } // Создадим наше окно OpenGL if (!CreateGLWindow("NeHe's Display List Tutorial", 640, 480, 16, fullscreen)) { return 0; // Выходим если окно не было создано } while(!done) { // Цикл, который продолжается пока done=FALSE if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { // Есть ожидаемое сообщение? if (msg.message == WM_QUIT) { // Мы получили сообщение о выходе? done = TRUE; // Если так done=TRUE } else { // Если нет,продолжаем работать с сообщениями окна TranslateMessage(&msg); // Переводим сообщение DispatchMessage(&msg); // Отсылаем сообщение } } else { // Если сообщений нет // Рисуем сцену. Ожидаем нажатия кнопки ESC и сообщения о выходе от DrawGLScene() if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) { // Активно? Было получено сообщение о выходе? done = TRUE; // ESC или DrawGLScene просигналили "выход" } else { // Не время выходить, обновляем экран SwapBuffers(hDC); // Переключаем буферы (Double Buffering) if (keys[VK_LEFT]) { // Была нажата стрелка влево? yrot -= 0.2f; // Если так, то повернем кубы влево } if (keys[VK_RIGHT]) { // Была нажата стрелка вправо? yrot += 0.2f; // Если так, то повернем кубы вправо } if (keys[VK_UP]) { // Была нажата стрелка вверх? xrot -= 0.2f; // Если так, то наклоним кубы вверх (в смысле - назад) } if (keys[VK_DOWN]) { // Была нажата стрелка вниз? xrot += 0.2f; // Если так, то наклоним кубы вниз } if (keys[VK_F1]) { // Была нажата кнопка F1? keys[VK_F1] = FALSE; // Если так - установим значение FALSE KillGLWindow(); // Закроем текущее окно OpenGL fullscreen = !fullscreen; // // Переключим режим "Полный экран"/"Оконный" // Заново создадим наше окно OpenGL if (!CreateGLWindow("NeHe's Display List Tutorial", 640, 480, 16, fullscreen)) { return 0; // Выйти, если окно не было создано } } } } } // Shutdown 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 }
int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure BOOL done=FALSE; // Bool Variable To Exit Loop // Ask The User Which Screen Mode They Prefer if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO) { fullscreen=FALSE; // Windowed Mode } // Create Our OpenGL Window if (!CreateGLWindow("RTA bridge maintenance",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } while(!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=TRUE; // If So done=TRUE } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received? { done=TRUE; // ESC or DrawGLScene Signalled A Quit } else // Not Time To Quit, Update Screen { SwapBuffers(hDC); // Swap Buffers (Double Buffering) if (keys['B'] && !bp) { bp=TRUE; blend=!blend; if (!blend) { glDisable(GL_BLEND); glEnable(GL_DEPTH_TEST); } else { glEnable(GL_BLEND); glDisable(GL_DEPTH_TEST); } } if (!keys['B']) { bp=FALSE; } if (keys['F'] && !fp) { fp=TRUE; filter+=1; if (filter>2) { filter=0; } } if (!keys['F']) { fp=FALSE; } if (keys[VK_PRIOR]) { z-=0.02f; } if (keys[VK_NEXT]) { z+=0.02f; } if (keys[VK_UP]) { xpos -= (float)sin(heading*piover180) * 0.001f; zpos -= (float)cos(heading*piover180) * 0.001f; if (walkbiasangle >= 359.0f) { walkbiasangle = 0.0f; } else { walkbiasangle+= 10; } walkbias = (float)sin(walkbiasangle * piover180)/20.0f; } if (keys[VK_DOWN]) { xpos += (float)sin(heading*piover180) * 0.001f; zpos += (float)cos(heading*piover180) * 0.001f; if (walkbiasangle <= 1.0f) { walkbiasangle = 359.0f; } else { walkbiasangle-= 10; } walkbias = (float)sin(walkbiasangle * piover180)/20.0f; } if (keys[VK_RIGHT]) { //heading -= 0.3f; yrot -= 0.05f; } if (keys[VK_LEFT]) { //heading += 0.3f; yrot += 0.05f; } if (keys[VK_PRIOR]) { lookupdown-= 1.0f; } if (keys[VK_NEXT]) { lookupdown+= 1.0f; } if (keys[VK_F1]) // Is F1 Being Pressed? { keys[VK_F1]=FALSE; // If So Make Key FALSE KillGLWindow(); // Kill Our Current Window fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode // Recreate Our OpenGL Window if (!CreateGLWindow("RTA bridge maintenance",640,480,16,fullscreen)) { return 0; // Quit If Window Was Not Created } } if (keys[VK_NUMPAD4]) { float yrotrad; yrotrad = (yrot / 180 * 3.141592654f); xpos += float(cos(yrotrad)) * 0.01; zpos += float(sin(yrotrad)) * 0.01; } if (keys[VK_NUMPAD6]) { float yrotrad; yrotrad = (yrot / 180 * 3.141592654f); xpos -= float(cos(yrotrad)) * 0.01; zpos -= float(sin(yrotrad)) * 0.01; } if (keys[VK_NUMPAD2]) { float yrotrad; yrotrad = (yrot / 180 * 3.141592654f); zpos += float(cos(yrotrad)) * 0.01; xpos += float(sin(yrotrad)) * 0.01; } if (keys[VK_NUMPAD8]) { float yrotrad; yrotrad = (yrot / 180 * 3.141592654f); zpos -= float(cos(yrotrad)) * 0.01; xpos -= float(sin(yrotrad)) * 0.01; } if (keys[VK_NUMPAD7]) { ypos += 0.01f; } if (keys[VK_NUMPAD1]) { ypos -= 0.01f; } } } } // Shutdown KillGLWindow(); // Kill The Window return (msg.wParam); // Exit The Program }
int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure BOOL done=FALSE; // Bool Variable To Exit Loop double deltaTime; { long long CountsPerSecond=0; QueryPerformanceCounter((LARGE_INTEGER*)&previousTime); QueryPerformanceFrequency((LARGE_INTEGER*)&CountsPerSecond); secondsPerCount = 1.0 / (double)CountsPerSecond; } // Ask The User Which Screen Mode They Prefer bFullScreen = !(MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO); // Windowed Mode // Create Our OpenGL Window if (!CreateGLWindow("Engine Programming",x_res,y_res,32,bFullScreen)) return 0; // Quit If Window Was Not Created while(!done) // Loop That Runs While done=FALSE { QueryPerformanceCounter((LARGE_INTEGER*)¤tTime); deltaTime=(double)(currentTime-previousTime)*secondsPerCount; if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=TRUE; // If So done=TRUE } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received? { done=TRUE; // ESC or DrawGLScene Signalled A Quit } else // Not Time To Quit, Update Screen { SwapBuffers(hDC); // Swap Buffers (Double Buffering) } UpdateGLScene(deltaTime); g.rotate_x(-g_Landscape->TotalRot); g.rotate_y((float)xDelta/4); g_newRot=g_Landscape->TotalRot+(float)yDelta/4; g.rotate_x(g_Landscape->TotalRot+(float)yDelta/4); xDelta=0; yDelta=0; if(!keys[VK_SHIFT]) g_MaxVelocity=vector(0.01,0.01,0.01); else g_MaxVelocity=vector(0.05,0.05,0.05); g_Acceleration=vector(0,0,0); if(keys[VK_UP]||keys['W']) g_Acceleration.wz=0.01; if(keys[VK_DOWN]||keys['S']) g_Acceleration.wz=-0.01; if(keys[VK_RIGHT]||keys['D']) g_Acceleration.wx=-0.01; if(keys[VK_LEFT]||keys['A']) g_Acceleration.wx=0.01; if(keys[VK_UP]||keys['U']) g_DominantDirectionalLight->rotate_z(1); if(keys[VK_DOWN]||keys['J']) g_DominantDirectionalLight->rotate_z(-1); if(keys[VK_RIGHT]||keys['K']) g_DominantDirectionalLight->rotate_x(-1); if(keys[VK_LEFT]||keys['H']) g_DominantDirectionalLight->rotate_x(1); if(g_Acceleration.wz==0.0) g_Velocity.wz=0.0f; if(g_Acceleration.wx==0.0f) g_Velocity.wx=0.0f; g_Velocity+=g_Acceleration*static_cast<float>(deltaTime); if(g_Velocity.wx>g_MaxVelocity.wx) g_Velocity.wx=g_MaxVelocity.wx; if(g_Velocity.wy>g_MaxVelocity.wy) g_Velocity.wy=g_MaxVelocity.wy; if(g_Velocity.wz>g_MaxVelocity.wz) g_Velocity.wz=g_MaxVelocity.wz; if(g_Velocity.wx<-g_MaxVelocity.wx) g_Velocity.wx=-g_MaxVelocity.wx; if(g_Velocity.wy<-g_MaxVelocity.wy) g_Velocity.wy=-g_MaxVelocity.wy; if(g_Velocity.wz<-g_MaxVelocity.wz) g_Velocity.wz=-g_MaxVelocity.wz; g.translate(g_Velocity.wx*deltaTime,g_Velocity.wy*deltaTime,g_Velocity.wz*deltaTime); if(keys[VK_F2] && !g_bF2Down) { g_bF2Down=true; g_WireFrameMode=!g_WireFrameMode; } else if(!keys[VK_F2]) g_bF2Down=false; if(keys[VK_F3] && !g_bF3Down) { g_bF3Down=true; g_DrawNormals=!g_DrawNormals; } else if(!keys[VK_F3]) g_bF3Down=false; if (keys[VK_F1]) // Is F1 Being Pressed? { keys[VK_F1]=FALSE; // If So Make Key FALSE } } } // Shutdown KillGLWindow(); // Kill The Window return (msg.wParam); // Exit The Program }
int WINAPI WinMain(HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure BOOL done = FALSE; // Bool Variable To Exit Loop GLenum err = glewInit(); /* if (GLEW_ARB_vertex_program) { /* It is safe to use the ARB_vertex_program extension here. * glGenProgramsARB(...); } In GLEW 1.0.x, a global structure was used for this task.To ensure binary compatibility between releases, the struct was replaced with a set of variables. You can also check for core OpenGL functionality.For example, to see if OpenGL 1.3 is supported, do the following : if (GLEW_VERSION_1_3) { /* Yay! OpenGL 1.3 is supported! * } In general, you can check if GLEW_{ extension_name } or GLEW_VERSION_{ version } is true or false. It is also possible to perform extension checks from string input.Starting from the 1.3.0 release, use glewIsSupported to check if the required core or extension functionality is available : if (glewIsSupported("GL_VERSION_1_4 GL_ARB_point_sprite")) { /* Great, we have OpenGL 1.4 + point sprites. * } */ // Ask The User Which Screen Mode They Prefer //if (MessageBox(NULL, "Would You Like To Run In Fullscreen Mode?", "Start FullScreen?", MB_YESNO | MB_ICONQUESTION) == IDNO) { fullscreen = FALSE; // Windowed Mode } // Create Our OpenGL Window if (!CreateGLWindow(L"NeHe's Solid Object Tutorial", 640, 480, 16, fullscreen)) { return 0; // Quit If Window Was Not Created } while (!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) // Is There A Message Waiting? { if (msg.message == WM_QUIT) // Have We Received A Quit Message? { done = TRUE; // If So done=TRUE } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if ((active && !DrawGLScene()) || keys[VK_ESCAPE]) // Active? Was There A Quit Received? { done = TRUE; // ESC or DrawGLScene Signalled A Quit } else // Not Time To Quit, Update Screen { SwapBuffers(hDC); // Swap Buffers (Double Buffering) } if (keys[VK_F1]) // Is F1 Being Pressed? { keys[VK_F1] = FALSE; // If So Make Key FALSE KillGLWindow(); // Kill Our Current Window fullscreen = !fullscreen; // Toggle Fullscreen / Windowed Mode // Recreate Our OpenGL Window if (!CreateGLWindow(L"NeHe's Solid Object Tutorial", 640, 480, 16, fullscreen)) { return 0; // Quit If Window Was Not Created } } } } // Shutdown KillGLWindow(); // Kill The Window return (msg.wParam); // Exit The Program }
bool CoreWindow::initGL(HWND hWnd) { 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, 0, 0, 0, 24, //Z-Buffer 8, //Stencil Buffer 0, PFD_MAIN_PLANE, 0, //Reserved 0, 0, 0 }; int PixelFormat; if (!(m_hDC = ::GetDC(hWnd))) { KillGLWindow(); MessageBox(NULL,_TX("Can't Create A GL Device Context."),_TX("ERROR"),MB_OK|MB_ICONEXCLAMATION); return FALSE; } if (!(PixelFormat = ChoosePixelFormat(m_hDC, &pfd))) { KillGLWindow(); MessageBox(NULL,_TX("Can't Find A Suitable PixelFormat."),_TX("ERROR"),MB_OK|MB_ICONEXCLAMATION); return FALSE; } if (!SetPixelFormat(m_hDC, PixelFormat, &pfd)) { KillGLWindow(); MessageBox(NULL,_TX("Can't Set The PixelFormat."),_TX("ERROR"),MB_OK|MB_ICONEXCLAMATION); return FALSE; } if (!(m_hRC = wglCreateContext(m_hDC))) { KillGLWindow(); MessageBox(NULL,_TX("Can't Create A GL Rendering Context."),_TX("ERROR"),MB_OK|MB_ICONEXCLAMATION); return FALSE; } if (!wglMakeCurrent(m_hDC, m_hRC)) { KillGLWindow(); MessageBox(NULL,_TX("Can't Activate The GL Rendering Context."),_TX("ERROR"),MB_OK|MB_ICONEXCLAMATION); return FALSE; } ShowWindow(hWnd,SW_SHOW); return TRUE; }
int WINAPI WinMain( HINSTANCE hInstance, // Instance HINSTANCE hPrevInstance, // Previous Instance LPSTR lpCmdLine, // Command Line Parameters int nCmdShow) // Window Show State { MSG msg; // Windows Message Structure BOOL done=FALSE; // Bool Variable To Exit Loop // Ask The User Which Screen Mode They Prefer if (MessageBox(NULL,"Would You Like To Run In Fullscreen Mode?", "Start FullScreen?",MB_YESNO|MB_ICONQUESTION)==IDNO) { fullscreen=FALSE; // Windowed Mode } // Create Our OpenGL Window if (!CreateGLWindow("OpenGL Framework",800,600,32,fullscreen)) { return 0; // Quit If Window Was Not Created } while(!done) // Loop That Runs While done=FALSE { if (PeekMessage(&msg,NULL,0,0,PM_REMOVE)) // Is There A Message Waiting? { if (msg.message==WM_QUIT) // Have We Received A Quit Message? { done=TRUE; // If So done=TRUE } else // If Not, Deal With Window Messages { TranslateMessage(&msg); // Translate The Message DispatchMessage(&msg); // Dispatch The Message } } else // If There Are No Messages { // Draw The Scene. Watch For ESC Key And Quit Messages From DrawGLScene() if (active) // Program Active? { if (keys[VK_ESCAPE]) // Was ESC Pressed? { done=TRUE; // ESC Signalled A Quit } else if (keys[VK_UP]) // Was ESC Pressed? { cameraY += 0.25f; // ESC Signalled A Quit cameraCY += 0.25f; keys[VK_UP] = FALSE; } else if (keys[VK_DOWN]) // Was ESC Pressed? { cameraY -= 0.25f; // ESC Signalled A Quit cameraCY -= 0.25f; keys[VK_DOWN] = FALSE; } else if (keys[VK_LEFT]) // Was ESC Pressed? { cameraZ += 0.25f; // ESC Signalled A Quit cameraCZ += 0.25f; keys[VK_LEFT] = FALSE; } else if (keys[VK_RIGHT]) // Was ESC Pressed? { cameraZ -= 0.25f; // ESC Signalled A Quit cameraCZ -= 0.25f; keys[VK_RIGHT] = FALSE; } else // Not Time To Quit, Update Screen { DrawGLScene(); // Draw The Scene SwapBuffers(hDC); // Swap Buffers (Double Buffering) } } if (keys[VK_F1]) // Is F1 Being Pressed? { keys[VK_F1]=FALSE; // If So Make Key FALSE KillGLWindow(); // Kill Our Current Window fullscreen=!fullscreen; // Toggle Fullscreen / Windowed Mode // Recreate Our OpenGL Window if (!CreateGLWindow("OpenGL Framework",800,600,32,fullscreen)) { return 0; // Quit If Window Was Not Created } } } } // Shutdown KillGLWindow(); // Kill The Window return (msg.wParam); // Exit The Program }
BOOL CreateGLWindow( char* 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 = (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 = "OpenGL"; // Устанавливаем имя классу if( !RegisterClass( &wc ) ) // Пытаемся зарегистрировать класс окна { MessageBox( NULL, "Failed To Register The Window Class.", "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, "The Requested Fullscreen Mode Is Not Supported By\nYour Video Card. Use Windowed Mode Instead?", "NeHe GL", MB_YESNO | MB_ICONEXCLAMATION) == IDYES ) { fullscreen = FALSE; // Выбор оконного режима (fullscreen = false) } else { // Выскакивающее окно, сообщающее пользователю о закрытие окна. MessageBox( NULL, "Program Will Now Close.", "ERROR", 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, // Расширенный стиль для окна "OpenGL", // Имя класса title, // Заголовок окна dwStyle | // Выбираемые стили для окна WS_CLIPSIBLINGS | // Требуемый стиль для окна WS_CLIPCHILDREN , // Требуемый стиль для окна 0, 0, // Позиция окна WindowRect.right - WindowRect.left, // Вычисление подходящей ширины WindowRect.bottom - WindowRect.top, // Вычисление подходящей высоты NULL, // Нет родительского NULL, // Нет меню hInstance, // Дескриптор приложения NULL ) ) ) // Не передаём ничего до WM_CREATE (???) { KillGLWindow(); // Восстановить экран MessageBox( NULL, "Window Creation Error.", "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, "Can't Create A GL Device Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION ); return FALSE; // Вернуть false } if( !( PixelFormat = ChoosePixelFormat( hDC, &pfd ) ) ) // Найден ли подходящий формат пикселя? { KillGLWindow(); // Восстановить экран MessageBox( NULL, "Can't Find A Suitable PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION ); return FALSE; // Вернуть false } if( !SetPixelFormat( hDC, PixelFormat, &pfd ) ) // Возможно ли установить Формат Пикселя? { KillGLWindow(); // Восстановить экран MessageBox( NULL, "Can't Set The PixelFormat.", "ERROR", MB_OK | MB_ICONEXCLAMATION ); return FALSE; // Вернуть false } if( !( hRC = wglCreateContext( hDC ) ) ) // Возможно ли установить Контекст Рендеринга? { KillGLWindow(); // Восстановить экран MessageBox( NULL, "Can't Create A GL Rendering Context.", "ERROR", MB_OK | MB_ICONEXCLAMATION); return FALSE; // Вернуть false } if( !wglMakeCurrent( hDC, hRC ) ) // Попробовать активировать Контекст Рендеринга { KillGLWindow(); // Восстановить экран MessageBox( NULL, "Can't Activate The GL Rendering Context.", "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, ("Initialization Failed."), ("ERROR"), MB_OK | MB_ICONEXCLAMATION ); return FALSE; // Вернуть 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; }