indows使用OpenGL必须设置OpenGL环境,将窗口连接到OpenGL。首先选择并设置相应像素格式,然后创建着色描述表并将其连接到设备描述表。本文介绍两种设置OpenGL环境的方法,主要是选择像素格式方法的不同。
HDC g_hDC = NULL;
HGLRC g_hRC = NULL;
#define METHOD_1
BOOL ConnectGL1 (HWND hWnd);
BOOL ConnectGL2 (HWND hWnd);
#ifdef METHOD_1
#define ConnectGL ConnectGL1
#endif
#ifdef METHOD_2
#define ConnectGL ConnectGL2
#endif
BOOL ConnectGL1 (HWND hWnd)
{
GLuint PixelFormat;
static PIXELFORMATDESCRIPTOR pfd = {
sizeof (PIXELFORMATDESCRIPTOR),
1,
PFD_DWAR_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, //标志
PFD_TYEP_RGBA, //颜色模式
24, //颜色位数
0, 0, 0, 0, 0, 0,
0,
0,
0,
0, 0, 0, 0,
32, //深度位数
0,
0,
PFD_MAIN_PLANE,
0,
0, 0, 0
};
if ((g_hDC = GetDC (hWnd)) == NULL) return FALSE;
if ((PixelFormat = ChoosePixelFormat (g_hDC, &pfd)) == 0) return FALSE; //选择相应像素格式
if (!SetPixelFormat (g_hDC, PixelFormat, &pfd)) return FALSE; //设置像素格式
if ((g_hRC = wglCreateContext (g_hDC)) == NULL) return FALSE; //创建着色描述表
if (!wglMakeCurrent (g_hDC, g_hRC)) return FALSE; //将着色描述表连接到设备描述表
}
#define DESFLAGS PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER
BOOL ConnectGL2 (HWND hWnd)
{
GLuint PixelFormat, iPixelFormat, maxPixelFormat;
static PIXELFORMATDESCRIPTOR pfd;
if ((g_hDC = GetDC (hWnd)) == NULL) return FALSE;
maxPixelFormat = DescribePixelFormat (g_hDC, 1, sizeof (PIXELFORMATDESCRIPTOR), NULL); //获取所支持的像素最大索引
for (iPixelFormat = 1; iPixelFormat <= maxPixelFormat; iPixelFormat++) {
DescribePixelFormat (g_hDC, iPixelFormat, sizeof (PIXELFORMATDESCRIPTOR), &pfd);
if ((pfd.dwFlags & DESFLAGS) == DESFLAGS) {
PixelFormat = iPixelFormat;
break;
}
}
if (!SetPixelFormat (g_hDC, PixelFormat, &pfd)) return FALSE; //设置像素格式
if ((g_hRC = wglCreateContext (g_hDC)) == NULL) return FALSE; //创建着色描述表
if (!wglMakeCurrent (g_hDC, g_hRC)) return FALSE; //将着色描述表连接到设备描述表
}