import sys, time, math, os, random import Image from pyglet.gl import * window = pyglet.window.Window() def initTexture(filename): img = Image.open(filename).transpose(Image.FLIP_TOP_BOTTOM) textureIDs = (pyglet.gl.GLuint * 1) () glGenTextures(1,textureIDs) textureID = textureIDs[0] print 'generating texture', textureID, 'from ', filename glBindTexture(GL_TEXTURE_2D, textureID) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img.size[0], img.size[1], 0, GL_RGB, GL_UNSIGNED_BYTE, img.tostring()) glBindTexture(GL_TEXTURE_2D, 0) return textureID class Square: def __init__(self, width=1.0, height=1.0, xpos=0.0, ypos=0.0, color=[1,1,1], texture=0): self.width = width self.height = height self.xpos = xpos self.ypos = ypos self.color = color self.texture = texture def draw(self): glColor3f(self.color[0],self.color[1],self.color[2]) if self.texture != 0: glEnable(GL_TEXTURE_2D) glBindTexture(GL_TEXTURE_2D, self.texture) glPushMatrix() glTranslatef(self.xpos, self.ypos, 0) glBegin(GL_QUADS) glTexCoord2f(0,0) glVertex2f(-self.width/2.0, -self.height/2.0) glTexCoord2f(1,0) glVertex2f(self.width/2.0, -self.height/2.0) glTexCoord2f(1,1) glVertex2f(self.width/2.0, self.height/2.0) glTexCoord2f(0,1) glVertex2f(-self.width/2.0, self.height/2.0) glEnd() glPopMatrix() if self.texture != 0: glDisable(GL_TEXTURE_2D) objects = [] def createObjects(textureFile): global objects square1 = Square(2, 2, texture=initTexture(textureFile)) objects.append(square1) square2 = Square(xpos=1, ypos=1.5, color=[1,0,0]) objects.append(square2) @window.event def on_draw(): glClearColor(0, 0.3, 0.5, 0) glClear(GL_COLOR_BUFFER_BIT) glMatrixMode(GL_PROJECTION) glLoadIdentity() gluOrtho2D(-2, 2, -2, 2) glMatrixMode(GL_MODELVIEW) for o in objects: o.draw() @window.event def on_key_press(key,modifiers): global objects if key == pyglet.window.key.LEFT: objects[0].xpos -= 0.25 elif key == pyglet.window.key.RIGHT: objects[0].xpos += 0.25 elif key == pyglet.window.key.UP: objects[0].ypos += 0.25 elif key == pyglet.window.key.DOWN: objects[0].ypos -= 0.25 def update(dummy): global objects objects[1].xpos += random.uniform(-0.1, 0.1) objects[1].ypos += random.uniform(-0.1, 0.1) pyglet.clock.schedule_interval(update,1/60.0) if len(sys.argv) > 1: createObjects(sys.argv[1]) else: createObjects("texture.jpg") pyglet.app.run()