Statistics
| Revision:

root / PyOpenGL-Demo / GLUT / shader_test.py @ 1

History | View | Annotate | Download (5.4 kB)

1
#! /usr/bin/env python
2
'''Tests rendering using shader objects from core GL or extensions
3

4
Uses the:
5
    Lighthouse 3D Tutorial toon shader
6
        http://www.lighthouse3d.com/opengl/glsl/index.php?toon2
7

8
By way of:
9
    http://www.pygame.org/wiki/GLSLExample
10
'''
11
import OpenGL 
12
OpenGL.ERROR_ON_COPY = True 
13
from OpenGL.GL import *
14
from OpenGL.GLU import *
15
from OpenGL.GLUT import *
16

    
17
# PyOpenGL 3.0.1 introduces this convenience module...
18
from OpenGL.GL.shaders import *
19

    
20
import time, sys
21
program = None
22

    
23
# A general OpenGL initialization function.  Sets all of the initial parameters. 
24
def InitGL(Width, Height):                # We call this right after our OpenGL window is created.
25
    glClearColor(0.0, 0.0, 0.0, 0.0)    # This Will Clear The Background Color To Black
26
    glClearDepth(1.0)                    # Enables Clearing Of The Depth Buffer
27
    glDepthFunc(GL_LESS)                # The Type Of Depth Test To Do
28
    glEnable(GL_DEPTH_TEST)                # Enables Depth Testing
29
    glShadeModel(GL_SMOOTH)                # Enables Smooth Color Shading
30
    
31
    glMatrixMode(GL_PROJECTION)
32
    glLoadIdentity()                    # Reset The Projection Matrix
33
                                        # Calculate The Aspect Ratio Of The Window
34
    gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
35

    
36
    glMatrixMode(GL_MODELVIEW)
37
 
38
    if not glUseProgram:
39
        print 'Missing Shader Objects!'
40
        sys.exit(1)
41
    global program
42
    program = compileProgram(
43
        compileShader('''
44
            varying vec3 normal;
45
            void main() {
46
                normal = gl_NormalMatrix * gl_Normal;
47
                gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
48
            }
49
        ''',GL_VERTEX_SHADER),
50
        compileShader('''
51
            varying vec3 normal;
52
            void main() {
53
                float intensity;
54
                vec4 color;
55
                vec3 n = normalize(normal);
56
                vec3 l = normalize(gl_LightSource[0].position).xyz;
57
            
58
                // quantize to 5 steps (0, .25, .5, .75 and 1)
59
                intensity = (floor(dot(l, n) * 4.0) + 1.0)/4.0;
60
                color = vec4(intensity*1.0, intensity*0.5, intensity*0.5,
61
                    intensity*1.0);
62
            
63
                gl_FragColor = color;
64
            }
65
    ''',GL_FRAGMENT_SHADER),)
66

    
67
# The function called when our window is resized (which shouldn't happen if you enable fullscreen, below)
68
def ReSizeGLScene(Width, Height):
69
    if Height == 0:                        # Prevent A Divide By Zero If The Window Is Too Small 
70
        Height = 1
71

    
72
    glViewport(0, 0, Width, Height)        # Reset The Current Viewport And Perspective Transformation
73
    glMatrixMode(GL_PROJECTION)
74
    glLoadIdentity()
75
    gluPerspective(45.0, float(Width)/float(Height), 0.1, 100.0)
76
    glMatrixMode(GL_MODELVIEW)
77

    
78
# The main drawing function. 
79
def DrawGLScene():
80
    # Clear The Screen And The Depth Buffer
81
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
82
    glLoadIdentity()                    # Reset The View 
83

    
84
    # Move Left 1.5 units and into the screen 6.0 units.
85
    glTranslatef(-1.5, 0.0, -6.0)
86

    
87
    if program:
88
        glUseProgram(program)
89
    glutSolidSphere(1.0,32,32)
90
    glTranslate( 1,0,2 )
91
    glutSolidCube( 1.0 )
92

    
93
    #  since this is double buffered, swap the buffers to display what just got drawn. 
94
    glutSwapBuffers()
95

    
96
# The function called whenever a key is pressed. Note the use of Python tuples to pass in: (key, x, y)  
97
def keyPressed(*args):
98
    # If escape is pressed, kill everything.
99
    if args[0] == '\x1b':
100
        sys.exit()
101

    
102
def main():
103
    global window
104
    # For now we just pass glutInit one empty argument. I wasn't sure what should or could be passed in (tuple, list, ...)
105
    # Once I find out the right stuff based on reading the PyOpenGL source, I'll address this.
106
    glutInit(sys.argv)
107

    
108
    # Select type of Display mode:   
109
    #  Double buffer 
110
    #  RGBA color
111
    # Alpha components supported 
112
    # Depth buffer
113
    glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
114
    
115
    # get a 640 x 480 window 
116
    glutInitWindowSize(640, 480)
117
    
118
    # the window starts at the upper left corner of the screen 
119
    glutInitWindowPosition(0, 0)
120
    
121
    # Okay, like the C version we retain the window id to use when closing, but for those of you new
122
    # to Python (like myself), remember this assignment would make the variable local and not global
123
    # if it weren't for the global declaration at the start of main.
124
    window = glutCreateWindow("Jeff Molofee's GL Code Tutorial ... NeHe '99")
125

    
126
       # Register the drawing function with glut, BUT in Python land, at least using PyOpenGL, we need to
127
    # set the function pointer and invoke a function to actually register the callback, otherwise it
128
    # would be very much like the C version of the code.    
129
    glutDisplayFunc(DrawGLScene)
130
    
131
    # Uncomment this line to get full screen.
132
    #glutFullScreen()
133

    
134
    # When we are doing nothing, redraw the scene.
135
    glutIdleFunc(DrawGLScene)
136
    
137
    # Register the function called when our window is resized.
138
    glutReshapeFunc(ReSizeGLScene)
139
    
140
    # Register the function called when the keyboard is pressed.  
141
    glutKeyboardFunc(keyPressed)
142

    
143
    # Initialize our window. 
144
    InitGL(640, 480)
145

    
146
    # Start Event Processing Engine    
147
    glutMainLoop()
148

    
149
# Print message to console, and kick off the main to get it rolling.
150

    
151
if __name__ == "__main__":
152
    print "Hit ESC key to quit."
153
    main()
154