Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #python2.6
- #pygame
- #numpy
- #pyopengl
- import numpy
- from OpenGL.GL import *
- from OpenGL.arrays import vbo
- from OpenGLContext.arrays import *
- from OpenGL.GL import shaders
- from OpenGL.GLU import *
- import pygame
- from pygame.locals import *
- from gameobjects.matrix44 import *
- from gameobjects.vector3 import *
- #DOWNLOADED AS PART OF THE DEMO AT http://www.willmcgugan.com/blog/tech/2007/6/4/opengl-sample-code-for-pygame/
- #THIS FILE ALSO USES THAT CAMERA CODE
- def resize(width, height):
- glViewport(0, 0, width, height) # sets the viewport
- glMatrixMode(GL_PROJECTION) # the matrix that transforms 3d into a 2d perspective picture
- glLoadIdentity() # resets the matrix to a default state - anythign multiplied by this returns itself, like 1
- gluPerspective(60.0, float(width)/height, .1, 1000.)
- '''
- ( GLdouble fovy, -- field of view
- GLdouble aspect, -- aspect ratio, basically unnecessary with width/height set?
- GLdouble zNear, -- closest a thing can be seen from the camera
- GLdouble zFar); -- furthest away a thing can be seen from the camera
- '''
- glMatrixMode(GL_MODELVIEW) # the matrix that sort of draws it into the world space, in front of the camera
- glLoadIdentity() # reset again
- def init():
- global shader, avbo, UNIFORM_LOCATIONS, position, texcoords, texture
- glEnable(GL_DEPTH_TEST) #let's be rash and have a z buffer
- glShadeModel(GL_FLAT) # no shading!
- glClearColor(0.6, 0.0, 1.0, 0.0) #purple
- glEnable(GL_COLOR_MATERIAL) #coloured material
- glEnable(GL_TEXTURE_2D)
- glEnable(GL_BLEND)
- glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
- glEnable(GL_LIGHTING)#lightingplz
- glEnable(GL_LIGHT0) #enable the light
- glLight(GL_LIGHT0, GL_POSITION, (0, 1, 1, 0)) #set it to be in a place.
- #Generate PyOpenGL Texture
- texture = glGenTextures(1)
- #Load the image file
- Surface = pygame.image.load('test.png')
- #Convert it to load any alpha channel
- Surface.convert_alpha()
- #Convert to PyOpenGL Data
- Data = pygame.image.tostring(Surface, "RGBA", 1)
- #Select our Texture Object
- glActiveTexture(GL_TEXTURE0)
- glBindTexture(GL_TEXTURE_2D, texture)
- #Load the Data into the Texture
- glTexImage2D( GL_TEXTURE_2D, 0, GL_RGBA, Surface.get_width(), Surface.get_height(), 0, GL_RGBA, GL_UNSIGNED_BYTE, Data )
- #Define some Parameters for this Texture
- glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
- glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
- VERTEX_SHADER = shaders.compileShader('''
- uniform float xpos;
- uniform float ypos;
- attribute vec3 position;
- attribute vec2 texcoords;
- attribute int texid;
- varying vec2 texcoords_v;
- void main() {
- gl_Position = gl_ModelViewProjectionMatrix * (vec4(position,1.0) + vec4(
- xpos, ypos, 0.0, 0.0
- ));
- texcoords_v = texcoords;
- }''', GL_VERTEX_SHADER)
- FRAGMENT_SHADER = shaders.compileShader('''
- varying vec2 texcoords_v;
- uniform sampler2D thetexture;
- //s[2]
- void main() {
- gl_FragColor = texture2D(thetexture, texcoords_v);
- }''', GL_FRAGMENT_SHADER)
- shader = shaders.compileProgram(VERTEX_SHADER,FRAGMENT_SHADER) #shaders have to be compiled to be used.
- position = glGetAttribLocation(
- shader, 'position'
- )
- texcoords = glGetAttribLocation(
- shader, 'texcoords'
- )
- avbo = vbo.VBO(
- numpy.array( [ #x, y, z ; texx, texy
- [ 0, 1, 0, 0.5,1],#top
- [ -1,-1, 0, 0, 0],#botleft
- [ 1,-1, 0, 1, 0],#botright
- [ 2,-1, 0, 0, 0],#botleft
- [ 4,-1, 0, 1, 0],#botright
- [ 4, 1, 0, 1, 1],#topright
- [ 2,-1, 0, 0, 0],#botleft
- [ 4, 1, 0, 1, 1],#topright
- [ 2, 1, 0, 0, 1],#topleft
- ], 'f')
- )#a triangle and a square
- UNIFORM_LOCATIONS = { #set up some linkages!
- 'xpos': glGetUniformLocation( shader, 'xpos' ),
- 'ypos': glGetUniformLocation( shader, 'ypos' ),
- 'thetexture': glGetUniformLocation( shader, 'thetexture' ),
- }
- SCREEN_SIZE = (800, 600)
- def run():
- global shader, avbo, UNIFORM_LOCATIONS, position, texcoords, texture
- pygame.init()
- screen = pygame.display.set_mode(SCREEN_SIZE, HWSURFACE|OPENGL|DOUBLEBUF)
- pygame.display.set_caption("TRIANGLES", "TRIANGLES")
- resize(*SCREEN_SIZE)# also starts gl and sets up the projection things
- init()# load shaders and vbo
- clock = pygame.time.Clock()
- # Camera transform matrix
- camera_matrix = Matrix44() #I think this probably just loads a default matrix
- camera_matrix.translate = (5.0, .6, 10.0) #translates to this position
- # Initialize speeds and directions
- rotation_direction = Vector3() # 0,0,0
- rotation_speed = radians(90.0)
- movement_direction = Vector3()
- movement_speed = 5.0
- xpos = 0.
- ypos = 0.
- while True:
- for event in pygame.event.get():
- if event.type == QUIT:
- return
- if event.type == KEYUP and event.key == K_ESCAPE:
- return
- # Clear the screen, and z-buffer
- glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
- time_passed = clock.tick()
- time_passed_seconds = time_passed / 1000.
- pressed = pygame.key.get_pressed()
- # Reset rotation and movement directions
- rotation_direction.set(0.0, 0.0, 0.0)
- movement_direction.set(0.0, 0.0, 0.0)
- # Modify direction vectors for key presses
- if pressed[K_LEFT]:
- rotation_direction.y = +1.0
- elif pressed[K_RIGHT]:
- rotation_direction.y = -1.0
- if pressed[K_UP]:
- rotation_direction.x = -1.0
- elif pressed[K_DOWN]:
- rotation_direction.x = +1.0
- if pressed[K_z]:
- rotation_direction.z = -1.0
- elif pressed[K_x]:
- rotation_direction.z = +1.0
- if pressed[K_q]:
- movement_direction.z = -1.0
- elif pressed[K_a]:
- movement_direction.z = +1.0
- if pressed[K_j]:
- xpos -= 0.1
- elif pressed[K_l]:
- xpos += 0.1
- if pressed[K_i]:
- ypos += 0.1
- elif pressed[K_k]:
- ypos -= 0.1
- # Calculate rotation matrix and multiply by camera matrix
- rotation = rotation_direction * rotation_speed * time_passed_seconds
- rotation_matrix = Matrix44.xyz_rotation(*rotation)
- camera_matrix *= rotation_matrix
- # Calcluate movment and add it to camera matrix translate
- heading = Vector3(camera_matrix.forward)
- movement = heading * movement_direction.z * movement_speed
- camera_matrix.translate += movement * time_passed_seconds
- # Upload the inverse camera matrix to OpenGL
- glLoadMatrixd(camera_matrix.get_inverse().to_opengl())
- # Light must be transformed as well
- glLight(GL_LIGHT0, GL_POSITION, (0, 1.5, 1, 0))
- shaders.glUseProgram(shader)#bind the shader
- glUniform1f(UNIFORM_LOCATIONS['xpos'],xpos)
- glUniform1f(UNIFORM_LOCATIONS['ypos'],ypos)
- #glActiveTexture(GL_TEXTURE0)
- #glBindTexture(GL_TEXTURE_2D, texture)
- glUniform1i(UNIFORM_LOCATIONS['thetexture'],0)
- #texture RETURNS 1, but IS #0, so lists might be wise.
- #print texture
- try:
- avbo.bind()#bind the vertex object
- try:
- glEnableVertexAttribArray( position )
- glEnableVertexAttribArray( texcoords )
- #4 bytes per number, 5 numbers, so 4*5 bytes between the start of each record.
- stride = 5*4
- glVertexAttribPointer(
- position,
- 3, GL_FLOAT,False, stride, avbo
- )
- glVertexAttribPointer(
- texcoords,
- 2, GL_FLOAT,False, stride, avbo+12
- )
- glDrawArrays(GL_TRIANGLES, 0, 9)
- finally:
- avbo.unbind() #unbind the vertex objct
- glDisableVertexAttribArray( position )
- glDisableVertexAttribArray( texcoords )
- finally:
- shaders.glUseProgram( 0 )#unbind the shader
- pygame.display.set_caption("TRIANGLES AT"+str(clock.get_fps())+" FPS", "TRIANGLES")
- # Show the screen by flipping buffers
- pygame.display.flip()
- run()#do the running
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement