前面两篇文章介绍了opengl在windows和android系统上的环境建立,身为跨平台开发者,linux是必需在兼顾的,话说不兼顾linux系统的不叫跨平台(这是大佬们说的,我只是借用一下,请轻喷!)
Linux系统的图形窗口类似于服务器与客户端的机制,它是被设计为C-S架构,我们的图形程序通过X Window (GLX) 将3D绘图指令以X协议扩展的方式发给X Server,然后X Server再发送给显卡。GLX与Windows上的WGL比较相似。
注意在Linux上创建窗口,需要切换到桌面环境,否则创建不成功。理解了Linux图形窗口的相关机制,我们来开始创建OpenGL环境。
获取当前显示设备
Display *display = XOpenDisplay(NULL);
检查GLX版本
if (!glXQueryVersion(display, &glx_major, &glx_minor) ||
((glx_major == 1) && (glx_minor < 3)) || (glx_major < 1))
{
return;
}
配置显示设备
static int visual_attribs[] =
{
GLX_X_RENDERABLE , True,
GLX_DRAWABLE_TYPE , GLX_WINDOW_BIT,
GLX_RENDER_TYPE , GLX_RGBA_BIT,
GLX_X_VISUAL_TYPE , GLX_TRUE_COLOR,
GLX_RED_SIZE , 8,
GLX_GREEN_SIZE , 8,
GLX_BLUE_SIZE , 8,
GLX_ALPHA_SIZE , 8,
GLX_DEPTH_SIZE , 24,
GLX_STENCIL_SIZE , 8,
GLX_DOUBLEBUFFER , True,
None
};
int default_screen = DefaultScreen(display);
GLXFBConfig *fb_configs = glXChooseFBConfig(display, default_screen, visual_attribs, &num_fb_configs);
获取视觉
XVisualInfo *vi = glXGetVisualFromFBConfig(display, fb_config);
创建窗口
XSetWindowAttributes swa;
Colormap cmap;
swa.colormap = cmap = XCreateColormap( display,
RootWindow( display, vi->screen ),
vi->visual, AllocNone );
swa.background_pixmap = None ;
swa.border_pixel = 0;
swa.event_mask = StructureNotifyMask;
Window win = XCreateWindow( display, RootWindow( display, vi->screen ),
0, 0, 100, 100, 0, vi->depth, InputOutput,
vi->visual,
CWBorderPixel|CWColormap|CWEventMask, &swa );
if ( !win )
{
return;
}
// Done with the visual info data
XFree( vi );
XStoreName( display, win, "GL 3.0 Window" );
XMapWindow( display, win );
创建opengl上下文并绑定
int context_attribs[] =
{
GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
GLX_CONTEXT_MINOR_VERSION_ARB, 0,
None
};
GLXContext context = glXCreateNewContext(display, fb_config, GLX_RGBA_TYPE, 0, True);
glXMakeCurrent( display, win, ctx );
微信号:ITComputerGraph
更多精彩内容,关注公众号《IT木子李》