如何将xlib和OpenGL模块与python一起使用?

时间:2013-02-18 09:58:41

标签: python opengl x11 xlib

我知道可以与GLX一起使用Xlib和OpenGL(我自己在C中完成)。

问题是,我如何在python中执行此操作? OpenGL模块具有GLX功能[documentation],但它似乎使用C类型,我不知道(也没有其他人出现)如何使用xlib types PyOpenGL。

我还尝试使用ctypes并直接加载库,但在尝试使用Xlib头文件中定义的C宏时遇到(明显的)问题,例如DefaultRootWindow

我是否遗漏了一些明显的东西,比如PyOpenGL有自己的xlib实现,或者如果没有一些(已编译的)模块编写,这是不可能的?

1 个答案:

答案 0 :(得分:3)

你不能直接使用python-opengl使用python-xlib类型。但是你可以使用窗口XID只是一个在同一窗口上使用python-opengl的数字。

from Xlib import X, display
from OpenGL import GL, GLX
from OpenGL.raw._GLX import struct__XDisplay
from ctypes import *

# some python-xlib code...
pd = display.Display()
pw = pd.screen().root.create_window(50, 50, 200, 200, 0,
                                    pd.screen().root_depth,
                                    X.InputOutput, X.CopyFromParent)
pw.map()

# ensure that the XID is valid on the server
pd.sync()

# get the window XID
xid = pw.__resource__()

# a separate ctypes Display object for OpenGL.GLX
xlib = cdll.LoadLibrary('libX11.so')
xlib.XOpenDisplay.argtypes = [c_char_p]
xlib.XOpenDisplay.restype = POINTER(struct__XDisplay)
d = xlib.XOpenDisplay("")

# use GLX to create an OpenGL context on the same window XID
elements = c_int()
configs = GLX.glXChooseFBConfig(d, 0, None, byref(elements))
w = GLX.glXCreateWindow(d, configs[0], c_ulong(xid), None)
context = GLX.glXCreateNewContext(d, configs[0], GLX.GLX_RGBA_TYPE, None, True)
GLX.glXMakeContextCurrent(d, w, w, context)

# some python-opengl code....
GL.glShadeModel(GL.GL_FLAT)
GL.glClearColor(0.5, 0.5, 0.5, 1.0)

GL.glViewport(0, 0, 200, 200)
GL.glMatrixMode(GL.GL_PROJECTION)
GL.glLoadIdentity()
GL.glOrtho(-1.0, 1.0, -1.0, 1.0, -1.0, 1.0)

GL.glClear(GL.GL_COLOR_BUFFER_BIT)
GL.glColor3f(1.0, 1.0, 0.0)
GL.glRectf(-0.8, -0.8, 0.8, 0.8)

# assume we got a double buffered fbConfig and show what we drew
GLX.glXSwapBuffers(d, w)

# a terrible end to a terrible piece of code...
raw_input()

但这真的太可怕了。 (为清楚起见,错误检查和选择合理的fbConfig)

尽管如此,应该可以使用ctypes进行所有必要的xlib调用。例如,Pyglet以某种方式管理,但我不确定你遇到了什么具体问题。