Wednesday, March 3, 2010

Using GLSL programs in python pyopengl

Here is an easy straightforward example of using GLSL shader programs with pyopengl.

To use this you will need to import the following:


from OpenGL.GL import *
from OpenGL.GLU import *


Thus we will need pyopengl package installed.



##compile and link shader
vs = fs = 0

vs = glCreateShader(GL_VERTEX_SHADER)
fs = glCreateShader(GL_FRAGMENT_SHADER)

vs_source = """
void main(void) {
gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
}
"""
fs_source = """
void main (void) {
gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
}
"""
glShaderSource(vs, vs_source)
glShaderSource(fs, fs_source)

glCompileShader(vs)
log = glGetShaderInfoLog(vs)
if log: print 'Vertex Shader: ', log

glCompileShader(fs)
log = glGetShaderInfoLog(fs)
if log: print 'Fragment Shader: ', log

prog = glCreateProgram()
glAttachShader(prog, vs)
glAttachShader(prog, fs)

glLinkProgram(prog)
glUseProgram(prog)


glShaderSource(shader_id, text) is a handy python function that will load our shader for us into opengl.


I also have a handy shader class I use in my engine program. Here it is:


class shader(node) :
def __init__(self, filename):
node.__init__(self)
fh = open(filename)
self.source = {'vertex': '', 'fragment':''}
write = None
for line in fh :
if line == '[[vertex-program]]\n' :
write = 'vertex'
elif line == '[[fragment-program]]\n' :
write = 'fragment'
else :
self.source[write] += line

self.draw = self.init

def init(self):
##compile and link shader
self.vs = self.fs = 0

self.vs = glCreateShader(GL_VERTEX_SHADER)
self.fs = glCreateShader(GL_FRAGMENT_SHADER)

glShaderSource(self.vs, self.source['vertex'])
glShaderSource(self.fs, self.source['fragment'])

glCompileShader(self.vs)
log = glGetShaderInfoLog(self.vs)
if log: print 'Vertex Shader: ', log

glCompileShader(self.fs)
log = glGetShaderInfoLog(self.fs)
if log: print 'Fragment Shader: ', log

self.prog = glCreateProgram()
glAttachShader(self.prog, self.vs)
glAttachShader(self.prog, self.fs)

glLinkProgram(self.prog)
self.use()
self.draw = self.use

def use(self):
glUseProgram(self.prog)

def end(self):
glUseProgram(0)

2 comments:

  1. I think this is correct way:

    from OpenGL import platform
    gl=platform.OpenGL
    vs = fs = 0
    vs = gl.glCreateShader(GL_VERTEX_SHADER)

    ReplyDelete
  2. Hm interesting, Im just going from the manual, eg http://pyopengl.sourceforge.net/ctypes/using.html

    ReplyDelete