Example #1
0
    def __init__(this):
        this.planeProgram = shaders.compileProgram(shaders.compileShader(plane_v, GL_VERTEX_SHADER),
            shaders.compileShader(plane_f, GL_FRAGMENT_SHADER)) 
        #the parameter tex0 must be use in shaders,otherwise the
        #glGetUniformLocation get -1
        this.planeProgram.tex0 = glGetUniformLocation(this.planeProgram,"tex0")
        this.planeProgram.tex1 = glGetUniformLocation(this.planeProgram,"tex1")        
        print (this.planeProgram.tex0,this.planeProgram.tex1)

        this.updateProgram = shaders.compileProgram(shaders.compileShader(update_v, GL_VERTEX_SHADER),
            shaders.compileShader(update_f, GL_FRAGMENT_SHADER)) 
        this.updateProgram.xl = glGetUniformLocation(this.updateProgram,"xw")
        this.updateProgram.yl = glGetUniformLocation(this.updateProgram,"yw")  
        this.updateProgram.height = glGetUniformLocation(this.updateProgram,"height")
        this.updateProgram.sphereRadius = glGetUniformLocation(this.updateProgram,"sphereRadius")   
        this.updateProgram.tex0 = glGetUniformLocation(this.updateProgram,"tex0")
        this.updateProgram.xz = glGetUniformLocation(this.updateProgram,"xz")
        this.updateProgram.hight = glGetUniformLocation(this.updateProgram,"hight")
        this.updateProgram.mMatrix = glGetUniformLocation(this.updateProgram,"mMatrix")
        this.updateProgram.vMatrix = glGetUniformLocation(this.updateProgram,"vMatrix")
        this.updateProgram.pMatrix = glGetUniformLocation(this.updateProgram,"pMatrix")

        this.gpgpuProgram = shaders.compileProgram(shaders.compileShader(gpgpu_v, GL_VERTEX_SHADER),
            shaders.compileShader(gpgpu_f, GL_FRAGMENT_SHADER)) 
        this.gpgpuProgram.tex0 = glGetUniformLocation(this.gpgpuProgram,"tex0")
        this.gpgpuProgram.xl = glGetUniformLocation(this.gpgpuProgram,"xw")
        this.gpgpuProgram.yl = glGetUniformLocation(this.gpgpuProgram,"yw")          
Example #2
0
    def __init__(self, vsrc, fsrc, csrc=None):
        path = os.path.dirname(os.path.realpath(__file__)) + "/shaders/"

        with open(path + fsrc, "r") as fin:
            src = fin.read()
        fragment = shaders.compileShader(src, GL_FRAGMENT_SHADER)
        with open(path + vsrc, "r") as fin:
            src = fin.read()
        vertex = shaders.compileShader(src, GL_VERTEX_SHADER)
        if csrc:
            with open(path + csrc, "r") as fin:
                src = fin.read()
                print(src)
            compute = shaders.compileShader(src, GL_COMPUTE_SHADER)
            self.program = shaders.compileProgram(fragment, vertex, compute)
            glDeleteShader(compute)
        else:
            self.program = shaders.compileProgram(fragment, vertex)

        glDeleteShader(fragment)
        glDeleteShader(vertex)

        self._delete_prog = glDeleteProgram

        self.locations = {}
Example #3
0
	def paintEvent(self, event):	
		# On OS X, when using QGLWidget, it is possible that the opengl draw framebuffer is not
		# completely constructed before entering paint event.
		# We just omit all paint event before framebuffer is fully initialized.
		if GL.glCheckFramebufferStatus(GL.GL_DRAW_FRAMEBUFFER) != GL.GL_FRAMEBUFFER_COMPLETE:
			return
			
		# Need this to make sure we are drawing on the correct GL context	
		self.makeCurrent()
		
		# Compile and link shaders only when OpenGL draw framebuffer is constructed
		if not self.programCompiled:
			self.vertexShader = shaders.compileShader(VERTEX_SHADER, GL.GL_VERTEX_SHADER)
			self.fragmentShader = shaders.compileShader(FRAGMENT_SHADER, GL.GL_FRAGMENT_SHADER)
			self.fragmentMarkerShader = shaders.compileShader(	FRAGMENT_MARKER_SHADER, GL.GL_FRAGMENT_SHADER)
			self.shader = shaders.compileProgram(self.vertexShader, self.fragmentShader)
			self.markerShader = shaders.compileProgram(self.vertexShader, self.fragmentMarkerShader)
			self.programCompiled = True
	
		GL.glShadeModel(GL.GL_FLAT)
		GL.glEnable(GL.GL_DEPTH_TEST)

		GL.glEnable(GL.GL_POINT_SMOOTH)
		GL.glHint(GL.GL_POINT_SMOOTH_HINT, GL.GL_NICEST)
		GL.glEnable(GL.GL_LINE_SMOOTH)
		GL.glHint(GL.GL_LINE_SMOOTH_HINT, GL.GL_NICEST)
		GL.glEnable(GL.GL_BLEND)
		GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)
		
		tv = math.tan(self.screen.parameterDialog.getVerticalFOV() * 0.5 / 180 * math.pi)
		th = math.tan(self.screen.parameterDialog.getHorizontalFOV() * 0.5 / 180 * math.pi)
		viewport_width = self.width()
		viewport_height = int(viewport_width * (tv / th))
		GL.glViewport((self.width() - viewport_width) / 2, (self.height() - viewport_height) / 2, viewport_width, viewport_height)
		
		GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
		
		self.updateCamera()				
		self.drawCoords()
		# self.drawCones()
		self.drawMarkers()
		self.drawGroups()
		
		GL.glDisable(GL.GL_CULL_FACE)
		GL.glDisable(GL.GL_DEPTH_TEST)
		
		GL.glPointSize(5)
		self.openGLDraw(self.shader, GL.GL_LINES, self.testVertexBuffer, self.testColorBuffer)
		
		painter = QtGui.QPainter(self)
		if len(self.mouseRect) > 0:
			painter.setPen(QtGui.QColor(0, 200, 50, 100))
			left = min(self.mouseRect[0].x(), self.mouseRect[1].x())
			top = min(self.mouseRect[0].y(), self.mouseRect[1].y())
			width = max(self.mouseRect[0].x(), self.mouseRect[1].x()) - left
			height = max(self.mouseRect[0].y(), self.mouseRect[1].y()) - top
			rect = QtCore.QRect(left, top, width, height)
			painter.drawRect(rect)
		painter.end()
Example #4
0
    def prepare_shaders(self):

        ### Base shader
        vertex = shaders.compileShader(self.BASIC_VERTEX_SHADER, GL_VERTEX_SHADER)
        fragment = shaders.compileShader(self.BASIC_FRAGMENT_SHADER, GL_FRAGMENT_SHADER)

        self.shader = shaders.compileProgram(vertex, fragment)

        self.set_shader_accessors(('u_modelMatrix',
                                   'u_viewProjectionMatrix',
                                   'u_normalMatrix',
                                   'u_lightPos',
                                   'u_materialDiffuse'),
                                  ('a_vertex',
                                   'a_normal'), self.shader)

        ### Flat shader
        flatvertex = shaders.compileShader(self.FLAT_VERTEX_SHADER, GL_VERTEX_SHADER)
        self.flatshader = shaders.compileProgram(flatvertex, fragment)

        self.set_shader_accessors(('u_modelMatrix',
                                   'u_viewProjectionMatrix',
                                   'u_materialDiffuse',),
                                  ('a_vertex',), self.flatshader)

        ### Silhouette shader
        silh_vertex = shaders.compileShader(self.SILHOUETTE_VERTEX_SHADER, GL_VERTEX_SHADER)
        self.silhouette_shader = shaders.compileProgram(silh_vertex, fragment)

        self.set_shader_accessors(('u_modelMatrix',
                                   'u_viewProjectionMatrix',
                                   'u_modelViewMatrix',
                                   'u_materialDiffuse',
                                   'u_bordersize'  # width of the silhouette
                                   ),
                                  ('a_vertex',
                                   'a_normal'), self.silhouette_shader)

        ### Gooch shader
        gooch_vertex = shaders.compileShader(self.GOOCH_VERTEX_SHADER, GL_VERTEX_SHADER)
        gooch_fragment = shaders.compileShader(self.GOOCH_FRAGMENT_SHADER, GL_FRAGMENT_SHADER)
        self.gooch_shader = shaders.compileProgram(gooch_vertex, gooch_fragment)

        self.set_shader_accessors(('u_modelMatrix',
                                   'u_viewProjectionMatrix',
                                   'u_normalMatrix',
                                   'u_lightPos',
                                   'u_materialDiffuse',
                                   'u_coolColor',
                                   'u_warmColor',
                                   'u_alpha',
                                   'u_beta'
                                   ),
                                  ('a_vertex',
                                   'a_normal'), self.gooch_shader)
	def initShaders(self):
		self.useShader = 1

		VERTEX_SHADER = shaders.compileShader("""#version 120
			uniform float end_fog;
			uniform vec4 fog_color;
			varying vec4 vertex_color;
			void main() {
				float fog;
				float fog_coord;
				gl_Position = ftransform();
				//gl_Position = gl_ProjectionMatrix * gl_ModelViewMatrix * gl_Vertex;
				vertex_color = gl_Color;
				fog_coord = abs(gl_Position.z);
				fog_coord = clamp( fog_coord, 0.0, end_fog);
				fog = (end_fog-fog_coord)/end_fog;
				fog = clamp( fog, 0.0, 3.0);
				gl_FrontColor = mix(fog_color, gl_Color, fog);

			}
		""", GL_VERTEX_SHADER )

		FRAGMENT_SHADER = shaders.compileShader("""
			void main() {
				gl_FragColor = gl_Color;
			}
		""",GL_FRAGMENT_SHADER)

		self.program = []
		self.program.append(shaders.compileProgram(VERTEX_SHADER, FRAGMENT_SHADER))

		VERTEX_SHADER = shaders.compileShader("""#version 120
			varying vec4 vertex_color;
			void main() {
				gl_Position = ftransform();
				gl_FrontColor = gl_Color;

			}
		""", GL_VERTEX_SHADER )

		FRAGMENT_SHADER = shaders.compileShader("""
			void main() {
				gl_FragColor = gl_Color;
			}
		""",GL_FRAGMENT_SHADER)

		self.program.append(shaders.compileProgram(VERTEX_SHADER, FRAGMENT_SHADER))

		self.UNIFORM_LOCATIONS = {
			'end_fog': glGetUniformLocation( self.program[0], 'end_fog' ),
			'fog_color': glGetUniformLocation( self.program[0], 'fog_color' ),
		}
Example #6
0
    def initializeGL(self):
        glViewport(0, 0, self.width(), self.height())
        # setup some OpenGL options
        glEnable(GL_DEPTH_TEST)

        vertexShader, fragmentShader = self.loadShaders("6.lighting.vs", "6.lighting.frag")
        self.__shader = shaders.compileProgram(vertexShader, fragmentShader)
        vertexShader, fragmentShader = self.loadShaders("6.hdr.vs", "6.hdr.frag")
        self.__hdrShader = shaders.compileProgram(vertexShader, fragmentShader)

        # light source
        self.lightPos = [
            np.array([0.0, 0.0, 49.5], np.float32),
            np.array([-1.4, -1.9, 9.0], np.float32),
            np.array([0.0, -1.0, 4.0], np.float32),
            np.array([0.8, -1.7, 6.0], np.float32),
        ]

        self.lightColors = [
            np.array([200.0, 200.0, 200.0], np.float32),
            np.array([0.1, 0.0, 0.0], np.float32),
            np.array([0.0, 0.0, 0.2], np.float32),
            np.array([0.0, 0.1, 0.0], np.float32),
        ]

        # load texture
        self.woodTexture = loadTexture(os.path.join(abPath, "..", "..", "resources", "textures", "wood.png"))

        # Set up floating point framebuffer to render scene to
        self.hdrFBO = glGenFramebuffers(1)
        # Create floating point color buffer
        self.colorBuffer = glGenTextures(1)
        glBindTexture(GL_TEXTURE_2D, self.colorBuffer)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA16F, self.width(), self.height(), 0, GL_RGBA, GL_FLOAT, None)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
        # create depth buffer (renderbuffer)
        self.rboDepth = glGenRenderbuffers(1)
        glBindRenderbuffer(GL_RENDERBUFFER, self.rboDepth)
        glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT, self.width(), self.height())
        # Attach buffer
        glBindFramebuffer(GL_FRAMEBUFFER, self.hdrFBO)
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, self.colorBuffer, 0)
        glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, self.rboDepth)
        if glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE:
            print "Framebuffer not complete!"
        glBindFramebuffer(GL_FRAMEBUFFER, 0)

        glClearColor(0.1, 0.1, 0.1, 1.0)
Example #7
0
 def __init__(self,contrast=1.0,*args,**kwargs):
     super(ShaderTexture, self).__init__(*args,**kwargs)
     """
     This contrast program comes from atduskgreg's shader example.
     See https://github.com/atduskgreg/Processing-Shader-Examples/
     """
     self.contrast_program = compileProgram(
         compileShader('''
             uniform sampler2D src_tex_unit0;
             uniform float contrast;
             void main() {
                 vec3 color = vec3(texture2D(src_tex_unit0, gl_TexCoord[0].st));
                 const vec3 LumCoeff = vec3(0.2125, 0.7154, 0.0721);
         
                 vec3 AvgLumin = vec3(0.5, 0.5, 0.5);
         
                 vec3 intensity = vec3(dot(color, LumCoeff));
         
                 // could substitute a uniform for this 1. and have variable saturation
                 vec3 satColor = mix(intensity, color, 1.);
                 vec3 conColor = mix(AvgLumin, satColor, contrast);
         
                 gl_FragColor = vec4(conColor, 1);
             }
         ''',gl.GL_FRAGMENT_SHADER))
     self.texture_loc = gl.glGetUniformLocation(self.contrast_program, "src_tex_unit0")
     self.contrast_loc = gl.glGetUniformLocation(self.contrast_program, "contrast")
     self.contrast = contrast
Example #8
0
File: dome.py Project: geo7/csci480
 def __init__(self,
              width = 25.0,
              peak = 26.0,
              vertShader = 'knotvertex.vs',
              fragShader = 'knotfragment.fs',
              shaderPositionName = 'position',
              shaderNormalName = 'normal',
              shaderTexcoordName = 'texcoord'):
     self.peak = peak
     self.width = width
     
     with open(os.path.join(os.getcwd(), vertShader)) as fp:
         vert = fp.read()
     with open(os.path.join(os.getcwd(), fragShader)) as fp:
         frag = fp.read()
     try:
         self.program = compileProgram(
             compileShader(vert, GL_VERTEX_SHADER),
             compileShader(frag, GL_FRAGMENT_SHADER))
     except RuntimeError as rte:
         print rte[0]
         raise
     self.positionLocation = glGetAttribLocation(self.program,
                                                 shaderPositionName)
     self.normalLocation = glGetAttribLocation(self.program,
                                               shaderNormalName)
     self.texcoordLocation = glGetAttribLocation(self.program,
                                                 shaderTexcoordName)
     self.makeDataBuffers()
Example #9
0
 def initializeGL(self):
     glClearColor(0, 0, 0, 0)
     
     # load shaders
     for shader in self.filters:
         # create shader from file
         vshader = shaderFromFile(GL_VERTEX_SHADER, 'shader.vert')
         fshader = shaderFromFile(GL_FRAGMENT_SHADER, shader)
         # compile shaders
         self.sprogram[shader] = shaders.compileProgram(vshader, fshader)
     
         # get attribute and set uniform for shaders
         glUseProgram(self.sprogram[shader])
         self.vertexAL = glGetAttribLocation(self.sprogram[shader], 'pos')
         self.tmUL = glGetUniformLocation(self.sprogram[shader], 'textureMap')
         glUniform1i(self.tmUL, 0)
         glUseProgram(0)
     
     # two triangle to make a quad
     self.vertices = np.array((0.0, 0.0, 
                               1.0, 0.0, 
                               1.0, 1.0, 
                               0.0, 1.0), dtype=np.float32)
     self.indices = np.array((0, 1, 2, 
                              0, 2, 3), dtype=np.ushort)
     
     # set up vertex array
     self.vaoID = glGenVertexArrays(1)
     self.vboVerticesID = glGenBuffers(1)
     self.vboIndicesID = glGenBuffers(1)
     
     glBindVertexArray(self.vaoID)
     glBindBuffer(GL_ARRAY_BUFFER, self.vboVerticesID)
     # copy vertices data from memery to gpu memery
     glBufferData(GL_ARRAY_BUFFER, self.vertices.nbytes, self.vertices, GL_STATIC_DRAW)
     # tell opengl how to procces the vertices data
     glEnableVertexAttribArray(self.vertexAL)
     glVertexAttribPointer(self.vertexAL, 2, GL_FLOAT, GL_FALSE, 0, None)
     # send the indice data too
     glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.vboIndicesID)
     glBufferData(GL_ELEMENT_ARRAY_BUFFER, self.indices.nbytes, self.indices, GL_STATIC_DRAW)
     
     # flip the image in the Y axis
     im = self.im.transpose(Image.FLIP_TOP_BOTTOM)
     
     # set up texture
     self.textureID = glGenTextures(1)
     glActiveTexture(GL_TEXTURE0)
     glBindTexture(GL_TEXTURE_2D, self.textureID)
     # set filters
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
     # set uv coords mode
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
     glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
     # send the image data to gpu memery
     glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, self.im.size[0], self.im.size[1], 
                  0, GL_RGB, GL_UNSIGNED_BYTE, im.tostring())
     
     print("Initialization successfull")
	def OnInit(self):
		vertex_shader = shaders.compileShader(
			"""
			void main()
			{
				gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
			}
			""",
			GL_VERTEX_SHADER)
		fragment_shader = shaders.compileShader(
			"""
			void main()
			{
				gl_FragColor = vec4(0, 1, 0, 1);
			}
			""",
			GL_FRAGMENT_SHADER)
		self.shader = shaders.compileProgram(vertex_shader, fragment_shader)
		self.vbo = vbo.VBO(
			array([
				[0, 1, 0],
				[-1, -1, 0],
				[1, -1, 0],
				[2, -1, 0],
				[4, -1, 0],
				[4, 1, 0],
				[2, -1, 0],
				[4, 1, 0],
				[2, 1, 0]
				], "f"))
Example #11
0
def initializeShaders():
    global theShaders, positionAttrib
    theShaders = compileProgram(
        compileShader(strVertexShader, GL_VERTEX_SHADER),
        compileShader(strFragmentShader, GL_FRAGMENT_SHADER)
    )
    positionAttrib = glGetAttribLocation(theShaders, "position")
def initialize_program():
    global offsetUniform, perspectiveMatrixUnif, SCREENSIZE
    """
    Instead of calling OpenGL's shader compilation functions directly
    (glShaderSource, glCompileShader, etc), we use PyOpenGL's wrapper
    functions, which are much simpler to use.
    """
    global theProgram
    theProgram = compileProgram(
        compileShader(strVertexShader, GL.GL_VERTEX_SHADER),
        compileShader(strFragmentShader, GL.GL_FRAGMENT_SHADER)
    )
    offsetUniform = GL.glGetUniformLocation(theProgram, 'offset')
    perspectiveMatrixUnif = GL.glGetUniformLocation(theProgram, 'perspectiveMatrix')
    fFrustumScale = 1.0
    fzNear = 0.5
    fzFar = 3.0

    w,h = SCREENSIZE
    theMatrix = N.zeros(16, dtype=N.float32)
    theMatrix[0] = fFrustumScale*float(h)/float(w)
    theMatrix[5] = fFrustumScale
    theMatrix[10] = (fzFar + fzNear) / (fzNear - fzFar)
    theMatrix[14] = (2 * fzFar * fzNear) / (fzNear - fzFar)
    theMatrix[11] = -1.0

    GL.glUseProgram(theProgram)
    GL.glUniformMatrix4fv(perspectiveMatrixUnif, 1, GL.GL_FALSE, theMatrix)
    GL.glUseProgram(0);
Example #13
0
def initializeShaders():
    global theShaders, positionAttrib, normalAttrib, tangentAttrib,\
        bitangentAttrib, uvAttrib, \
        modelUnif, viewUnif, projUnif, lightUnif, \
        colorSamplerUnif, normalSamplerUnif, scaleuvUnif, colorUnif
    theShaders = compileProgram(
        compileShader(strVertexShader, GL_VERTEX_SHADER),
        compileShader(strFragmentShader, GL_FRAGMENT_SHADER)
    )
    positionAttrib = glGetAttribLocation(theShaders, "position")
    normalAttrib = glGetAttribLocation(theShaders, "normal")
    
    lightUnif = glGetUniformLocation(theShaders, "light")
    modelUnif = glGetUniformLocation(theShaders, "model")
    viewUnif = glGetUniformLocation(theShaders, "view")
    projUnif = glGetUniformLocation(theShaders, "projection")
    colorSamplerUnif = glGetUniformLocation(theShaders, "colorsampler")
    normalSamplerUnif = glGetUniformLocation(theShaders, "normalsampler")
    colorUnif = glGetUniformLocation(theShaders, "color")

    check("positionAttrib", positionAttrib)
    check("normalAttrib", normalAttrib)
    
    check("modelUnif", modelUnif)
    check("viewUnif", viewUnif)
    check("projUnif", projUnif)
    check("lightUnif", lightUnif)
    check("colorUnif", colorUnif)
Example #14
0
    def initialize(self):
        vertex_shader = shaders.compileShader("""#version 330
            in vec3 vPosition;
            uniform mat4 MVP;

            void main()
            {
                gl_Position = MVP * vec4(vPosition, 1.0);
            }""", gl.GL_VERTEX_SHADER)

        fragment_shader = shaders.compileShader("""#version 330
            void main() 
            {
                gl_FragColor = vec4( 0, 1, 1, 1 );
            }""", gl.GL_FRAGMENT_SHADER)

        self._shader = shaders.compileProgram(vertex_shader, fragment_shader)
        self._position_handle = 0
        gl.glBindAttribLocation(self._shader, self._position_handle, b"vPosition")
        self._mvp_handle = gl.glGetUniformLocation(self._shader, b"MVP")

        self._vertex_vbo = gl.glGenBuffers(1)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self._vertex_vbo)
        gl.glBufferData(gl.GL_ARRAY_BUFFER, len(self._model._vertex_buffer), self._model._vertex_buffer, gl.GL_STATIC_DRAW)
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)

        self._index_vbo = gl.glGenBuffers(1)
        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, self._index_vbo)
        gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, len(self._model._index_buffer), self._model._index_buffer, gl.GL_STATIC_DRAW)
        gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, 0)
Example #15
0
    def __compileShaders(self):
        vertex_shader = shaders.compileShader("""
            varying vec2 uv;
            varying vec3 normal;
            varying vec4 ecPos;
            void main()
            {
                uv = gl_MultiTexCoord0;
                ecPos = gl_ModelViewMatrix * gl_Vertex;
                normal = normalize(gl_NormalMatrix * gl_Normal);
                gl_Position = ftransform();
            }
            """, GL_VERTEX_SHADER)

        fragment_shader = shaders.compileShader("""
            varying vec2 uv;
            varying vec3 normal;
            varying vec4 ecPos;
            uniform sampler2D tex;
            void main()
            {
                gl_FragColor = texture2D(tex, uv);
            }
            """, GL_FRAGMENT_SHADER)

        self.__shaders = shaders.compileProgram(vertex_shader, fragment_shader)
        self.__recompileShader = False
Example #16
0
	def __init__ ( self, title="title", width=640, height=480, pos_x=50, pos_y=50, 
					vertex_shader=None, fragment_shader=None ):
	 
		# initialize GLUT library ( cf. window handling, user interactions )
		glutInit( sys.argv )
		glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH )
		# glutFullScreen()

		# initialize and create window
		glutInitWindowPosition( pos_x, pos_y ) 	# set upper left corner on screen
		glutInitWindowSize( width, height )
		self.window = glutCreateWindow( title )

		# register callback functions
		glutDisplayFunc( self.display )
		# glutIdleFunc( self.display )
		glutReshapeFunc( self.reshape )		# called on window creation as well
		glutKeyboardFunc( self.keyboard )
		glutMouseFunc( self.mouse )

		# specify clear values for some buffers and the shading technique to use
		# ( noted for explicity only, values are the defaults )
		glClearColor( 0.0, 0.0, 0.0, 0.0 )	# range [0;1]
		glClearDepth( 1.0 )					# range [0;1]
		glShadeModel( GL_SMOOTH )			# GL_FLAT or GL_SMOOTH

		# compile shaders
		if vertex_shader and fragment_shader:
			self.shader = shaders.compileProgram ( # uses OpenGL.GL.shaders
							shaders.compileShader( vertex_shader, GL_VERTEX_SHADER ),
							shaders.compileShader( fragment_shader, GL_FRAGMENT_SHADER ) )
			glUseProgram( self.shader )
    def initializeGL(self):
        vertexShader, fragmentShader = self.loadShaders()
        self.__shaderProgram = shaders.compileProgram(vertexShader, fragmentShader)

        vertices = np.array([
            #  position           colors
            0.5, -0.5, 0.0,     1.0, 0.0, 0.0,
            -0.5, -0.5, 0.0,   0.0, 1.0, 0.0,
            0.0, 0.5, 0.0,     0.0, 0.0, 1.0,
            ], np.float32)

        self.__vao = glGenVertexArrays(1)
        vbo = glGenBuffers(1)

        glBindVertexArray(self.__vao)

        glBindBuffer(GL_ARRAY_BUFFER, vbo)
        glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)

        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * vertices.itemsize, None)
        glEnableVertexAttribArray(0)

        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * vertices.itemsize, ctypes.c_void_p(3 * vertices.itemsize))
        glEnableVertexAttribArray(1)

        glBindBuffer(GL_ARRAY_BUFFER, 0)

        glBindVertexArray(0)
Example #18
0
    def initializeProgram(self):
        shaderList = []

        shaderList.append(compileShader(VERTEX_SHADER, GL.GL_VERTEX_SHADER))
        shaderList.append(compileShader(FRAGMENT_SHADER, GL.GL_FRAGMENT_SHADER))

        self.theProgram = compileProgram(*shaderList)
Example #19
0
    def initializeProgram(self):
        shaderList = []

        shaderList.append(compileShader(VERTEX_SHADER, GL.GL_VERTEX_SHADER))
        shaderList.append(compileShader(FRAGMENT_SHADER, GL.GL_FRAGMENT_SHADER))

        self.theProgram = compileProgram(*shaderList)

        self.positionAttrib = GL.glGetAttribLocation(self.theProgram, "position")
        self.colorAttrib = GL.glGetAttribLocation(self.theProgram, "color")

        self.modelToCameraMatrixUnif = GL.glGetUniformLocation(self.theProgram, "modelToCameraMatrix")
        self.cameraToClipMatrixUnif = GL.glGetUniformLocation(self.theProgram, "cameraToClipMatrix")

        fzNear = 1.0
        fzFar = 61.0

        self.cameraToClipMatrix[0, 0] = self.fFrustumScale
        self.cameraToClipMatrix[1, 1] = self.fFrustumScale
        self.cameraToClipMatrix[2, 2] = (fzFar+fzNear)/(fzNear-fzFar)
        self.cameraToClipMatrix[2, 3] = -1.0
        self.cameraToClipMatrix[3, 2] = (2*fzFar*fzNear)/(fzNear-fzFar)

        GL.glUseProgram(self.theProgram)
        GL.glUniformMatrix4fv(self.cameraToClipMatrixUnif,1,GL.GL_FALSE,self.cameraToClipMatrix.tolist())
        GL.glUseProgram(0)
Example #20
0
 def compile_shader(self):
     vertex = shaders.compileShader(self.VERTEX_SHADER,
                                    GL_VERTEX_SHADER)
     fragment = shaders.compileShader(self.FRAGMENT_SHADER,
                                      GL_FRAGMENT_SHADER)
     
     self.shader = shaders.compileProgram(vertex, fragment)
Example #21
0
 def __init__(self, vert_src, frag_src, attribs):
     self.program = compileProgram(
         compileShader(vert_src, GL.GL_VERTEX_SHADER), compileShader(frag_src, GL.GL_FRAGMENT_SHADER)
     )
     self.attrib = {}
     for attrib in attribs:
         self.attrib[attrib] = GL.glGetAttribLocation(self.program, attrib)
Example #22
0
def initializeShaders():
    global theShaders, positionAttrib, uvAttrib, \
           modelUnif, viewUnif, projUnif, \
           samplerUnif, scaleuvUnif
    theShaders = compileProgram(
        compileShader(strVertexShader, GL_VERTEX_SHADER),
        compileShader(strFragmentShader, GL_FRAGMENT_SHADER)
    )
    positionAttrib = glGetAttribLocation(theShaders, "position")
    uvAttrib = glGetAttribLocation(theShaders, "uv")
    
    modelUnif = glGetUniformLocation(theShaders, "model")
    viewUnif = glGetUniformLocation(theShaders, "view")
    projUnif = glGetUniformLocation(theShaders, "projection")
    samplerUnif = glGetUniformLocation(theShaders, "sampler")
    scaleuvUnif = glGetUniformLocation(theShaders, "scaleuv")

    check("positionAttrib", positionAttrib)
    check("uvAttrib", uvAttrib)
    
    check("modelUnif", modelUnif)
    check("viewUnif", viewUnif)
    check("projUnif", projUnif)
    check("samplerUnif", samplerUnif)
    check("scaleuvUnif", scaleuvUnif)
Example #23
0
def shades():
    """Set up the Vertex and Fragment Shaders."""
    global shaderp

    vertex_shader = shaders.compileShader("""#version 330 core
    layout (location = 0) in vec3 position;
    layout (location = 1) in vec3 normal;
    layout (location = 2) in vec3 colour;
    layout (location = 3) in vec2 texcord;
    uniform mat4 projectmatrix;
    uniform mat4 viewmatrix;
    uniform mat4 modelmatrix;
    out vec3 ourcolour;
    out vec2 ourtex;
    void main(){
        gl_Position = projectmatrix * viewmatrix * modelmatrix * vec4(position, 1.0);
        ourcolour = colour;
        ourtex = texcord;
    }""", GL.GL_VERTEX_SHADER)
    fragment_shader = shaders.compileShader("""#version 330 core
    in vec3 ourcolour;
    in vec2 ourtex;
    out vec4 colour;
    uniform sampler2D tex;
    void main(){
        colour = texture(tex, ourtex) * vec4(ourcolour, 1.0);
    }""", GL.GL_FRAGMENT_SHADER)
    shaderp = shaders.compileProgram(vertex_shader, fragment_shader)
    GL.glUseProgram(shaderp)
Example #24
0
 def __init__(self, resolution = (400,400), maxfps = 1):
     #Here we set everything up initially.
     #This will only be executed once.
     #Variables with the self-prefix are variables that can be used by other functions
     #within this particular class. I don't know if they span across other classes but
     #that would be kinda wierd, no?
     
     pg.init()
     self.resolution, self.maxfps = resolution, maxfps
     pg.display.set_mode(self.resolution, pg.OPENGL|pg.DOUBLEBUF)
     
     self.running = True #Is the program running?
     
     #We setup the shader. I think you later compile the shader in a
     #seperate file so this won't be so cluttered
     try:
         with open("VERTEX_SHADER.txt", 'r') as fileInput: ##LOADING VERTEX_SHADER-specs FROM EXTERNAL FILE
             VERTEX_SHADER = GLshaders.compileShader(fileInput.read(), GL.GL_VERTEX_SHADER)
         del fileInput #Cleanup!
     except(GL.GLError, RuntimeError) as err:
         print("Shader compile error (VERTEX_SHADER)", err)
     
     try:
         with open("FRAGMENT_SHADER.txt", 'r') as fileInput: ##LOADING VERTEX_SHADER-specs FROM EXTERNAL FILE
             FRAGMENT_SHADER = GLshaders.compileShader(fileInput.read(), GL.GL_FRAGMENT_SHADER)
         del fileInput #Cleanup!
     except(GL.GLError, RuntimeError) as err:
         print("Shader compile error (FRAGMENT_SHADER)", err)
     
     #The shader is compiled. Remember! This only happens once!
     #So no more changes after this point!
     self.GLEngineShader = GLshaders.compileProgram(VERTEX_SHADER, FRAGMENT_SHADER)
Example #25
0
def compileShaderProgram(*stages, **named):
    try:
        return shaders.compileProgram(*stages, **named)
    except RuntimeError as e:
        print 'Error while linking shader'
        print e
        print e.__dict__
Example #26
0
def init_context(name, modelview_matrix, projection_matrix):
    state = get_state()
    with open(state["shaders"][name]['vertex_shader_path']) as f:
        vertex_shader_text = f.read()
    vertex_shader = shaders.compileShader(vertex_shader_text, GL_VERTEX_SHADER)
    with open(state["shaders"][name]['fragment_shader_path']) as f:
        fragment_shader_text = f.read()
    fragment_shader = shaders.compileShader(fragment_shader_text, GL_FRAGMENT_SHADER)
    shader = shaders.compileProgram(vertex_shader, fragment_shader)

    #print "init interface state: ", state

    position_location = glGetAttribLocation(shader, 'position')
    normal_location = glGetAttribLocation(shader, 'normal')
    color_location = glGetAttribLocation(shader, 'color')
    modelview_location = glGetUniformLocation(shader, 'modelViewMatrix')
    projection_location = glGetUniformLocation(shader, 'projectionMatrix')


    contexts[name] = {
        'shader': shader,
        'modelview': {
            'location': modelview_location,
            'matrix': modelview_matrix
        },
        'projection': {
            'location': projection_location,
            'matrix': projection_matrix
        },
        'position_location': position_location,
        'color_location': color_location,
        'normal_location': normal_location,
        'thing': state[name]
    }
Example #27
0
 def __init__(self, size = 0.2):
   self.size = size
   self.vertexShader = shaders.compileShader(VERTEX_SOURCE, GL_VERTEX_SHADER)
   self.fragmentShader = shaders.compileShader(FRAGMENT_SOURCE, GL_FRAGMENT_SHADER)
   self.shader = shaders.compileProgram(self.vertexShader,self.fragmentShader)
   self.vao = glGenVertexArrays(1)
   glBindVertexArray(self.vao)
Example #28
0
    def __init__(self):
        self.vertexshader = shaders.compileShader("""
        attribute vec2 position;
        attribute vec4 color;

        uniform vec2 resolution;
        uniform vec2 scroll;

        varying vec4 v_color;
        void main() {
            vec2 p = (position + scroll) / resolution * 2.0 - 1.0;
            gl_Position = vec4(p.x, -p.y, 0.0, 1.0);
            v_color = color;
        }""", GL_VERTEX_SHADER)
        self.fragmentshader = shaders.compileShader("""
        varying vec4 v_color;

        void main() {
            gl_FragColor = v_color;
        }""", GL_FRAGMENT_SHADER)
        self.shader = shaders.compileProgram(
            self.vertexshader,
            self.fragmentshader)
        self.vbo = glGenBuffers(1)
        self.vertices = []
        self.vertexcount = 0
        self.dirty = True
    def OnInit( self ):
        VERTEX_SHADER = shaders.compileShader("""#version 120
        void main() {
            gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
        }""", GL_VERTEX_SHADER)

        FRAGMENT_SHADER = shaders.compileShader("""#version 120
        uniform vec4 color;
        void main() {
            gl_FragColor = color;
        }""", GL_FRAGMENT_SHADER)

        self.shader = shaders.compileProgram(VERTEX_SHADER,FRAGMENT_SHADER)


        self.vbo = vbo.VBO(
            array( [
                [ -2,-2, 0 ],
                [  2,-2, 0 ],
                [  2, 2, 0 ],
                [ -2,-2, 0 ],
                [  2, 2, 0 ],
                [ -2, 2, 0 ],
            ],'f')
        )
Example #30
0
    def initializeProgram(self):
        shaderList = []

        shaderList.append(compileShader(VERTEX_SHADER, GL.GL_VERTEX_SHADER))
        shaderList.append(compileShader(FRAGMENT_SHADER, GL.GL_FRAGMENT_SHADER))

        self.theProgram = compileProgram(*shaderList)

        self.offsetUniform = GL.glGetUniformLocation(self.theProgram, "offset")

        self.perspectiveMatrixUnif = GL.glGetUniformLocation(self.theProgram, "perspectiveMatrix")

        fFrustumScale = 1.0
        fzNear = 0.5
        fzFar = 3.0

        theMatrix = [0.0 for i in range(16)]
        theMatrix[0] = fFrustumScale
        theMatrix[5] = fFrustumScale
        theMatrix[10] = (fzFar+fzNear)/(fzNear-fzFar)
        theMatrix[14] = (2*fzFar*fzNear)/(fzNear-fzFar)
        theMatrix[11] = -1.0

        GL.glUseProgram(self.theProgram)
        GL.glUniformMatrix4fv(self.perspectiveMatrixUnif,1,GL.GL_FALSE,theMatrix)
        GL.glUseProgram(0)
Example #31
0
    def prepare_shaders(self):

        phong_weightCalc = """
        float phong_weightCalc(
            in vec3 light_pos, // light position
            in vec3 frag_normal // geometry normal
        ) {
            // returns vec2( ambientMult, diffuseMult )
            float n_dot_pos = max( 0.0, dot(
                frag_normal, light_pos
            ));
            return n_dot_pos;
        }
        """

        vertex = shaders.compileShader( phong_weightCalc +
        """
        uniform vec4 Global_ambient;
        uniform vec4 Light_ambient;
        uniform vec4 Light_diffuse;
        uniform vec3 Light_location;
        uniform vec4 Material_ambient;
        uniform vec4 Material_diffuse;
        attribute vec3 Vertex_position;
        attribute vec3 Vertex_normal;
        varying vec4 baseColor;
        void main() {
            gl_Position = gl_ModelViewProjectionMatrix * vec4(
                Vertex_position, 1.0
            );
            vec3 EC_Light_location = gl_NormalMatrix * Light_location;
            float diffuse_weight = phong_weightCalc(
                normalize(EC_Light_location),
                normalize(gl_NormalMatrix * Vertex_normal)
            );
            baseColor = clamp(
            (
                // global component
                (Global_ambient * Material_ambient)
                // material's interaction with light's contribution
                // to the ambient lighting...
                + (Light_ambient * Material_ambient)
                // material's interaction with the direct light from
                // the light.
                + (Light_diffuse * Material_diffuse * diffuse_weight)
            ), 0.0, 1.0);
        }""", GL_VERTEX_SHADER)

        fragment = shaders.compileShader("""
        varying vec4 baseColor;
        void main() {
            gl_FragColor = baseColor;
        }
        """, GL_FRAGMENT_SHADER)

        self.shader = shaders.compileProgram(vertex,fragment)
        self.set_shader_accessors( (
            'Global_ambient',
            'Light_ambient','Light_diffuse','Light_location',
            'Material_ambient','Material_diffuse',
        ), (
            'Vertex_position','Vertex_normal',
        ), self.shader)
Example #32
0
glutInit(sys.argv)
glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB | GLUT_DEPTH)
glutInitWindowSize(SIZE, SIZE)
glutCreateWindow("Hello GPU")

# Set viewport to match frame size
glViewport(0, 0, SIZE, SIZE)

# Set clear color and clear (same as in javascript example)
glClearColor(0.5, 0.7, 0.6, 1.0)
glClear(GL_COLOR_BUFFER_BIT)

# Compile the shaders
vertex_shader = shaders.compileShader(vertex_shader, GL_VERTEX_SHADER)
fragment_shader = shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER)
program = shaders.compileProgram(vertex_shader, fragment_shader)

# Activate the compiled shader program
shaders.glUseProgram(program)

# Make a quadrilateral that will serve as the drawing surface
# Remember that WebGL descends from OpenGL for drawing 3D scenes
# Think of this as a minimal 3D model serving as a "screen"
buffer = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, buffer)
glBufferData(GL_ARRAY_BUFFER,
             float32([-1, -1, 1, -1, -1, 1, -1, 1, 1, -1, 1, 1]),
             GL_STATIC_DRAW)
# We also need to manually pass arguments to the shader
positionLocation = glGetAttribLocation(program, "a_position")
glEnableVertexAttribArray(positionLocation)
Example #33
0
    def __init__(self):
        glClearColor(0.0, 0.0, 0.0, 0.0)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        vertex_shader = shaders.compileShader(
            """#version 430 core
        layout (location = 0) in vec4 vPosition;

        out gl_PerVertex {
            vec4 gl_Position;
        };

        void main() {
            gl_Position = vPosition;
        }""", GL_VERTEX_SHADER)

        fragment_shader_red = shaders.compileShader(
            """#version 430 core
        out vec4 fColor;

        void main() {
            fColor = vec4(1.0, 0.0, 0.0, 1.0);
        }""", GL_FRAGMENT_SHADER)

        fragment_shader_green = shaders.compileShader(
            """#version 430 core
        out vec4 fColor;

        void main() {
            fColor = vec4(0.0, 1.0, 0.0, 1.0);
        }""", GL_FRAGMENT_SHADER)

        self.position_shader = shaders.compileProgram(vertex_shader,
                                                      separable=True)

        self.red_shader = shaders.compileProgram(fragment_shader_red,
                                                 separable=True)

        self.green_shader = shaders.compileProgram(fragment_shader_green,
                                                   separable=True)

        self.pipeline_red = GLuint()
        glGenProgramPipelines(1, self.pipeline_red)
        glUseProgramStages(self.pipeline_red, GL_VERTEX_SHADER_BIT,
                           self.position_shader)
        glUseProgramStages(self.pipeline_red, GL_FRAGMENT_SHADER_BIT,
                           self.red_shader)

        self.pipeline_green = GLuint()
        glGenProgramPipelines(1, self.pipeline_green)
        glUseProgramStages(self.pipeline_green, GL_VERTEX_SHADER_BIT,
                           self.position_shader)
        glUseProgramStages(self.pipeline_green, GL_FRAGMENT_SHADER_BIT,
                           self.green_shader)

        self.vbo = vbo.VBO(
            array([
                [-0.90, -0.90],
                [0.85, -0.90],
                [-0.90, 0.85],
                [0.90, -0.85],
                [0.90, 0.90],
                [-0.85, 0.90],
            ], 'f'))
        self.vbo.bind()

        glVertexAttribPointer(0, 2, GL_FLOAT, False, 0, self.vbo)
        glEnableVertexAttribArray(0)
if not glfw.init():
    raise Exception('glfw con not be initialized')

window = glfw.create_window(1280, 720, 'My OpenGL window', None, None)

if not window:
    glfw.terminate()
    raise Exception('glfw window can not be created')

glfw.set_window_pos(window, 4000, 200)
glfw.set_cursor_pos(window, WINDOW_RESOLUTION[0] / 2, WINDOW_RESOLUTION[1] / 2)
glfw.set_window_size_callback(window, window_resize)
glfw.set_cursor_pos_callback(window, cursor_position_callback)
glfw.make_context_current(window)

light_shader = compileProgram(compileShader(light_vs, GL_VERTEX_SHADER),
                              compileShader(light_fs, GL_FRAGMENT_SHADER))
# lamp_shader = compileProgram(compileShader(lamp_vs, GL_VERTEX_SHADER), compileShader(lamp_fs, GL_FRAGMENT_SHADER))

texture = glGenTextures(2)
load_texture('lightning_test/textures/container.png', texture[0])
load_texture('lightning_test/textures/container_specular.png', texture[1])

### BOX ###############################
box_VAO = glGenVertexArrays(1)
glBindVertexArray(box_VAO)

VBO = glGenBuffers(1)
glBindBuffer(GL_ARRAY_BUFFER, VBO)
glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)

glEnableVertexAttribArray(0)
    def initializeGL(self):
        # setup some OpenGL options
        glEnable(GL_DEPTH_TEST)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

        vertexShader, fragmentShader = self.loadShaders()
        self.__shaderProgram = shaders.compileProgram(vertexShader, fragmentShader)

        vertices = np.array([
            -0.5, -0.5, -0.5,  0.0, 0.0,
             0.5, -0.5, -0.5,  1.0, 0.0,
             0.5,  0.5, -0.5,  1.0, 1.0,
             0.5,  0.5, -0.5,  1.0, 1.0,
            -0.5,  0.5, -0.5,  0.0, 1.0,
            -0.5, -0.5, -0.5,  0.0, 0.0,

            -0.5, -0.5,  0.5,  0.0, 0.0,
             0.5, -0.5,  0.5,  1.0, 0.0,
             0.5,  0.5,  0.5,  1.0, 1.0,
             0.5,  0.5,  0.5,  1.0, 1.0,
            -0.5,  0.5,  0.5,  0.0, 1.0,
            -0.5, -0.5,  0.5,  0.0, 0.0,

            -0.5,  0.5,  0.5,  1.0, 0.0,
            -0.5,  0.5, -0.5,  1.0, 1.0,
            -0.5, -0.5, -0.5,  0.0, 1.0,
            -0.5, -0.5, -0.5,  0.0, 1.0,
            -0.5, -0.5,  0.5,  0.0, 0.0,
            -0.5,  0.5,  0.5,  1.0, 0.0,

             0.5,  0.5,  0.5,  1.0, 0.0,
             0.5,  0.5, -0.5,  1.0, 1.0,
             0.5, -0.5, -0.5,  0.0, 1.0,
             0.5, -0.5, -0.5,  0.0, 1.0,
             0.5, -0.5,  0.5,  0.0, 0.0,
             0.5,  0.5,  0.5,  1.0, 0.0,

            -0.5, -0.5, -0.5,  0.0, 1.0,
             0.5, -0.5, -0.5,  1.0, 1.0,
             0.5, -0.5,  0.5,  1.0, 0.0,
             0.5, -0.5,  0.5,  1.0, 0.0,
            -0.5, -0.5,  0.5,  0.0, 0.0,
            -0.5, -0.5, -0.5,  0.0, 1.0,

            -0.5,  0.5, -0.5,  0.0, 1.0,
             0.5,  0.5, -0.5,  1.0, 1.0,
             0.5,  0.5,  0.5,  1.0, 0.0,
             0.5,  0.5,  0.5,  1.0, 0.0,
            -0.5,  0.5,  0.5,  0.0, 0.0,
            -0.5,  0.5, -0.5,  0.0, 1.0
            ], np.float32)

        self.planeVertices = np.array([
            # Positions     Texture Coords (note we set these higher than 1 that together with GL_REPEAT as texture wrapping mode will cause the floor texture to repeat)
            5.0, -0.5, 5.0, 2.0, 0.0,
            -5.0, -0.5, 5.0, 0.0, 0.0,
            -5.0, -0.5, -5.0, 0.0, 2.0,

            5.0, -0.5, 5.0, 2.0, 0.0,
            -5.0, -0.5, -5.0, 0.0, 2.0,
            5.0, -0.5, -5.0, 2.0, 2.0
        ], np.float32)

        self.transparentVertices = np.array([
            # Position     # Texture Coords (swapped y coordinates because texture is flipped upside down)
            0.0, 0.5, 0.0, 0.0, 0.0,
            0.0, -0.5, 0.0, 0.0, 1.0,
            1.0, -0.5, 0.0, 1.0, 1.0,
            0.0, 0.5, 0.0, 0.0, 0.0,
            1.0, -0.5, 0.0, 1.0, 1.0,
            1.0, 0.5, 0.0, 1.0, 0.0
        ], np.float32)

        # setup cube VAO
        self.cubeVAO = glGenVertexArrays(1)
        vbo = glGenBuffers(1)

        glBindVertexArray(self.cubeVAO)

        glBindBuffer(GL_ARRAY_BUFFER, vbo)
        glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)

        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * vertices.itemsize, None)
        glEnableVertexAttribArray(0)

        glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * vertices.itemsize, ctypes.c_void_p(3 * vertices.itemsize))
        glEnableVertexAttribArray(1)

        # setup plane VAO
        self.planeVAO = glGenVertexArrays(1)
        planeVBO = glGenBuffers(1)

        glBindVertexArray(self.planeVAO)
        glBindBuffer(GL_ARRAY_BUFFER, planeVBO)
        glBufferData(GL_ARRAY_BUFFER, self.planeVertices.nbytes, self.planeVertices, GL_STATIC_DRAW)
        glEnableVertexAttribArray(0)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * self.planeVertices.itemsize, None)
        glEnableVertexAttribArray(1)
        glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * self.planeVertices.itemsize, ctypes.c_void_p(3 * self.planeVertices.itemsize))
        glBindBuffer(GL_ARRAY_BUFFER, 0)

        glBindVertexArray(0)

        # setup transparent plane VAO
        self.transparentVAO = glGenVertexArrays(1)
        transparentVBO = glGenBuffers(1)
        glBindVertexArray(self.transparentVAO)
        glBindBuffer(GL_ARRAY_BUFFER, transparentVBO)
        glBufferData(GL_ARRAY_BUFFER, self.transparentVertices.nbytes, self.transparentVertices, GL_STATIC_DRAW)
        glEnableVertexAttribArray(0)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * self.transparentVertices.itemsize, None)
        glEnableVertexAttribArray(1)
        glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * self.transparentVertices.itemsize, ctypes.c_void_p(3 * self.transparentVertices.itemsize))
        glBindVertexArray(0)

        # load and create a texture
        texturePath = os.path.join(abPath, '..', '..', 'resources', 'textures', 'marble.jpg')
        self.cubeTexture = loadTexture(texturePath)
        texture2Path = os.path.join(abPath, '..', '..', 'resources', 'textures', 'metal.png')
        self.floorTexture = loadTexture(texture2Path)
        texture3Path = os.path.join(abPath, '..', '..', 'resources', 'textures', 'window.png')
        self.transparentTexture = loadTexture(texture3Path)

        self.vegetation = ((-1.5, 0.0, -0.48),
                           (1.5, 0.0, 0.51),
                           (0.0, 0.0, 0.7),
                           (-0.3, 0.0, -2.3),
                           (0.5, 0.0, -0.6))
Example #36
0
#version 460
layout (location = 0) out vec4 diffuseColor;

in vec4 vertexColor;
in vec2 vertexTexcoords;

uniform sampler2D tex;

void main()
{
    diffuseColor = vertexColor * texture(tex, vertexTexcoords);
}
"""

shader = compileProgram(
    compileShader(vertex_shader, GL_VERTEX_SHADER),
    compileShader(fragment_shader, GL_FRAGMENT_SHADER),
)
glUseProgram(shader)

model = glm.mat4(1)
view = glm.mat4(1)
projection = glm.perspective(glm.radians(45), 800 / 600, 0.1, 1000.0)
glViewport(0, 0, 800, 600)

scene = pyassimp.load('./archivos/newBigben.obj')


def glize(node, light, rgbGamingShader):
    model = node.transformation.astype(numpy.float32)
    #render
    for mesh in node.meshes:
    def __init__(self):
        self.current_time = None
        self.current_angle = 0.0

        glClearColor(0.0, 0.0, 0.0, 0.0)
        glEnable(GL_BLEND)
        glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
        glEnable(GL_DEPTH_TEST)

        vertex_shader = shaders.compileShader(
            """#version 430 core
        in vec4 vPosition;
        in vec4 vColor;
        uniform mat4 modelMatrix;
        uniform float rotationAngle;
        varying vec4 varyingColor;

        // function from http://www.neilmendoza.com/glsl-rotation-about-an-arbitrary-axis/
        mat4 rotationMatrix(vec3 axis, float angle) {
            axis = normalize(axis);
            float s = sin(angle);
            float c = cos(angle);
            float oc = 1.0 - c;

            return mat4(oc * axis.x * axis.x + c,           oc * axis.x * axis.y - axis.z * s,  oc * axis.z * axis.x + axis.y * s,  0.0,
                        oc * axis.x * axis.y + axis.z * s,  oc * axis.y * axis.y + c,           oc * axis.y * axis.z - axis.x * s,  0.0,
                        oc * axis.z * axis.x - axis.y * s,  oc * axis.y * axis.z + axis.x * s,  oc * axis.z * axis.z + c,           0.0,
                        0.0,                                0.0,                                0.0,                                1.0);
        }

        void main() {
            mat4 rotation = rotationMatrix(vec3(0.1, 0.2, 0.3), rotationAngle);
            gl_Position = modelMatrix * rotation * vPosition;
            varyingColor = vColor;
        }""", GL_VERTEX_SHADER)

        fragment_shader = shaders.compileShader(
            """#version 430 core
        out vec4 fColor;
        varying vec4 varyingColor;

        void main() {
            fColor = varyingColor;
        }""", GL_FRAGMENT_SHADER)

        self.shader = shaders.compileProgram(vertex_shader, fragment_shader)
        shaders.glUseProgram(self.shader)

        self.position_location = glGetAttribLocation(self.shader, 'vPosition')
        self.color_location = glGetAttribLocation(self.shader, 'vColor')
        self.model_matrix_location = glGetUniformLocation(
            self.shader, 'modelMatrix')
        self.rotation_angle_location = glGetUniformLocation(
            self.shader, 'rotationAngle')

        vertex_positions = array([
            -1.0, -1.0, -1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, -1.0, 1.0,
            -1.0, 1.0, 1.0, 1.0, 1.0, -1.0, -1.0, 1.0, 1.0, -1.0, 1.0, 1.0,
            1.0, 1.0, -1.0, 1.0, 1.0, 1.0, 1.0, 1.0
        ], 'f')

        vertex_colors = array([
            1.0, 1.0, 1.0, 1.0, 1.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, 1.0,
            0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 0.0,
            1.0, 1.0, 0.5, 0.5, 0.5, 1.0
        ], 'f')

        self.vertex_buffer_object = vbo.VBO(
            concatenate((vertex_positions, vertex_colors)))
        self.vertex_buffer_object.bind()

        self.vertex_indices = vbo.VBO(array(
            [0, 1, 2, 3, 6, 7, 4, 5, 0xFFFF, 2, 6, 0, 4, 1, 5, 3, 7], 'I'),
                                      target=GL_ELEMENT_ARRAY_BUFFER)
        self.vertex_indices.bind()

        glEnable(GL_PRIMITIVE_RESTART)
        glPrimitiveRestartIndex(0xFFFF)

        glVertexAttribPointer(self.position_location, 4, GL_FLOAT, False, 0,
                              self.vertex_buffer_object)
        glEnableVertexAttribArray(self.position_location)

        glVertexAttribPointer(
            self.color_location, 4, GL_FLOAT, False, 0,
            self.vertex_buffer_object + vertex_positions.nbytes)
        glEnableVertexAttribArray(self.color_location)
Example #38
0
def main():
    global shader

    vertex_src = """
    # version 330

    layout(location = 0) in vec3 a_position;
    layout(location = 1) in vec2 a_texture;
    layout(location = 2) in vec3 a_offset;

    uniform mat4 model;
    uniform mat4 projection;
    uniform mat4 view;
    uniform mat4 move;

    out vec2 v_texture;

    void main()
    {
        vec3 final_pos = a_position + a_offset;
        gl_Position =  projection * view * move * model * vec4(final_pos, 1.0f);
        v_texture = a_texture;
    }
    """

    fragment_src = """
    # version 330

    in vec2 v_texture;

    out vec4 out_color;

    uniform sampler2D s_texture;

    void main()
    {
        out_color = texture(s_texture, v_texture);
    }
    """

    # initializing glfw library
    if not glfw.init():
        raise Exception("glfw can not be initialized!")

    if "Windows" in pltf.platform():
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
    else:
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)

    # creating the window
    window = glfw.create_window(WIDTH, HEIGHT, "My OpenGL window", None, None)

    # check if window was created
    if not window:
        glfw.terminate()
        raise Exception("glfw window can not be created!")

    # set window's position
    glfw.set_window_pos(window, 100, 100)

    # set the callback function for window resize
    glfw.set_window_size_callback(window, window_resize_clb)
    # set the mouse position callback
    glfw.set_cursor_pos_callback(window, mouse_look_clb)
    # set the keyboard input callback
    glfw.set_key_callback(window, key_input_clb)
    # capture the mouse cursor
    glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)

    # make the context current
    glfw.make_context_current(window)


    #              positions        texture_coords
    cube_buffer = [-0.5, -0.5,  0.5, 0.0, 0.0,
                 0.5, -0.5,  0.5, 1.0, 0.0,
                 0.5,  0.5,  0.5, 1.0, 1.0,
                -0.5,  0.5,  0.5, 0.0, 1.0,

                -0.5, -0.5, -0.5, 0.0, 0.0,
                 0.5, -0.5, -0.5, 1.0, 0.0,
                 0.5,  0.5, -0.5, 1.0, 1.0,
                -0.5,  0.5, -0.5, 0.0, 1.0,

                 0.5, -0.5, -0.5, 0.0, 0.0,
                 0.5,  0.5, -0.5, 1.0, 0.0,
                 0.5,  0.5,  0.5, 1.0, 1.0,
                 0.5, -0.5,  0.5, 0.0, 1.0,

                -0.5,  0.5, -0.5, 0.0, 0.0,
                -0.5, -0.5, -0.5, 1.0, 0.0,
                -0.5, -0.5,  0.5, 1.0, 1.0,
                -0.5,  0.5,  0.5, 0.0, 1.0,

                -0.5, -0.5, -0.5, 0.0, 0.0,
                 0.5, -0.5, -0.5, 1.0, 0.0,
                 0.5, -0.5,  0.5, 1.0, 1.0,
                -0.5, -0.5,  0.5, 0.0, 1.0,

                 0.5,  0.5, -0.5, 0.0, 0.0,
                -0.5,  0.5, -0.5, 1.0, 0.0,
                -0.5,  0.5,  0.5, 1.0, 1.0,
                 0.5,  0.5,  0.5, 0.0, 1.0]

    cube_buffer = np.array(cube_buffer, dtype=np.float32)

    cube_indices = [ 0,  1,  2,  2,  3,  0,
                     4,  5,  6,  6,  7,  4,
                     8,  9, 10, 10, 11,  8,
                    12, 13, 14, 14, 15, 12,
                    16, 17, 18, 18, 19, 16,
                    20, 21, 22, 22, 23, 20]

    cube_indices = np.array(cube_indices, dtype=np.uint32)

    # VAO, VBO and EBO
    VAO = glGenVertexArrays(1)
    VBO = glGenBuffers(1)
    EBO = glGenBuffers(1)

    # cube VAO
    glBindVertexArray(VAO)

    shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER), compileShader(fragment_src, GL_FRAGMENT_SHADER))
    # cube Vertex Buffer Object
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, cube_buffer.nbytes, cube_buffer, GL_STATIC_DRAW)
    # cube Element Buffer Object
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, cube_indices.nbytes, cube_indices, GL_STATIC_DRAW)

    # cube vertices
    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 5, ctypes.c_void_p(0))
    # cube textures
    glEnableVertexAttribArray(1)
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 5, ctypes.c_void_p(12))

    textures = glGenTextures(1)
    load_texture("textures/crate.jpg", textures)

    # instance VBO
    instance_array = []
    offset = 1

    for z in range(0, 100, 2):
        for y in range(0, 100, 2):
            for x in range(0, 100, 2):
                translation = pyrr.Vector3([0.0, 0.0, 0.0])
                translation.x = x + offset
                translation.y = y + offset
                translation.z = z + offset
                instance_array.append(translation)

    len_of_instance_array = len(instance_array) # do this before you flatten the array
    instance_array = np.array(instance_array, np.float32).flatten()

    instanceVBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, instanceVBO)
    glBufferData(GL_ARRAY_BUFFER, instance_array.nbytes, instance_array, GL_STATIC_DRAW)

    glEnableVertexAttribArray(2)
    glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0))
    glVertexAttribDivisor(2, 1) # 1 means, every instance will have it's own translate

    glUseProgram(shader)

    glClearColor(0, 0.1, 0.1, 1)
    glEnable(GL_DEPTH_TEST)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    projection = pyrr.matrix44.create_perspective_projection_matrix(45, WIDTH / HEIGHT, 0.1, 100)
    cube_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([-50.0, -50.0, -200.0]))

    model_loc = glGetUniformLocation(shader, "model")
    proj_loc = glGetUniformLocation(shader, "projection")
    view_loc = glGetUniformLocation(shader, "view")
    move_loc = glGetUniformLocation(shader, "move")

    glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)
    glUniformMatrix4fv(model_loc, 1, GL_FALSE, cube_pos)

    glUseProgram(0)

    # the main application loop
    while not glfw.window_should_close(window):
        glfw.poll_events()
        # do_movement()

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        move = pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 0, glfw.get_time()*8]))
        
        glUseProgram(shader)
        glUniformMatrix4fv(move_loc, 1, GL_FALSE, move)

        view = cam.get_view_matrix()
        glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)

        glDrawElementsInstanced(GL_TRIANGLES, len(cube_indices), GL_UNSIGNED_INT, None, len_of_instance_array)

        glUseProgram(0)

        glfw.swap_buffers(window)

    # terminate glfw, free up allocated resources
    glfw.terminate()
Example #39
0
def initialize():
    global shaderProgram
    global VAO
    global VBO

    vertexShader = shaders.compileShader("""
#version 330

layout (location=0) in vec4 position;
layout (location=1) in vec4 colour;

smooth out vec4 theColour;

void main()
{
    gl_Position = position;
    theColour = colour;
}
""", GL.GL_VERTEX_SHADER)

    fragmentShader = shaders.compileShader("""
#version 330

smooth in vec4 theColour;
out vec4 outputColour;

void main()
{
    outputColour = theColour;
}
""", GL.GL_FRAGMENT_SHADER)

    shaderProgram = shaders.compileProgram(vertexShader, fragmentShader)

    vertexData = numpy.array([
	# Vertex Positions
        0.0, 0.5, 0.0, 1.0,
        0.5, -0.366, 0.0, 1.0,
        -0.5, -0.366, 0.0, 1.0,

	# Vertex Colours
        1.0, 0.0, 0.0, 1.0,
        0.0, 1.0, 0.0, 1.0,
        0.0, 0.0, 1.0, 1.0,
    ], dtype=numpy.float32)

    # Core OpenGL requires that at least one OpenGL vertex array be bound
    VAO = GL.glGenVertexArrays(1)
    GL.glBindVertexArray(VAO)

    # Need VBO for triangle vertices and colours
    VBO = GL.glGenBuffers(1)
    GL.glBindBuffer(GL.GL_ARRAY_BUFFER, VBO)
    GL.glBufferData(GL.GL_ARRAY_BUFFER, vertexData.nbytes, vertexData,
        GL.GL_STATIC_DRAW)

    # enable array and set up data
    GL.glEnableVertexAttribArray(0)
    GL.glEnableVertexAttribArray(1)
    GL.glVertexAttribPointer(0, 4, GL.GL_FLOAT, GL.GL_FALSE, 0,
        None)
    # the last parameter is a pointer
    GL.glVertexAttribPointer(1, 4, GL.GL_FLOAT, GL.GL_FALSE, 0,
        ctypes.c_void_p(48))

    GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
    GL.glBindVertexArray(0)
Example #40
0
    def OnInit(self):
        """Initialize the context"""
        '''As you can see, we've created a new 4-element vector 
        called SPOT_PARAMS which holds 3 "meaningful" float values.
        The first element cos_spot_cutoff represents the cosign of 
        the angle beyond which the light is cut off. This angle is 
        measured from the light's spot_direction compared with the 
        light_location vector.  In effect, it is a check to see if 
        the fragment is within the cone of the light.  The use of the 
        *cosine* of the angle is to allow for very fast checks against 
        the dot-product of the normalized vectors.
        
        The second element, spot_exponent, is used to calculate the 
        amount of "spotiness" of the spotlight, that is, the amount 
        to which the spotlight focusses light on the center of the 
        beam versus the outside of the beam.  A higher spot_exponent
        will cause the spotlight to "focus" more, a lower exponent 
        will cause the spotlight to act more like a "shielded" 
        point-light (such as a lamp with blockers rather than reflectors).
        
        The last component of the SPOT_PARAMS is being used as a simple 
        flag to tell us whether to apply the spot calculation.  We could 
        have shaved a whole vec4 by packing the spot_exponent into the 
        ATTENUATION vector's unused .w component, and then packing the 
        spot_cutoff into the spot_direction's unused .w, but that becomes 
        a bit awkward looking.
        '''
        lightConst = """
        const int LIGHT_COUNT = %s;
        const int LIGHT_SIZE = %s;
        
        const int AMBIENT = 0;
        const int DIFFUSE = 1;
        const int SPECULAR = 2;
        const int POSITION = 3;
        const int ATTENUATION = 4;
        //SPOT_PARAMS [ cos_spot_cutoff, spot_exponent, ignored, is_spot ]
        const int SPOT_PARAMS = 5;
        const int SPOT_DIR = 6;
        
        uniform vec4 lights[ LIGHT_COUNT*LIGHT_SIZE ];
        varying vec3 EC_Light_half[LIGHT_COUNT];
        varying vec3 EC_Light_location[LIGHT_COUNT]; 
        varying float Light_distance[LIGHT_COUNT]; 
        
        varying vec3 baseNormal;
        """ % (self.LIGHT_COUNT, self.LIGHT_SIZE)
        '''Our phong_weightCalc function receives its final tweaks here.  We 
        provide the two vec4 spot elements for the current light.
        The spotlight operation modifies the point-light code such that 
        the "attenuation" numerator is either 1.0 (for non-directional 
        point-lights) or a calculated value for spot-lights.
        
        To calculate this value, we take the (cos of the) angle between 
        the light direction (spot_direction) and the vector between 
        the fragment and the light location (-light_pos).  If this value 
        is lower than our spot_cutoff, then we do not want to provide 
        any lighting whatsoever from this light, so we short-circuit and 
        return a null vector of weights. 
        
        If the value is higher than the cutoff, we calculate the
        "spotiness" multiplier.  Here we are *not* using the OpenGL 
        standard method, instead we calculate the fraction of total 
        cosine-space which is displayed and raise it to the power of our 
        spot_exponent value.
        
        This is our last tweak to the blinn-phong lighting model so we'll make 
        this version of the function available like so:
        
        from OpenGLContext.resources.phongweights_frag import data as phong_weightCalc
        '''
        phong_weightCalc = """
        vec3 phong_weightCalc( 
            in vec3 light_pos, // light position/direction
            in vec3 half_light, // half-way vector between light and view
            in vec3 frag_normal, // geometry normal
            in float shininess, // shininess exponent
            in float distance, // distance for attenuation calculation...
            in vec4 attenuations, // attenuation parameters...
            in vec4 spot_params, // spot control parameters...
            in vec4 spot_direction // model-space direction
        ) {
            // returns vec3( ambientMult, diffuseMult, specularMult )
            
            float n_dot_pos = max( 0.0, dot( 
                frag_normal, light_pos
            ));
            float n_dot_half = 0.0;
            float attenuation = 1.0;
            if (n_dot_pos > -.05) {
                float spot_effect = 1.0;
                if (spot_params.w != 0.0) {
                    // is a spot...
                    float spot_cos = dot(
                        gl_NormalMatrix * normalize(spot_direction.xyz),
                        normalize(-light_pos)
                    );
                    if (spot_cos <= spot_params.x) {
                        // is a spot, and is outside the cone-of-light...
                        return vec3( 0.0, 0.0, 0.0 );
                    } else {
                        if (spot_cos == 1.0) {
                            spot_effect = 1.0;
                        } else {
                            spot_effect = pow( 
                                    (1.0-spot_params.x)/(1.0-spot_cos), 
                                    spot_params.y 
                                );
                        }
                    }
                }
                n_dot_half = pow(
                    max(0.0,dot( 
                        half_light, frag_normal
                    )), 
                    shininess
                );
                if (distance != 0.0) {
                    float attenuation = 1.0/(
                        attenuations.x + 
                        (attenuations.y * distance) +
                        (attenuations.z * distance * distance)
                    );
                    n_dot_half *= spot_effect;
                    n_dot_pos *= attenuation;
                    n_dot_half *= attenuation;
                }
            }
            return vec3( attenuation, n_dot_pos, n_dot_half);
        }		
        """
        '''Nothing needs to change in our vertex shader, save that we're 
        using the functions we stored to external files in the previous 
        tutorial.'''
        from OpenGLContext.resources.phongprecalc_vert import data as phong_preCalc
        if bytes is not str:
            phong_preCalc = phong_preCalc.decode('ascii')
        light_preCalc = open('_shader_tut_lightprecalc.vert').read()

        vertex = shaders.compileShader(
            lightConst + phong_preCalc + light_preCalc + """
        attribute vec3 Vertex_position;
        attribute vec3 Vertex_normal;
        void main() {
            gl_Position = gl_ModelViewProjectionMatrix * vec4( 
                Vertex_position, 1.0
            );
            baseNormal = gl_NormalMatrix * normalize(Vertex_normal);
            light_preCalc( Vertex_position );
        }""", GL_VERTEX_SHADER)
        '''Our only change for the fragment shader is to pass in the 
        spot components of the current light when calling phong_weightCalc.'''
        fragment = shaders.compileShader(
            lightConst + phong_weightCalc + """
        struct Material {
            vec4 ambient;
            vec4 diffuse;
            vec4 specular;
            float shininess;
        };
        uniform Material material;
        uniform vec4 Global_ambient;
        
        void main() {
            vec4 fragColor = Global_ambient * material.ambient;
            
            int i,j;
            for (i=0;i<LIGHT_COUNT;i++) {
                j = i* LIGHT_SIZE;
                vec3 weights = phong_weightCalc(
                    normalize(EC_Light_location[i]),
                    normalize(EC_Light_half[i]),
                    normalize(baseNormal),
                    material.shininess,
                    abs(Light_distance[i]), // see note tutorial 9
                    lights[j+ATTENUATION],
                    lights[j+SPOT_PARAMS],
                    lights[j+SPOT_DIR]
                );
                fragColor = (
                    fragColor 
                    + (lights[j+AMBIENT] * material.ambient * weights.x)
                    + (lights[j+DIFFUSE] * material.diffuse * weights.y)
                    + (lights[j+SPECULAR] * material.specular * weights.z)
                );
            }
            gl_FragColor = fragColor;
        }
        """, GL_FRAGMENT_SHADER)
        '''Our uniform/geometry handling code is unchanged.'''
        self.shader = shaders.compileProgram(vertex, fragment)
        self.coords, self.indices, self.count = Sphere(radius=1).compile()
        self.uniform_locations = {}
        for uniform, value in self.UNIFORM_VALUES:
            location = glGetUniformLocation(self.shader, uniform)
            if location in (None, -1):
                print('Warning, no uniform: %s' % (uniform))
            self.uniform_locations[uniform] = location
        self.uniform_locations['lights'] = glGetUniformLocation(
            self.shader, 'lights')
        for attribute in (
                'Vertex_position',
                'Vertex_normal',
        ):
            location = glGetAttribLocation(self.shader, attribute)
            if location in (None, -1):
                print('Warning, no attribute: %s' % (uniform))
            setattr(self, attribute + '_loc', location)
Example #41
0
def initialize():
    global shaderProgram
    global VAO
    global VBO
    global texUnitUniform
    global sampleTexture

    vertexShader = shaders.compileShader(
        """
#version 330

layout (location=0) in vec3 position;
layout (location=1) in vec2 texCoords;

out vec2 theCoords;

void main()
{
    gl_Position = vec4(position, 1);
    theCoords = texCoords;
}
""", GL.GL_VERTEX_SHADER)

    fragmentShader = shaders.compileShader(
        """
#version 330

uniform sampler2D texUnit;

in vec2 theCoords;

out vec4 outputColour;

void main()
{
    outputColour = texture(texUnit, theCoords);
}
""", GL.GL_FRAGMENT_SHADER)

    shaderProgram = shaders.compileProgram(vertexShader, fragmentShader)

    vertexData = numpy.array(
        [
            # X,    Y,   Z     U,   V
            0.0,
            0.8,
            0.0,
            0.5,
            1.0,
            -0.8,
            -0.8,
            0.0,
            0.0,
            0.0,
            0.8,
            -0.8,
            0.0,
            1.0,
            0.0,
        ],
        dtype=numpy.float32)

    # Core OpenGL requires that at least one OpenGL vertex array be bound
    VAO = GL.glGenVertexArrays(1)
    GL.glBindVertexArray(VAO)

    # Need VBO for triangle vertices and texture UV coordinates
    VBO = GL.glGenBuffers(1)
    GL.glBindBuffer(GL.GL_ARRAY_BUFFER, VBO)
    GL.glBufferData(GL.GL_ARRAY_BUFFER, vertexData.nbytes, vertexData,
                    GL.GL_STATIC_DRAW)

    # enable array and set up data
    positionAttrib = GL.glGetAttribLocation(shaderProgram, 'position')
    coordsAttrib = GL.glGetAttribLocation(shaderProgram, 'texCoords')

    GL.glEnableVertexAttribArray(0)
    GL.glEnableVertexAttribArray(1)
    GL.glVertexAttribPointer(positionAttrib, 3, GL.GL_FLOAT, GL.GL_FALSE, 20,
                             None)
    # the last parameter is a pointer
    GL.glVertexAttribPointer(coordsAttrib, 2, GL.GL_FLOAT, GL.GL_TRUE, 20,
                             ctypes.c_void_p(12))

    # load texture and assign texture unit for shaders
    sampleTexture = loadTexture('hazard.png')
    texUnitUniform = GL.glGetUniformLocation(shaderProgram, 'texUnit')

    # Finished
    GL.glBindBuffer(GL.GL_ARRAY_BUFFER, 0)
    GL.glBindVertexArray(0)
Example #42
0
def init():
    global shaderProgram
    global vao
    global vbo
    global model
    global uMat

    glClearColor(0, 0, 0, 1)

    vertex_code = readShaderFile('cube.vp')
    fragment_code = readShaderFile('cube.fp')

    # compile shaders and program
    vertexShader = shaders.compileShader(vertex_code, GL_VERTEX_SHADER)
    fragmentShader = shaders.compileShader(fragment_code, GL_FRAGMENT_SHADER)
    shaderProgram = shaders.compileProgram(vertexShader, fragmentShader)

    # Create and bind the Vertex Array Object
    vao = GLuint(0)
    glGenVertexArrays(1, vao)
    glBindVertexArray(vao)

    # lendo os obj pegando vertices e normais
    vertices = np.array(readVertexData(), dtype='f')
    print("vertices:", len(vertices) // 6)
    print(vertices)

    vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    glBufferData(GL_ARRAY_BUFFER, vertices, GL_STATIC_DRAW)
    glVertexAttribPointer(
        0, 3, GL_FLOAT, False, 6 * sizeof(GLfloat),
        ctypes.c_void_p(3 *
                        sizeof(GLfloat)))  # first 0 is the location in shader
    glVertexAttribPointer(
        1, 3, GL_FLOAT, False, 6 * sizeof(GLfloat),
        ctypes.c_void_p(0))  # first 0 is the location in shader
    #glVertexAttribPointer(0, 3, GL_FLOAT, False, 0, None)  # first 0 is the location in shader
    #glBindAttribLocation(shaderProgram, 0, 'vertexPosition')  # name of attribute in shader
    glEnableVertexAttribArray(
        0
    )  # 0=location do atributo, tem que ativar todos os atributos inicialmente sao desabilitados por padrao
    glEnableVertexAttribArray(
        1
    )  # 0=location do atributo, tem que ativar todos os atributos inicialmente sao desabilitados por padrao
    # cria a matriz de transformação
    model = pyrr.matrix44.create_identity()
    scale = pyrr.matrix44.create_from_scale([0.5, 0.5, 0.5], dtype='f')
    model = pyrr.matrix44.multiply(model, scale)

    rotZ = pyrr.matrix44.create_from_z_rotation(math.radians(0))
    rotY = pyrr.matrix44.create_from_y_rotation(math.radians(45))
    rotx = pyrr.matrix44.create_from_x_rotation(math.radians(45))
    rotT = pyrr.matrix44.multiply(rotY, rotx)
    rotT = pyrr.matrix44.multiply(rotT, rotZ)

    model = pyrr.matrix44.multiply(model, rotT)

    # atribui uma variavel uniforme para matriz de transformacao
    uMat = glGetUniformLocation(shaderProgram, "model")

    # Note that this is allowed, the call to glVertexAttribPointer registered VBO
    # as the currently bound vertex buffer object so afterwards we can safely unbind
    glBindBuffer(GL_ARRAY_BUFFER, 0)
    # Unbind VAO (it's always a good thing to unbind any buffer/array to prevent strange bugs)
    glBindVertexArray(0)
def main():
    vertex_src = """
    # version 330

    layout(location = 0) in vec3 a_position;
    layout(location = 1) in vec2 a_texture;
    layout(location = 2) in vec3 a_normal;

    uniform mat4 model;
    uniform mat4 projection;
    uniform mat4 view;

    out vec2 v_texture;

    void main()
    {
        gl_Position = projection * view * model * vec4(a_position, 1.0);
        v_texture = a_texture;
    }
    """

    fragment_src = """
    # version 330

    in vec2 v_texture;

    out vec4 out_color;

    uniform sampler2D s_texture;

    void main()
    {
        out_color = texture(s_texture, v_texture);
    }
    """

    pygame.init()

    pygame.display.gl_set_attribute(pygame.GL_CONTEXT_MAJOR_VERSION, 4)
    pygame.display.gl_set_attribute(pygame.GL_CONTEXT_MINOR_VERSION, 1)
    pygame.display.gl_set_attribute(pygame.GL_CONTEXT_PROFILE_MASK,
                                    pygame.GL_CONTEXT_PROFILE_CORE)

    pygame.display.set_mode((WIDTH, HEIGHT), pygame.OPENGL | pygame.DOUBLEBUF
                            | pygame.RESIZABLE)  # |pygame.FULLSCREEN
    pygame.mouse.set_visible(False)
    pygame.event.set_grab(True)

    # load here the 3d meshes
    cube_indices, cube_buffer = ObjLoader.load_model("meshes/cube.obj", False)
    monkey_indices, monkey_buffer = ObjLoader.load_model("meshes/monkey.obj")
    floor_indices, floor_buffer = ObjLoader.load_model("meshes/floor.obj")

    # VAO and VBO
    VAO = glGenVertexArrays(3)
    VBO = glGenBuffers(3)
    EBO = glGenBuffers(1)

    # cube VAO
    glBindVertexArray(VAO[0])

    shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER),
                            compileShader(fragment_src, GL_FRAGMENT_SHADER))

    # cube Vertex Buffer Object
    glBindBuffer(GL_ARRAY_BUFFER, VBO[0])
    glBufferData(GL_ARRAY_BUFFER, cube_buffer.nbytes, cube_buffer,
                 GL_STATIC_DRAW)

    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, cube_indices.nbytes, cube_indices,
                 GL_STATIC_DRAW)

    # cube vertices
    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8,
                          ctypes.c_void_p(0))

    # cube textures
    glEnableVertexAttribArray(1)
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8,
                          ctypes.c_void_p(12))

    # cube normals
    glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, cube_buffer.itemsize * 8,
                          ctypes.c_void_p(20))
    glEnableVertexAttribArray(2)

    glBindVertexArray(0)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
    glBindBuffer(GL_ARRAY_BUFFER, 0)

    # monkey VAO
    glBindVertexArray(VAO[1])
    # monkey Vertex Buffer Object
    glBindBuffer(GL_ARRAY_BUFFER, VBO[1])
    glBufferData(GL_ARRAY_BUFFER, monkey_buffer.nbytes, monkey_buffer,
                 GL_STATIC_DRAW)

    # monkey vertices
    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8,
                          ctypes.c_void_p(0))
    # monkey textures
    glEnableVertexAttribArray(1)
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8,
                          ctypes.c_void_p(12))
    # monkey normals
    glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, monkey_buffer.itemsize * 8,
                          ctypes.c_void_p(20))
    glEnableVertexAttribArray(2)

    glBindVertexArray(0)
    glBindBuffer(GL_ARRAY_BUFFER, 0)

    # floor VAO
    glBindVertexArray(VAO[2])
    # floor Vertex Buffer Object
    glBindBuffer(GL_ARRAY_BUFFER, VBO[2])
    glBufferData(GL_ARRAY_BUFFER, floor_buffer.nbytes, floor_buffer,
                 GL_STATIC_DRAW)

    # floor vertices
    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8,
                          ctypes.c_void_p(0))
    # floor textures
    glEnableVertexAttribArray(1)
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8,
                          ctypes.c_void_p(12))
    # floor normals
    glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, floor_buffer.itemsize * 8,
                          ctypes.c_void_p(20))
    glEnableVertexAttribArray(2)

    glBindVertexArray(0)
    glBindBuffer(GL_ARRAY_BUFFER, 0)

    textures = glGenTextures(3)
    load_texture_pygame("meshes/cube.jpg", textures[0])
    load_texture_pygame("meshes/monkey.jpg", textures[1])
    load_texture_pygame("meshes/floor.jpg", textures[2])

    glUseProgram(shader)
    glClearColor(0, 0.1, 0.1, 1)
    glEnable(GL_DEPTH_TEST)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    projection = pyrr.matrix44.create_perspective_projection_matrix(
        45, 1280 / 720, 0.1, 100)
    cube_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([6, 4, 0]))
    monkey_pos = pyrr.matrix44.create_from_translation(
        pyrr.Vector3([-4, 4, -4]))
    floor_pos = pyrr.matrix44.create_from_translation(pyrr.Vector3([0, 0, 0]))

    model_loc = glGetUniformLocation(shader, "model")
    proj_loc = glGetUniformLocation(shader, "projection")
    view_loc = glGetUniformLocation(shader, "view")

    glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)

    glUseProgram(0)

    running = True

    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:
                running = False

            if event.type == pygame.VIDEORESIZE:
                glViewport(0, 0, event.w, event.h)
                projection = pyrr.matrix44.create_perspective_projection_matrix(
                    45, event.w / event.h, 0.1, 100)
                glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)

        keys_pressed = pygame.key.get_pressed()
        if keys_pressed[pygame.K_a]:
            cam.process_keyboard("LEFT", 0.08)
        if keys_pressed[pygame.K_d]:
            cam.process_keyboard("RIGHT", 0.08)
        if keys_pressed[pygame.K_w]:
            cam.process_keyboard("FORWARD", 0.08)
        if keys_pressed[pygame.K_s]:
            cam.process_keyboard("BACKWARD", 0.08)

        mouse_pos = pygame.mouse.get_pos()
        mouse_look(mouse_pos[0], mouse_pos[1])

        # to been able to look around 360 degrees, still not perfect
        if mouse_pos[0] <= 0:
            pygame.mouse.set_pos((1279, mouse_pos[1]))
        elif mouse_pos[0] >= 1279:
            pygame.mouse.set_pos((0, mouse_pos[1]))

        ct = pygame.time.get_ticks() / 1000

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        view = cam.get_view_matrix()

        glUseProgram(shader)
        glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)

        rot_y = pyrr.Matrix44.from_y_rotation(0.8 * ct)
        model = pyrr.matrix44.multiply(rot_y, cube_pos)

        # draw the cube
        glBindVertexArray(VAO[0])
        glBindTexture(GL_TEXTURE_2D, textures[0])
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)
        glDrawElements(GL_TRIANGLES, len(cube_indices), GL_UNSIGNED_INT, None)

        # draw the monkey
        glBindVertexArray(VAO[1])
        glBindTexture(GL_TEXTURE_2D, textures[1])
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, monkey_pos)
        glDrawArrays(GL_TRIANGLES, 0, len(monkey_indices))

        # draw the floor
        glBindVertexArray(VAO[2])
        glBindTexture(GL_TEXTURE_2D, textures[2])
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, floor_pos)
        glDrawArrays(GL_TRIANGLES, 0, len(floor_indices))

        glUseProgram(0)

        pygame.display.flip()

    pygame.quit()
    sys.exit()
Example #44
0
    1.0,
    -0.6,
    0.6,
    0,
    1.0,
    0.0,
    -0.6,
    0,
    1.0,
])

pygame.display.set_mode((512, 512), pygame.OPENGL | pygame.DOUBLEBUF)
glClearColor(0.9, 0.9, 0.5, 1.0)

shader_program = shaders.compileProgram(
    shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
    shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

# Create a new VAO (Vertex Array Object) and bind it
vertex_array_object = glGenVertexArrays(1)
glBindVertexArray(vertex_array_object)

# Get the position of the 'position' in parameter of our shader_program and bind it.
position = glGetAttribLocation(shader_program, 'position')

if position != -1:  # maybe the attribute is useless and was discarded by the compiler
    glEnableVertexAttribArray(position)

    # Generate buffers to hold our vertices
    vertex_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
Example #45
0
    def __init__(this):
        this.planeProgram = shaders.compileProgram(
            shaders.compileShader(plane_v, GL_VERTEX_SHADER),
            shaders.compileShader(plane_f, GL_FRAGMENT_SHADER))
        #the parameter tex0 must be use in shaders,otherwise the
        #glGetUniformLocation get -1
        this.planeProgram.tex0 = glGetUniformLocation(this.planeProgram,
                                                      "tex0")
        this.planeProgram.tex1 = glGetUniformLocation(this.planeProgram,
                                                      "tex1")
        #print ("t0,t1:", this.planeProgram.tex0,this.planeProgram.tex1)

        this.updateProgram = shaders.compileProgram(
            shaders.compileShader(update_v, GL_VERTEX_SHADER),
            shaders.compileShader(update_f, GL_FRAGMENT_SHADER))
        this.updateProgram.xl = glGetUniformLocation(this.updateProgram, "xw")
        this.updateProgram.yl = glGetUniformLocation(this.updateProgram, "yw")
        this.updateProgram.height = glGetUniformLocation(
            this.updateProgram, "height")
        this.updateProgram.sphereRadius = glGetUniformLocation(
            this.updateProgram, "sphereRadius")
        this.updateProgram.tex0 = glGetUniformLocation(this.updateProgram,
                                                       "tex0")
        this.updateProgram.xz = glGetUniformLocation(this.updateProgram, "xz")
        this.updateProgram.hight = glGetUniformLocation(
            this.updateProgram, "hight")
        this.updateProgram.mMatrix = glGetUniformLocation(
            this.updateProgram, "mMatrix")
        this.updateProgram.vMatrix = glGetUniformLocation(
            this.updateProgram, "vMatrix")
        this.updateProgram.pMatrix = glGetUniformLocation(
            this.updateProgram, "pMatrix")
        this.updateProgram.pos = glGetAttribLocation(this.updateProgram,
                                                     "vectpos")

        this.gpgpuProgram = shaders.compileProgram(
            shaders.compileShader(gpgpu_v, GL_VERTEX_SHADER),
            shaders.compileShader(gpgpu_f, GL_FRAGMENT_SHADER))
        this.gpgpuProgram.tex0 = glGetUniformLocation(this.gpgpuProgram,
                                                      "tex0")
        this.gpgpuProgram.xl = glGetUniformLocation(this.gpgpuProgram, "xw")
        this.gpgpuProgram.yl = glGetUniformLocation(this.gpgpuProgram, "yw")

        this.tfProgram = glCreateProgram()
        this.tfProgram = ShaderProgram(this.tfProgram)
        tfvshader = shaders.compileShader(tf_v, GL_VERTEX_SHADER)
        glAttachShader(this.tfProgram, tfvshader)
        LP_LP_c_char = POINTER(POINTER(c_char))
        ptrs = (c_char_p * 2)(bytes('outValue', encoding="utf8"),
                              bytes('out2', encoding="utf8"))
        # print (ptrs,len(ptrs))
        c_array = cast(ptrs, LP_LP_c_char)
        glTransformFeedbackVaryings(this.tfProgram, len(ptrs), c_array,
                                    GL_INTERLEAVED_ATTRIBS)
        glLinkProgram(this.tfProgram)
        this.tfProgram.invalue = glGetAttribLocation(this.tfProgram, "inValue")

        this.particleProgram = glCreateProgram()
        this.particleProgram = ShaderProgram(this.particleProgram)
        particleshader = shaders.compileShader(particle_v, GL_VERTEX_SHADER)
        glAttachShader(this.particleProgram, particleshader)
        LP_LP_c_char = POINTER(POINTER(c_char))
        ptrs = (c_char_p * 3)(bytes('outpos', encoding="utf8"),
                              bytes('outvel', encoding="utf8"),
                              bytes('outtime', encoding="utf8"))
        c_array = cast(ptrs, LP_LP_c_char)
        glTransformFeedbackVaryings(this.particleProgram, len(ptrs), c_array,
                                    GL_INTERLEAVED_ATTRIBS)
        glLinkProgram(this.particleProgram)
        this.particleProgram.pos = glGetAttribLocation(this.particleProgram,
                                                       "pos")
        this.particleProgram.vel = glGetAttribLocation(this.particleProgram,
                                                       "vel")
        this.particleProgram.time = glGetAttribLocation(
            this.particleProgram, "time")
        this.particleProgram.span = glGetUniformLocation(
            this.particleProgram, "span")
        this.particleProgram.live = glGetUniformLocation(
            this.particleProgram, "live")
        this.particleProgram.plane = glGetUniformLocation(
            this.particleProgram, "plane")
        this.particleProgram.planeSacle = glGetUniformLocation(
            this.particleProgram, "planeSacle")
Example #46
0
 def compileShader(self):
     self.shader = shaders.compileProgram(
         shaders.compileShader(self.vertexShader, GL_VERTEX_SHADER),
         shaders.compileShader(self.fragmentShader, GL_FRAGMENT_SHADER),
     )
Example #47
0
def create_shader(vertex_shader_src, fragment_shader_src):
    vertex_shader = shaders.compileShader(vertex_shader_src, GL_VERTEX_SHADER)
    fragment_shader = shaders.compileShader(fragment_shader_src,
                                            GL_FRAGMENT_SHADER)
    return shaders.compileProgram(vertex_shader, fragment_shader)
Example #48
0
 def load(vs, fs):
     VERTEX = open(vs).read()
     vertexShader = shaders.compileShader(VERTEX, GL.GL_VERTEX_SHADER)
     FRAGMENT = open(fs).read()
     fragmentShader = shaders.compileShader(FRAGMENT, GL.GL_FRAGMENT_SHADER)
     return shaders.compileProgram(vertexShader, fragmentShader)
Example #49
0
def main(width, height, bsp):
    bsp = bsp_tool.bsp(bsp)
    SDL_Init(SDL_INIT_VIDEO)
    window = SDL_CreateWindow(bytes(bsp.filename, 'utf-8'), SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, width, height, SDL_WINDOW_OPENGL) #| SDL_WINDOW_BORDERLESS) #SDL_WINDOW_FULLSCREEN
    glContext = SDL_GL_CreateContext(window)
    glClearColor(0, .5, 1, 0)
    
    ent_dicts = []
    for e in bsp.ENTITIES[1:-1].split('}\n{'):
        ent_dicts.append(eval('{' + e.replace('" "', '": "').replace('"\n', '", ') + '}'))
    try:
        light_environment = [e for e in ent_dicts if e['classname'] == 'light_environment'][0]
        light_environment['angles'] = tuple(map(float, light_environment['angles'].split(' ')))
        light_environment['pitch'] = float(light_environment['pitch'])
        light_environment['_light'] = tuple(map(int, light_environment['_light'].split(' ')))
        light_environment['_ambient'] = tuple(map(int, light_environment['_ambient'].split(' ')))
        sun_vector = vec3(1, 0, 0).rotate(light_environment['angles'][2], -light_environment['pitch'], light_environment['angles'][1])
        sun_colour = (*[x / 255 for x in light_environment['_light'][:3]], light_environment['_light'][-1]) # vec4 (R, G, B) + Strength
        sun_ambient = (*[x / 255 for x in light_environment['_ambient'][:3]], light_environment['_ambient'][-1]) # vec4 (R, G, B) + Strength
        glClearColor(*sun_ambient[:3], 0)
    except: # no light_environment in .bsp (defaults to goldrush)
        sun_vector = vec3(1, 0, 0).rotate(0, 35, 108)
        sun_colour = (1.00, 0.89, 0.73, 600)
        sun_ambient = (0.46, 0.45, 0.55, 350)
        glClearColor(0, 0, 0, 0)
    
    gluPerspective(90, width / height, 0.1, 4096 * 4)
    glPointSize(4)
    glPolygonMode(GL_BACK, GL_LINE)
    glEnable(GL_DEPTH_TEST)
    glFrontFace(GL_CW)
    glEnable(GL_CULL_FACE)
    glColor(1, 1, 1)

    filtered_faces = list(filter(lambda x: x['lightofs'] != -1, bsp.FACES)) #no sky or trigger
##    filtered_faces = list(filter(lambda x: x['dispinfo'] != -1, bsp.FACES)) #disp only
##    filtered_faces = list(filter(lambda x: x['lightofs'] != -1 and x['dispinfo'] == -1, bsp.FACES)) #no sky, trigger or disp
##    filtered_faces = list(filter(lambda x: x['styles'] == (-1, -1, -1, -1), bsp.FACES))
##    filtered_faces = bsp.FACES

    face_count = len(filtered_faces)
    current_face_index = 0
    current_face = filtered_faces[current_face_index]
    current_face_verts = [v[0] for v in bsp.verts_of(current_face)]

    all_faces = []
    all_faces_map = []
    start = 0
    t1 = time()
    for face in filtered_faces:
        if face['dispinfo'] == -1:
            f_verts = bsp.verts_of(face) # add to vertex buffer here and fan the indices
            out = f_verts[:3]
            f_verts = f_verts[3:]
            for vert in f_verts:
                out += [out[0], out[-1], vert]
            f_verts = out
            f_verts_len = len(f_verts)
            all_faces_map.append((start, f_verts_len))
            start += f_verts_len
        else:
            power = bsp.DISP_INFO[face['dispinfo']]['power']
            f_verts = bsp.dispverts_of(face)
            f_verts = bsp_tool.disp_tris(f_verts, power)
        all_faces += f_verts
    slow_faces = all_faces.copy()
    all_faces = list(itertools.chain(*itertools.chain(*all_faces)))
    all_faces_size = len(all_faces)

    vertices = all_faces
    indices = range(all_faces_size)

##    print('compressing vertex buffer...')
##    vertices = []
##    indices = []
##    currentIndex = 0
##    for face in filtered_faces:
##        if face["dispinfo"] == -1:
##            faceVerts = bsp.verts_of(face)
##            faceIndices = calcTriFanIndices(faceVerts, currentIndex)
##        else:
##            power = bsp.DISP_INFO[face['dispinfo']]['power']
##            faceVerts = bsp_tool.disp_tris(bsp.dispverts_of(face), power)
##            faceIndices = bsp_tool.disp_tris(range((2 ** power + 1) ** 2), power)
##        vertices += faceVerts
##        indices += faceIndices
##        currentIndex = faceIndices[-1] + 1 # ?
##    vertices = list(itertools.chain(*itertools.chain(*vertices)))

##    RGB_LIGHTING = []
##    for RGBE_texel in struct.iter_unpack('3Bb', bsp.LIGHTING):
##        RGBA_texel = vec3(RGBE_texel[:-1]) * 2 ** RGBE_texel[-1]
##        RGBA_texel = [clamp(int(x) // 2, 0, 255) for x in RGBA_texel]
##        RGB_LIGHTING.append(struct.pack('3Bb', *RGBA_texel, RGBE_texel[3]))
##    RGB_LIGHTING = b''.join(RGB_LIGHTING)
##
##    lightmap = [] # store on GPU
##    for face in filtered_faces:
##        lmap_start = face['lightofs']
##        if lmap_start != -1:
##            bounds = face['LightmapTextureSizeinLuxels']
##            bounds = [x + 1 for x in bounds]
##            num_styles = sum([1 if x is not -1 else 0 for x in face['styles']])
##            lmap_end = lmap_start + bounds[0] * bounds[1] * 4 * num_styles
##            lmap_bytes = RGB_LIGHTING[lmap_start:lmap_end]
##            lightmap.append([lmap_bytes, bounds])

    t2 = time()
    print(bsp.filename.upper(), end=' ')
    print(f'{bsp.bytesize // 1024:,}KB BSP', end=' >>> ')
    print(f'{len(all_faces) // 9:,} TRIS', end=' & ')
    print(f'{(len(all_faces) * 4) // 1024:,}KB VRAM')
    print(f'ASSEMBLED IN {(t2 - t1) * 1000:,.3f}ms')
    print()

    # SHADERS (check GLSL version)
    USING_ES = False
    try:
        vertShader = compileShader(open('shaders/bsp_faces.v', 'rb'), GL_VERTEX_SHADER)
        fragShader = compileShader(open('shaders/bsp_faces.f', 'rb'), GL_FRAGMENT_SHADER)
    except Exception as exc: # requires PyOpenGL changes described elsewhere
        USING_ES = True # if OpenGL 4.5 is not supported, switch to GLES 3.0
        vertShader = compileShader(open('shaders/bsp_faces_300_es.v', 'rb'), GL_VERTEX_SHADER)
        fragShader = compileShader(open('shaders/bsp_faces_300_es.f', 'rb'), GL_FRAGMENT_SHADER)
        raise exc # need error log if issue is not GLSL version
    bsp_shader = compileProgram(vertShader, fragShader)
    glLinkProgram(bsp_shader)
    glUseProgram(bsp_shader) # must UseProgram to set uniforms

    # UNIFORMS
    if USING_ES:
        # GLES vertex attribs
        attrib_position = glGetAttribLocation(bsp_shader, 'vertexPosition')
        attrib_normal = glGetAttribLocation(bsp_shader, 'vertexNormal')
        attrib_texture_uv = glGetAttribLocation(bsp_shader, 'vertexTexCoord')
        attrib_lightmap_uv = glGetAttribLocation(bsp_shader, 'vertexLightCoord')
        attrib_colour_uv = glGetAttribLocation(bsp_shader, 'vertexColour')
##        ProjectionMatrixLoc = glGetUniformLocation(bsp_shader, 'ProjectionMatrix')
##        # https://www.khronos.org/opengl/wiki/GluPerspective_code
##        glUniformMatrix4fv(ProjectionMatrixLoc, 1, GL_FALSE, ProjectionMatrix) # bad input?
    else: # glsl 450 core uniforms
        glUniform3f(glGetUniformLocation(bsp_shader, 'sun_vector'), *sun_vector)
        glUniform4f(glGetUniformLocation(bsp_shader, 'sun_colour'), *sun_colour)
        glUniform4f(glGetUniformLocation(bsp_shader, 'sun_ambient'), *sun_ambient)

    VERTEX_BUFFER, INDEX_BUFFER = glGenBuffers(2)
    glBindBuffer(GL_ARRAY_BUFFER, VERTEX_BUFFER)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, INDEX_BUFFER)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, len(indices) * 4, np.array(indices, dtype=np.uint32), GL_STATIC_DRAW) # INDICES
    glBufferData(GL_ARRAY_BUFFER, len(vertices) * 4, np.array(vertices, dtype=np.float32), GL_STATIC_DRAW) # VERTICES
    glEnableVertexAttribArray(0)  #vertexPosition
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 52, GLvoidp(0))
    glEnableVertexAttribArray(1)  #vertexNormal
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_TRUE, 52, GLvoidp(12))
    glEnableVertexAttribArray(2) #vertexTexcoord
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 52, GLvoidp(24))
    glEnableVertexAttribArray(3) #vertexLightmapCoord
    glVertexAttribPointer(3, 2, GL_FLOAT, GL_FALSE, 52, GLvoidp(32))
    glEnableVertexAttribArray(4) #reflectivityColour
    glVertexAttribPointer(4, 3, GL_FLOAT, GL_FALSE, 52, GLvoidp(40))
    # displacement alpha (seperate format or shared?)


    glEnable(GL_TEXTURE_2D)
    glActiveTexture(GL_TEXTURE0)
    # texture = open('materials/obsolete.bmp', 'rb')
    texture = open('materials/dev/reflectivity_100.bmp', 'rb')
    texture.seek(54)
    # glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB4, 256, 256, 0, GL_BGR, GL_UNSIGNED_BYTE, texture.read())
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB4, 512, 512, 0, GL_BGR, GL_UNSIGNED_BYTE, texture.read())
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
    texture.close()
    del texture

    SDL_GL_SetSwapInterval(0)
    SDL_CaptureMouse(SDL_TRUE)
    SDL_WarpMouseInWindow(window, width // 2, height // 2)
    SDL_SetRelativeMouseMode(SDL_TRUE)
    SDL_SetWindowGrab(window, SDL_TRUE)

    cam_spawn = vec3(0, 0, 32)
    init_speed = 128
    VIEW_CAMERA = camera.freecam(cam_spawn, None, init_speed)

##    # http://heatmaps.tf/api.html
##    url_tail = '.json?fields=id,timestamp,killer_class,killer_weapon,killer_x,killer_y,killer_z,victim_class,victim_x,victim_y,victim_z,customkill,damagebits,death_flags,team&limit=1024'
####    heatmap = json.load(urllib.request.urlopen('http://heatmaps.tf/data/kills/' + bsp.filename[:-4] + url_tail)) # including the limit in the url is great for load times
##    heatmap = json.load(open('heatmaps.tf/pl_upward_complete.json'))
##    k_class = heatmap['fields'].index('killer_class')
##    k_wep = heatmap['fields'].index('killer_weapon')
##    MINI_SENTRY = -2
##    SENTRY = -1
##    WORLD = 0
##    SCOUT = 1
##    SNIPER = 2
##    SOLDIER = 3
##    DEMOMAN = 4
##    MEDIC = 5
##    HEAVY = 6
##    PYRO = 7
##    SPY = 8
##    ENGINEER = 9
##    k_x = heatmap['fields'].index('killer_x')
##    v_class = heatmap['fields'].index('victim_class')
##    v_x = heatmap['fields'].index('victim_x')
##    kill_range = lambda kill: (vec3(*kill[v_x:v_x + 3]) - vec3(*kill[k_x:k_x + 3])).magnitude()
##
##    filtered_kills = [*filter(lambda k: k[k_wep] == MINI_SENTRY, heatmap['kills'])][:1024]

    mousepos = vec2()
    keys = []

    tickrate = 120
    oldtime = time()
    event = SDL_Event()
    while True:
        while SDL_PollEvent(ctypes.byref(event)) != 0:
            if event.type == SDL_QUIT or event.key.keysym.sym == SDLK_ESCAPE and event.type == SDL_KEYDOWN:
                SDL_GL_DeleteContext(glContext)
                SDL_DestroyWindow(window)
                SDL_Quit()
                return bsp
            if event.type == SDL_KEYDOWN:
                if event.key.keysym.sym not in keys:
                    keys.append(event.key.keysym.sym)
            if event.type == SDL_KEYUP:
                while event.key.keysym.sym in keys:
                    keys.remove(event.key.keysym.sym)
            if event.type == SDL_MOUSEMOTION:
                mousepos += vec2(event.motion.xrel, event.motion.yrel)
                SDL_WarpMouseInWindow(window, width // 2, height // 2)
            if event.type == SDL_MOUSEWHEEL:
                VIEW_CAMERA.speed += event.wheel.y * 32
            if event.type == SDL_MOUSEBUTTONDOWN:
                if event.button.button not in keys:
                    keys.append(event.button.button)
            if event.type == SDL_MOUSEBUTTONUP:
                while event.button.button in keys:
                    keys.remove(event.button.button)

        dt = time() - oldtime
        while dt >= 1 / tickrate:
            VIEW_CAMERA.update(mousepos, keys, 1 / tickrate)
            # turning sun
            sun_vector = sun_vector.rotate(.05, 0, 0)
            glUseProgram(bsp_shader)
            glUniform3f(glGetUniformLocation(bsp_shader, 'sun_vector'), *sun_vector)
            #update projection matrix
            if SDLK_BACKQUOTE in keys:
##                print(VIEW_CAMERA)
                #FACES
                fe, ne = current_face['firstedge'], current_face['numedges']
                se_loop = bsp.SURFEDGES[fe:fe + ne]
                e_loop = [bsp.EDGES[e] for e in se_loop]
                print(f'{bsp.filename}.FACES[{bsp.FACES.index(current_face)}]', '\n'.join([f'{k} = {v}' for k,v in current_face.items()]), sep='\n')
                print('\n\t', '\n\t'.join([f'{bsp.VERTICES[v]}' for v in itertools.chain(*e_loop)][::2]), sep='', end='\n\n')
                
                face_center = sum(map(vec3, current_face_verts), vec3()) / len(current_face_verts)
                face_normal = bsp.PLANES[current_face['planenum']]['normal']
                VIEW_CAMERA.position = face_center + vec3(face_normal) * 32
                while SDLK_BACKQUOTE in keys:
                    keys.remove(SDLK_BACKQUOTE)
            if SDLK_r in keys:
                VIEW_CAMERA = camera.freecam(cam_spawn, None, init_speed)
            if SDLK_LSHIFT in keys:
                VIEW_CAMERA.speed += 5
            if SDLK_LCTRL in keys:
                VIEW_CAMERA.speed -= 5
            if SDLK_LEFT in keys or SDL_BUTTON_LEFT in keys:
                current_face_index -= 1
                current_face = filtered_faces[current_face_index]
                current_face_verts = [v[0] for v in bsp.verts_of(current_face)]
                while SDLK_LEFT in keys:
                    keys.remove(SDLK_LEFT)
                while SDL_BUTTON_LEFT in keys:
                    keys.remove(SDL_BUTTON_LEFT)
            if SDLK_RIGHT in keys or SDL_BUTTON_RIGHT in keys:
                current_face_index += 1
                current_face = filtered_faces[current_face_index]
                current_face_verts = [v[0] for v in bsp.verts_of(current_face)]
                while SDLK_RIGHT in keys:
                    keys.remove(SDLK_RIGHT)
                while SDL_BUTTON_RIGHT in keys:
                    keys.remove(SDL_BUTTON_RIGHT)
            dt -= 1 / tickrate
            oldtime = time()

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glPushMatrix()
        VIEW_CAMERA.set()

        glPolygonMode(GL_FRONT, GL_FILL)
        glUseProgram(bsp_shader)
##        for i, face in enumerate(all_faces_map):
##            texture = lightmap[i]
##            glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, texture[1][0], texture[1][1], 0, GL_RGBA, GL_UNSIGNED_BYTE, texture[0])
##            glDrawArrays(GL_TRIANGLES, face[0], face[1])
##        glDrawArrays(GL_TRIANGLES, 0, all_faces_size) # supported in gl3.0 Mesa?
        glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, GLvoidp(0))

        # for when shaders are too much work
##        glBegin(GL_TRIANGLES)
##        for pos, normal, uv, uv2, colour in slow_faces[:2048]:
##            glColor(*colour)
##            glTexCoord(*uv)
##            glVertex(*pos)
##        glEnd()

        # CENTER MARKER
##        glUseProgram(0)
##        glBegin(GL_LINES)
##        glColor(1, 0, 0)
##        glVertex(0, 0, 0)
##        glVertex(128, 0, 0)
##        glColor(0, 1, 0)
##        glVertex(0, 0, 0)
##        glVertex(0, 128, 0)
##        glColor(0, 0, 1)
##        glVertex(0, 0, 0)
##        glVertex(0, 0, 128)
##        glEnd()

        glUseProgram(0)
        glDisable(GL_TEXTURE_2D)
        glPolygonMode(GL_FRONT_AND_BACK, GL_LINE)
        glColor(1, 1, 1)
        glDisable(GL_DEPTH_TEST)
##        glBegin(GL_LINE_LOOP)
##        for vertex in current_face_verts:
##            glVertex(*vertex)
##        glEnd()
##        glBegin(GL_POINTS)
##        for vertex in current_face_verts:
##            glVertex(*vertex)
##        glEnd()
        glPointSize(24)
        glBegin(GL_POINTS)
        glVertex(*(sun_vector * 4096))
        glEnd()
        glPointSize(4)
        glEnable(GL_DEPTH_TEST)
        glEnable(GL_TEXTURE_2D)

##        glTranslate(0, 0, 64)
##        glBegin(GL_LINES)
##        for kill in filtered_kills:
##            glColor(*colorsys.hsv_to_rgb(kill[k_class] / 9, 1, .75))
##            glVertex(*kill[k_x:k_x + 3])
##            glColor(*colorsys.hsv_to_rgb(kill[v_class] / 9, 1, 1))
##            glVertex(*kill[v_x:v_x + 3])
##        glEnd()

        glPopMatrix()
        SDL_GL_SwapWindow(window)
Example #50
0
    def initializeGL(self):
        # setup some OpenGL options
        glEnable(GL_DEPTH_TEST)

        vertexShader, fragmentShader = self.loadShaders(
            '3.1.shadow_mapping.vs', '3.1.shadow_mapping.frag')
        self.__shader = shaders.compileProgram(vertexShader, fragmentShader)
        vertexShader, fragmentShader = self.loadShaders(
            '3.1.shadow_mapping_depth.vs', '3.1.shadow_mapping_depth.frag')
        self.__simpleDepthShader = shaders.compileProgram(
            vertexShader, fragmentShader)
        vertexShader, fragmentShader = self.loadShaders(
            '3.1.debug_quad.vs', '3.1.debug_quad_depth.frag')
        self.__debugDepthQuad = shaders.compileProgram(vertexShader,
                                                       fragmentShader)

        vertices = np.array(
            [
                # positions          # normals       # texture coords
                25.0,
                -0.5,
                25.0,
                0.0,
                1.0,
                0.0,
                25.0,
                0.0,
                -25.0,
                -0.5,
                -25.0,
                0.0,
                1.0,
                0.0,
                0.0,
                25.0,
                -25.0,
                -0.5,
                25.0,
                0.0,
                1.0,
                0.0,
                0.0,
                0.0,
                25.0,
                -0.5,
                25.0,
                0.0,
                1.0,
                0.0,
                25.0,
                0.0,
                25.0,
                -0.5,
                -25.0,
                0.0,
                1.0,
                0.0,
                25.0,
                25.0,
                -25.0,
                -0.5,
                -25.0,
                0.0,
                1.0,
                0.0,
                0.0,
                25.0,
            ],
            np.float32)

        # setup cube VAO
        self.planeVAO = glGenVertexArrays(1)
        vbo = glGenBuffers(1)
        glBindVertexArray(self.planeVAO)
        glBindBuffer(GL_ARRAY_BUFFER, vbo)
        glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices,
                     GL_STATIC_DRAW)
        glEnableVertexAttribArray(0)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 8 * vertices.itemsize,
                              None)
        glEnableVertexAttribArray(1)
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 8 * vertices.itemsize,
                              ctypes.c_void_p(3 * vertices.itemsize))
        glEnableVertexAttribArray(2)
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 8 * vertices.itemsize,
                              ctypes.c_void_p(6 * vertices.itemsize))
        glBindVertexArray(0)

        # light source
        self.lightPos = np.array([-2.0, 4.0, -1.0], np.float32)

        # load texture
        self.woodTexture = loadTexture(
            os.path.join(abPath, '..', '..', 'resources', 'textures',
                         'wood.png'))

        # Configure depth map FBO
        self.shadowWidth = 1024
        self.shadowHeight = 1024
        self.depthMapFBO = glGenFramebuffers(1)
        # Create depth texture
        self.depthMap = glGenTextures(1)
        glBindTexture(GL_TEXTURE_2D, self.depthMap)

        glTexImage2D(GL_TEXTURE_2D, 0, GL_DEPTH_COMPONENT, self.shadowWidth,
                     self.shadowHeight, 0, GL_DEPTH_COMPONENT, GL_FLOAT, None)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
        borderColor = np.array([1.0, 1.0, 1.0, 1.0], np.float32)
        glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, borderColor)

        glBindFramebuffer(GL_FRAMEBUFFER, self.depthMapFBO)
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT,
                               GL_TEXTURE_2D, self.depthMap, 0)
        glDrawBuffer(GL_NONE)
        glReadBuffer(GL_NONE)
        glBindFramebuffer(GL_FRAMEBUFFER, 0)

        glClearColor(0.1, 0.1, 0.1, 1.0)
def main():
    global shader

    vertex_src = """
    # version 330

    layout(location = 0) in vec3 a_position;
    layout(location = 1) in vec2 a_texture;

    uniform mat4 model; // combined translation and rotation
    uniform mat4 projection;

    out vec3 v_color;
    out vec2 v_texture;

    void main()
    {
        gl_Position = projection * model * vec4(a_position, 1.0);
        v_texture = a_texture;
    }
    """

    fragment_src = """
    # version 330

    in vec2 v_texture;

    out vec4 out_color;

    uniform sampler2D s_texture;

    void main()
    {
        out_color = texture(s_texture, v_texture);
    }
    """

    # initializing glfw library
    if not glfw.init():
        raise Exception("glfw can not be initialized!")

    if "Windows" in pltf.platform():
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 6)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
    else:
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)

    # creating the window
    window = glfw.create_window(1280, 720, "My OpenGL window", None, None)

    # check if window was created
    if not window:
        glfw.terminate()
        raise Exception("glfw window can not be created!")

    # set window's position
    glfw.set_window_pos(window, 100, 100)

    # set the callback function for window resize
    glfw.set_window_size_callback(window, window_resize)

    # make the context current
    glfw.make_context_current(window)

    vertices = [
        -0.5, -0.5, 0.5, 0.0, 0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.5, 0.5, 0.5,
        1.0, 1.0, -0.5, 0.5, 0.5, 0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5,
        -0.5, -0.5, 1.0, 0.0, 0.5, 0.5, -0.5, 1.0, 1.0, -0.5, 0.5, -0.5, 0.0,
        1.0, 0.5, -0.5, -0.5, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0, 0.0, 0.5, 0.5,
        0.5, 1.0, 1.0, 0.5, -0.5, 0.5, 0.0, 1.0, -0.5, 0.5, -0.5, 0.0, 0.0,
        -0.5, -0.5, -0.5, 1.0, 0.0, -0.5, -0.5, 0.5, 1.0, 1.0, -0.5, 0.5, 0.5,
        0.0, 1.0, -0.5, -0.5, -0.5, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.5,
        -0.5, 0.5, 1.0, 1.0, -0.5, -0.5, 0.5, 0.0, 1.0, 0.5, 0.5, -0.5, 0.0,
        0.0, -0.5, 0.5, -0.5, 1.0, 0.0, -0.5, 0.5, 0.5, 1.0, 1.0, 0.5, 0.5,
        0.5, 0.0, 1.0
    ]

    indices = [
        0, 1, 2, 2, 3, 0, 4, 5, 6, 6, 7, 4, 8, 9, 10, 10, 11, 8, 12, 13, 14,
        14, 15, 12, 16, 17, 18, 18, 19, 16, 20, 21, 22, 22, 23, 20
    ]

    vertices = np.array(vertices, dtype=np.float32)
    indices = np.array(indices, dtype=np.uint32)

    VAO = glGenVertexArrays(1)
    glBindVertexArray(VAO)

    shader = compileProgram(compileShader(vertex_src, GL_VERTEX_SHADER),
                            compileShader(fragment_src, GL_FRAGMENT_SHADER))

    # Vertex Buffer Object
    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices, GL_STATIC_DRAW)

    # Element Buffer Object
    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices,
                 GL_STATIC_DRAW)

    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, vertices.itemsize * 5,
                          ctypes.c_void_p(0))

    glEnableVertexAttribArray(1)
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, vertices.itemsize * 5,
                          ctypes.c_void_p(12))

    texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, texture)

    # Set the texture wrapping parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    # Set texture filtering parameters
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

    # load image
    image = Image.open("textures/crate.jpg")
    image = image.transpose(Image.FLIP_TOP_BOTTOM)
    img_data = image.convert("RGBA").tobytes()
    # img_data = np.array(image.getdata(), np.uint8) # second way of getting the raw image data
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.width, image.height, 0,
                 GL_RGBA, GL_UNSIGNED_BYTE, img_data)

    glBindVertexArray(0)
    glBindBuffer(GL_ARRAY_BUFFER, 0)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)

    glClearColor(0, 0.1, 0.1, 1)
    glEnable(GL_DEPTH_TEST)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    # projection = pyrr.matrix44.create_perspective_projection_matrix(45, 1280/720, 0.1, 100)
    projection = pyrr.matrix44.create_orthogonal_projection_matrix(
        0, 1280, 0, 720, -1000, 1000)
    translation = pyrr.matrix44.create_from_translation(
        pyrr.Vector3([400, 200, -3]))
    scale = pyrr.matrix44.create_from_scale(pyrr.Vector3([200, 200, 200]))

    glUseProgram(shader)
    model_loc = glGetUniformLocation(shader, "model")
    proj_loc = glGetUniformLocation(shader, "projection")

    glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)
    glUseProgram(0)

    # the main application loop
    while not glfw.window_should_close(window):
        glfw.poll_events()

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        rot_x = pyrr.Matrix44.from_x_rotation(0.5 * glfw.get_time())
        rot_y = pyrr.Matrix44.from_y_rotation(0.8 * glfw.get_time())

        rotation = pyrr.matrix44.multiply(rot_x, rot_y)
        model = pyrr.matrix44.multiply(scale, rotation)
        model = pyrr.matrix44.multiply(model, translation)
        glUseProgram(shader)
        glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)

        glBindVertexArray(VAO)
        glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)
        glBindVertexArray(0)
        glUseProgram(0)

        glfw.swap_buffers(window)

    # terminate glfw, free up allocated resources
    glfw.terminate()
Example #52
0
def main():

    # initialize glfw
    if not glfw.init():
        return

    # create a window
    h = 600
    w = 600
    mywin = glfw.create_window(w, h, "My Window", None, None)

    # check if the window is initialized
    if not mywin:
        glfw.terminate()
        return

    # set the created window the current context
    glfw.make_context_current(mywin)

    # create a mesh
    # psotion        #color
    triangle = [
        -.5, -.5, 0., 1., 0., 0., 0., .5, 0., 0., 1., 0., .5, -.5, 0., 0., 0.,
        1.
    ]

    triangle = np.array(triangle, dtype=np.float32)

    # now we pass these information to the GPU (creating mesh program)
    # vertex shader
    vertex_shader = """
    #version 330
    in vec3 position;
    in vec3 color;
    out vec3 newColor;
    void main(){
        gl_Position = vec4(position, 1.0f);
        newColor = color;
    }
    """

    # fragment shader
    fragment_shader = """
    #version 330
    in vec3 newColor;
    out vec4 outColor;
    void main(){
        outColor = vec4(newColor, 1.0f);
    }
    """

    # compile shader program (combine shader objects)
    shader = glShader.compileProgram(
        glShader.compileShader(vertex_shader, GL_VERTEX_SHADER),
        glShader.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    # send the information to GPU (create VBO, bind and copy data)
    vbo = glGenBuffers(1)  # create vbo
    glBindBuffer(GL_ARRAY_BUFFER, vbo)  # bind it
    glBufferData(GL_ARRAY_BUFFER, triangle.shape[0] * 4, triangle,
                 GL_STATIC_DRAW)

    # now we have to enable and pass the attributes specifically
    # enable and pass position attribute
    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0))

    # enable and pass color attribute
    glEnableVertexAttribArray(1)
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12))

    # and finally, enable the shader program
    glUseProgram(shader)

    # change the background color
    glClearColor(.6, 0., .15, 1.)
    # draw loop
    while not glfw.window_should_close(mywin):

        # clear color and depth buffer
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # draw the triangle (primitive, starting index, number of indices to render)
        glDrawArrays(GL_TRIANGLES, 0, 3)

        glfw.swap_buffers(mywin)  # swap front and back buffer
        glfw.poll_events()  # keep receiving events

    # after exit (closing window), destroy window object and terminate glfw
    glfw.destroy_window(mywin)
    glfw.terminate()
def makeShaders_pull_push(vs, nlvls):
    # Inefficient version: not making use of hardware bilinear sampling.
    h1 = np.array((1 / 64, 3 / 64, 3 / 64, 1 / 64, 3 / 64, 9 / 64, 9 / 64,
                   3 / 64, 3 / 64, 9 / 64, 9 / 64, 3 / 64, 1 / 64, 3 / 64,
                   3 / 64, 1 / 64)).astype(np.float32).reshape(4, 4) * 6
    h2 = np.array((1 / 16, 3 / 16, 3 / 16, 1 / 16, 3 / 16, 9 / 16, 9 / 16,
                   3 / 16, 3 / 16, 9 / 16, 9 / 16, 3 / 16, 1 / 16, 3 / 16,
                   3 / 16, 1 / 16)).astype(np.float32).reshape(4, 4) / 4
    print(' - h1 sum', h1.sum(), 'norm', np.linalg.norm(h1))
    print(' - h2 sum', h2.sum(), 'norm', np.linalg.norm(h2))

    def conv_down(v, out, h, step):
        code = ''
        code += ' vec4 a11 = h11 * texture(lastImg, uv + vec2(-STEP*2./2.,-STEP*2./2.));'
        code += ' vec4 a12 = h12 * texture(lastImg, uv + vec2(-STEP*2./2.,-STEP*1./2.));'
        code += ' vec4 a13 = h13 * texture(lastImg, uv + vec2(-STEP*2./2.,+STEP*1./2.));'
        code += ' vec4 a14 = h14 * texture(lastImg, uv + vec2(-STEP*2./2.,+STEP*2./2.));'
        code += ' vec4 a21 = h21 * texture(lastImg, uv + vec2(-STEP*1./2.,-STEP*2./2.));'
        code += ' vec4 a22 = h22 * texture(lastImg, uv + vec2(-STEP*1./2.,-STEP*1./2.));'
        code += ' vec4 a23 = h23 * texture(lastImg, uv + vec2(-STEP*1./2.,+STEP*1./2.));'
        code += ' vec4 a24 = h24 * texture(lastImg, uv + vec2(-STEP*1./2.,+STEP*2./2.));'
        code += ' vec4 a31 = h31 * texture(lastImg, uv + vec2(+STEP*1./2.,-STEP*2./2.));'
        code += ' vec4 a32 = h32 * texture(lastImg, uv + vec2(+STEP*1./2.,-STEP*1./2.));'
        code += ' vec4 a33 = h33 * texture(lastImg, uv + vec2(+STEP*1./2.,+STEP*1./2.));'
        code += ' vec4 a34 = h34 * texture(lastImg, uv + vec2(+STEP*1./2.,+STEP*2./2.));'
        code += ' vec4 a41 = h41 * texture(lastImg, uv + vec2(+STEP*2./2.,-STEP*3./2.));'
        code += ' vec4 a42 = h42 * texture(lastImg, uv + vec2(+STEP*2./2.,-STEP*1./2.));'
        code += ' vec4 a43 = h43 * texture(lastImg, uv + vec2(+STEP*2./2.,+STEP*1./2.));'
        code += ' vec4 a44 = h44 * texture(lastImg, uv + vec2(+STEP*2./2.,+STEP*2./2.));'
        code += ' vec4 b = a11 + a12 + a13 + a14 + a21 + a22 + a23 + a24  +'
        code += '          a31 + a32 + a33 + a34 + a41 + a42 + a43 + a44;'
        #code += ' float w = clamp(b.w,0.000000000001,999.);'
        code += ' float w = clamp(b.w,0.00001,999.);'
        code += ' float wc = 1. - pow((1. - clamp(w,0.,1.)), 16.0);'
        #code += ' float wc = clamp(w,0.,1.);'
        code += ' vec3 a = b.rgb / w;'
        code += ' if (isLastLvl != 1) a = a * wc;'
        code += ' {} = vec4(a,wc);'.format(out)
        for i in range(1, 5):
            for j in range(1, 5):
                code = code.replace('h' + str(i) + str(j), str(h[i - 1,
                                                                 j - 1]))
        code = code.replace('STEP', step)
        return code

    def conv_up(v, out, h, step):
        code = ''
        code += ' vec4 a0 = texture(img, uv);'
        code += ' vec4 a11 = h11 * texture(nxtImg, uv2 + vec2(-STEP*2./2.,-STEP*2./2.));'
        code += ' vec4 a12 = h12 * texture(nxtImg, uv2 + vec2(-STEP*2./2.,-STEP*1./2.));'
        code += ' vec4 a13 = h13 * texture(nxtImg, uv2 + vec2(-STEP*2./2.,+STEP*1./2.));'
        code += ' vec4 a14 = h14 * texture(nxtImg, uv2 + vec2(-STEP*2./2.,+STEP*2./2.));'
        code += ' vec4 a21 = h21 * texture(nxtImg, uv2 + vec2(-STEP*1./2.,-STEP*2./2.));'
        code += ' vec4 a22 = h22 * texture(nxtImg, uv2 + vec2(-STEP*1./2.,-STEP*1./2.));'
        code += ' vec4 a23 = h23 * texture(nxtImg, uv2 + vec2(-STEP*1./2.,+STEP*1./2.));'
        code += ' vec4 a24 = h24 * texture(nxtImg, uv2 + vec2(-STEP*1./2.,+STEP*2./2.));'
        code += ' vec4 a31 = h31 * texture(nxtImg, uv2 + vec2(+STEP*1./2.,-STEP*2./2.));'
        code += ' vec4 a32 = h32 * texture(nxtImg, uv2 + vec2(+STEP*1./2.,-STEP*1./2.));'
        code += ' vec4 a33 = h33 * texture(nxtImg, uv2 + vec2(+STEP*1./2.,+STEP*1./2.));'
        code += ' vec4 a34 = h34 * texture(nxtImg, uv2 + vec2(+STEP*1./2.,+STEP*2./2.));'
        code += ' vec4 a41 = h41 * texture(nxtImg, uv2 + vec2(+STEP*2./2.,-STEP*2./2.));'
        code += ' vec4 a42 = h42 * texture(nxtImg, uv2 + vec2(+STEP*2./2.,-STEP*1./2.));'
        code += ' vec4 a43 = h43 * texture(nxtImg, uv2 + vec2(+STEP*2./2.,+STEP*1./2.));'
        code += ' vec4 a44 = h44 * texture(nxtImg, uv2 + vec2(+STEP*2./2.,+STEP*2./2.));'
        code += ' vec4 b = a11 + a12 + a13 + a14 + a21 + a22 + a23 + a24  +'
        code += '          a31 + a32 + a33 + a34 + a41 + a42 + a43 + a44;'
        #code += ' float wc = clamp(b.a/6.0 + a0.a, 0., 1.);' # WTF is this
        #code += ' float wc = a0.w;'
        code += ' float wc = a0.w;'
        code += ' vec3 a = (1.-wc) * b.rgb + a0.rgb;'
        #code += ' vec3 a = b.rgb;'
        #code += ' vec3 a = (1.-wc) * b.rgb;'
        #code += ' vec3 a =  texture(texSampler, uv).rgb;'
        #code += ' vec3 a =  a0.rgb;'
        #code += ' vec3 a = a0.rgb;'
        code += ' {} = vec4(a,1.);'.format(out)
        #code += ' {} = vec4(a0.rgb,1.);'.format(out)
        for i in range(1, 5):
            for j in range(1, 5):
                code = code.replace('h' + str(i) + str(j), str(h[i - 1,
                                                                 j - 1]))
        code = code.replace('STEP', step)
        return code

    push = '''
    #version 440
    in vec2 v_uv;
    layout(location = 0) out vec4 color;
    layout(binding = 0) uniform sampler2D lastImg;
    layout(location = 3) uniform float W;
    layout(location = 4) uniform int lvl;
    layout(location = 5) uniform int isLastLvl;
    void main() {
        int lvl1 = lvl-1;

        float P = (1. / (1<<(lvl1+1)));
        float uoff = .5 * (1 - pow(.25,(lvl1+1)/2)) / (1.-.25);
        float voff = .25 * (1 - pow(.25,(lvl1)/2)) / (1.-.25);
        vec2 uv = (4./3.) * (P * v_uv + vec2(uoff,voff));

        float step = (2./3.) / (W);
    ''' + conv_down(1, 'color', h1, 'step') + '''
    }'''
    pull = '''
    #version 440
    in vec2 v_uv;
    layout(location = 0) out vec4 color;
    layout(binding = 0) uniform sampler2D img;
    layout(binding = 1) uniform sampler2D nxtImg;
    layout(location = 3) uniform float W;
    layout(location = 4) uniform int lvl;
    void main() {

        int lvl0 = lvl+0;
        int lvl1 = lvl+1;
        float P0 = (1. / (1<<(lvl0+1)));
        float uoff0 = .5 * (1 - pow(.25,(lvl0+1)/2)) / (1.-.25);
        float voff0 = .25 * (1 - pow(.25,(lvl0)/2)) / (1.-.25);
        float P1 = (1. / (1<<(lvl1+1)));
        float uoff1 = .5 * (1 - pow(.25,(lvl1+1)/2)) / (1.-.25);
        float voff1 = .25 * (1 - pow(.25,(lvl1)/2)) / (1.-.25);

        vec2 uv = (4./3.) * (P0 * v_uv + vec2(uoff0,voff0));
        vec2 uv2 = (4./3.) * (P1 * v_uv + vec2(uoff1,voff1));
        float step = (2./3.) / W;

    ''' + conv_up(1, 'color', h2, 'step') + '''
    }
    '''

    push = push.replace('; ', ';\n ')
    pull = pull.replace('; ', ';\n ')
    pull = compileShader(pull, GL_FRAGMENT_SHADER)
    push = compileShader(push, GL_FRAGMENT_SHADER)
    push = compileProgram(vs, push)
    pull = compileProgram(vs, pull)

    return dict(pushShader=push, pullShader=pull)
def initialize():
    global VERTEX_SHADER
    global FRAGMENT_SHADER
    global shaderProgram
    global VAO
    global tex
    global texKitten
    global texPuppy
    # compile shaders and program
    vertexShader = shaders.compileShader(VERTEX_SHADER, GL_VERTEX_SHADER)
    fragmentShader = shaders.compileShader(FRAGMENT_SHADER, GL_FRAGMENT_SHADER)
    shaderProgram = shaders.compileProgram(vertexShader, fragmentShader)
    glUseProgram(shaderProgram)
    # triangle position and color
    vertex_data_type = np.float32
    vertex_positions = [
        -0.5,
        0.5,
        0.0,
        1,  #linksboven: x,y,z,w
        0.5,
        0.5,
        0.0,
        1.0,  #rechtsboven: x,
        0.5,
        -0.5,
        0.0,
        1.0,  #rechtsonder
        -0.5,
        -0.5,
        0.0,
        1.0
    ]

    vertex_colors = [
        1.0,
        0.0,
        0.0,
        1.0,  #linksboven RGBA
        0.0,
        1.0,
        0.0,
        1.0,  #rechtsboven: 
        0.0,
        0.0,
        1.0,
        1.0,  #rechtsonder
        1.0,
        1.0,
        1.0,
        1.0
    ]

    vertex_texture = [
        0,
        0,  #2d texture coordinaten
        1,
        0,
        1,
        1,
        0,
        1
    ]
    vertexData = np.array(vertex_positions + vertex_colors + vertex_texture,
                          dtype=vertex_data_type)

    # create VAO
    VAO = glGenVertexArrays(1)
    glBindVertexArray(VAO)

    #elements

    elements = np.array([
        0,
        1,
        2,
        2,
        3,
        0,
    ], dtype=np.uint32)

    ebo = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, elements.nbytes, elements,
                 GL_STATIC_DRAW)

    #texturethings
    textures = glGenTextures(2)
    glActiveTexture(GL_TEXTURE0)
    glBindTexture(GL_TEXTURE_2D, textures[0])
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    tempcolor = np.array([0.5, 0.5, 0.5, 1], dtype=np.float32)
    glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, tempcolor)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    glGenerateMipmap(GL_TEXTURE_2D)

    im = PIL.Image.open(
        "C:/Users/daniel/Documents/python/opengloefenen/sample.png")
    try:
        ix, iy, image = im.size[0], im.size[1], im.tostring(
            "raw", "RGB", 0, -1)
    except SystemError:
        ix, iy, image = im.size[0], im.size[1], im.tostring(
            "raw", "RGBX", 0, -1)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, ix, iy, 0, GL_RGB, GL_UNSIGNED_BYTE,
                 image)
    glUniform1i(glGetUniformLocation(shaderProgram, "texKitten"), 0)

    glActiveTexture(GL_TEXTURE1)
    glBindTexture(GL_TEXTURE_2D, textures[1])
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
    tempcolor = np.array([0.5, 0.5, 0.5, 1], dtype=np.float32)
    glTexParameterfv(GL_TEXTURE_2D, GL_TEXTURE_BORDER_COLOR, tempcolor)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
    glGenerateMipmap(GL_TEXTURE_2D)

    im = PIL.Image.open(
        "C:/Users/daniel/Documents/python/opengloefenen/sample2.png")
    try:
        ix, iy, image = im.size[0], im.size[1], im.tostring(
            "raw", "RGB", 0, -1)
    except SystemError:
        ix, iy, image = im.size[0], im.size[1], im.tostring(
            "raw", "RGBX", 0, -1)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, ix, iy, 0, GL_RGB, GL_UNSIGNED_BYTE,
                 image)
    print glGetUniformLocation(shaderProgram, "texPuppy")
    glUniform1i(glGetUniformLocation(shaderProgram, "texPuppy"), 1)

    # create VBO
    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, vertexData.nbytes, vertexData,
                 GL_STATIC_DRAW)

    # enable array and set up data
    glEnableVertexAttribArray(glGetAttribLocation(shaderProgram, "position"))
    glEnableVertexAttribArray(glGetAttribLocation(shaderProgram, "color"))
    glEnableVertexAttribArray(glGetAttribLocation(shaderProgram, "texcoord"))
    glVertexAttribPointer(glGetAttribLocation(shaderProgram, "position"), 4,
                          GL_FLOAT, GL_FALSE, 0, None)
    # the last parameter is a pointer
    # python donot have pointer, have to using ctypes
    glVertexAttribPointer(
        glGetAttribLocation(shaderProgram, "color"), 4, GL_FLOAT, GL_FALSE, 0,
        ctypes.c_void_p(
            np.dtype(vertex_data_type).itemsize *
            len(vertex_positions)))  #96= number of bytes in 6 vertex vectors
    glVertexAttribPointer(
        glGetAttribLocation(shaderProgram, "texcoord"), 2, GL_FLOAT, GL_FALSE,
        0,
        ctypes.c_void_p(
            np.dtype(vertex_data_type).itemsize *
            len(vertex_positions + vertex_colors)))
    glBindBuffer(GL_ARRAY_BUFFER, 0)
    glBindVertexArray(0)

    ##

    #matrixen en zo

    #model=np.matrix(np.identity(4))
    model = np.matrix(
        np.array([[1., 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0],
                  [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]))
    model = rotatez(np.pi) * model
    #result=np.array(model).dot([1,0,0,1])

    glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "model"), 1,
                       GL_FALSE, np.array(model, dtype=np.float32))

    view = np.matrix(
        np.array([[1., 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0],
                  [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]))
    eye = np.array([1.2, 1.2, 1.2])
    at = np.array([0.0, 0.0, 0.0])
    up = np.array([0.0, 0.0, 1.0])
    view2 = lookat2(eye, at, up)
    print view
    print view2
    view = view2

    glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "view"), 1,
                       GL_FALSE, np.array(view, dtype=np.float32))

    proj = np.matrix(
        np.array([[1., 0.0, 0.0, 0.0], [0.0, 1.0, 0.0, 0.0],
                  [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0]]))
    proj2 = Matrix4.new_perspective(math.radians(45.0), 800.0 / 600.0, 1.0,
                                    10.0)  # uit euclid
    glUniformMatrix4fv(glGetUniformLocation(shaderProgram, "proj"), 1,
                       GL_FALSE, np.array(proj, dtype=np.float32))
void main(){
    const vec3 light_color = vec3(1.0,1.0,1.0);

    const vec3 ray = camera_pos.xyz - frag_pos;
    float brightness = dot(frag_normal, ray) / length(ray);
    brightness = clamp(brightness, 0, 1);

    result = vec4(max(0.4,brightness) * light_color * color.rgb, 1.0);
}
""").substitute({
        "size_x": lattice_x,
        "size_y": lattice_y,
        "size_z": lattice_z
    }), GL_FRAGMENT_SHADER)

particle_program = shaders.compileProgram(particle_shader, fragment_shader)
particle_projection_id = shaders.glGetUniformLocation(particle_program,
                                                      'projection')
particle_rotation_id = shaders.glGetUniformLocation(particle_program,
                                                    'rotation')

domain_program = shaders.compileProgram(vertex_shader, fragment_shader)
domain_projection_id = shaders.glGetUniformLocation(domain_program,
                                                    'projection')
domain_rotation_id = shaders.glGetUniformLocation(domain_program, 'rotation')

obstacle_program = shaders.compileProgram(lighting_vertex_shader,
                                          lighting_fragment_shader)
obstacle_projection_id = shaders.glGetUniformLocation(obstacle_program,
                                                      'projection')
obstacle_rotation_id = shaders.glGetUniformLocation(obstacle_program,
Example #56
0
 def init_gl(self):
     vertex_shader = compileShader(
         dedent("""\
         #version 450 core
         #line 36
         
         // Adapted from @jherico's RiftDemo.py in pyovr
         
         layout(location = 0) uniform mat4 Projection = mat4(1);
         layout(location = 4) uniform mat4 ModelView = mat4(1);
         layout(location = 8) uniform float Size = 0.3;
         
         // Minimum Y value is zero, so cube sits on the floor in room scale
         const vec3 UNIT_CUBE[8] = vec3[8](
           vec3(-1.0, -0.0, -1.0), // 0: lower left rear
           vec3(+1.0, -0.0, -1.0), // 1: lower right rear
           vec3(-1.0, +2.0, -1.0), // 2: upper left rear
           vec3(+1.0, +2.0, -1.0), // 3: upper right rear
           vec3(-1.0, -0.0, +1.0), // 4: lower left front
           vec3(+1.0, -0.0, +1.0), // 5: lower right front
           vec3(-1.0, +2.0, +1.0), // 6: upper left front
           vec3(+1.0, +2.0, +1.0)  // 7: upper right front
         );
         
         const vec3 UNIT_CUBE_NORMALS[6] = vec3[6](
           vec3(0.0, 0.0, -1.0),
           vec3(0.0, 0.0, 1.0),
           vec3(1.0, 0.0, 0.0),
           vec3(-1.0, 0.0, 0.0),
           vec3(0.0, 1.0, 0.0),
           vec3(0.0, -1.0, 0.0)
         );
         
         const int CUBE_INDICES[36] = int[36](
           0, 1, 2, 2, 1, 3, // front
           4, 6, 5, 6, 5, 7, // back
           0, 2, 4, 4, 2, 6, // left
           1, 3, 5, 5, 3, 7, // right
           2, 6, 3, 6, 3, 7, // top
           0, 1, 4, 4, 1, 5  // bottom
         );
         
         out vec3 _color;
         
         void main() {
           _color = vec3(1.0, 0.0, 0.0);
           int vertexIndex = CUBE_INDICES[gl_VertexID];
           int normalIndex = gl_VertexID / 6;
           
           _color = UNIT_CUBE_NORMALS[normalIndex];
           if (any(lessThan(_color, vec3(0.0)))) {
               _color = vec3(1.0) + _color;
           }
         
           gl_Position = Projection * ModelView * vec4(UNIT_CUBE[vertexIndex] * Size, 1.0);
         }
         """), GL_VERTEX_SHADER)
     fragment_shader = compileShader(
         dedent("""\
         #version 450 core
         #line 94
         
         in vec3 _color;
         out vec4 FragColor;
         
         void main() {
           FragColor = vec4(_color, 1.0);
         }
         """), GL_FRAGMENT_SHADER)
     self.shader = compileProgram(vertex_shader, fragment_shader)
     #
     self.vao = glGenVertexArrays(1)
     glBindVertexArray(self.vao)
     glEnable(GL_DEPTH_TEST)
Example #57
0
 def __init__(self, shaders):
     compiled_shaders = [_compile_shader(shader) for shader in shaders]
     self.shader_program = ogl_shaders.compileProgram(*compiled_shaders)
     for shader in compiled_shaders:
         glDeleteShader(shader)
def makeShaders(nlvls):
    vsrc = '''
    #version 440
    layout(location = 0) in vec3 i_pos;
    layout(location = 1) in vec2 i_uv;
    out vec2 v_uv;
    void main() {
        gl_Position = vec4(i_pos,1.0);
        v_uv = i_uv;
    }'''
    vs = compileShader(vsrc, GL_VERTEX_SHADER)
    unproject = '''
    #version 440
    in vec2 v_uv;
    out vec4 xyz;
    layout(location = 4) uniform mat4 invProj;
    layout(binding = 0) uniform sampler2D depthMap;

    const float twoThirds = 2./3.;
    const float threeHalfs = 3./2.;

    void main() {
        //vec2 uv = (3./2.) * v_uv;
        vec2 uv = v_uv;
        float x = uv.x * 2. - 1.;
        float y = uv.y * 2. - 1.;

        //float z = texture(depthMap, (2./3.) * v_uv).r * 2 - 1.;
        float z = texture(depthMap, (2./3.) * v_uv).r;
        xyz = (invProj *  vec4(x,y, z, 1));

        /*
        //float z = texture(depthMap, v_uv).r;
        //float z = (texture(depthMap, v_uv).r + 1.) * .5;
        float z0 = texture(depthMap, v_uv).r;
        float z = (z0 * 2.) - 1.;

        //xyz = (invProj * vec4(x,y, 1., -z));
        //xyz = (invProj * z * vec4(x,y, 1., -1.));

        //xyz = (invProj *  vec4(x,y, z, 1));

        float far = 4.;
        float near = .02;
        float zz = (2*far*near/(far-near)) / (z0 * -2. + 1. + (far+near) / (far-near));
        zz = (zz - near) / (far - near);
        xyz = vec4(x*invProj[0][0], y*invProj[1][1], -zz, 1.);
        */

        xyz.xyz = xyz.xyz / xyz.w;
        //xyz.z *= -1;

        // NOTE: Dividing by far plane here.
        xyz.z *= -1 / 4.2;
        xyz.a = 1.0;
    }
    '''
    pyrDownDepth = '''
    #version 440
    in vec2 v_uv;
    layout(location = 0) out vec4 xyz;
    layout(binding = 0) uniform sampler2D texXYZ;
    //layout(location = 2) uniform float S;
    //layout(location = 3) uniform float H;

    layout(location = 2) uniform float W;
    layout(location = 3) uniform int lvl0;

    const float twoThirds = 2./3.;
    const float threeHalfs = 3./2.;

    void main() {

        int lvl1 = lvl0 - 1;

        //float P = (1. / (1<<(lvl1+1)));
        float P = (1. / (1<<(lvl1+1)));
        float uoff = .5 * (1 - pow(.25,(lvl1+1)/2)) / (1.-.25);
        float voff = .25 * (1 - pow(.25,(lvl1)/2)) / (1.-.25);

        vec2 uv1 = (4./3.) * (P * v_uv + vec2(uoff, voff));

        // I think the step is constant. Although the access in terms of level=0
        // is (1<<lvl)/W, the access of the above level is fixed per lvl?
        //float step = (1<<lvl1) / W;
        float step = (2./3.) / W;

        vec4 p11 = texture(texXYZ, uv1 + vec2(0.,0.));
        vec4 p12 = texture(texXYZ, uv1 + vec2(0.,step));
        vec4 p21 = texture(texXYZ, uv1 + vec2(step,0.));
        vec4 p22 = texture(texXYZ, uv1 + vec2(step,step));

        if (p11.z < p12.z && p11.z < p21.z && p11.z < p22.z) xyz = p11;
        else if (p12.z < p21.z && p12.z < p22.z) xyz = p12;
        else if (p21.z < p22.z) xyz = p21;
        else xyz = p22;
        //if (p11.a > .6 && p11.z < p12.z && p11.z < p21.z && p11.z < p22.z) xyz = p11;
        //else if (p12.a > .6 && p12.z < p21.z && p12.z < p22.z) xyz = p12;
        //else if (p21.a > .6 && p21.z < p22.z) xyz = p21;
        //else xyz = p22;

        //xyz.a = 1.;
        //xyz = vec4(lvl0/8.,lvl0/8.,lvl0/8.,1.);
        //xyz = vec4(uv1.s,uv1.t,1.,1.).bgra;
        //xyz = vec4(v_uv.s,v_uv.t,1.,1.).bgra;

    }'''
    getMask = '''
    #version 440
    in vec2 v_uv;
    layout(location = 0) out vec4 outColor;
    layout(binding = 0) uniform sampler2D xyzEven;
    layout(binding = 1) uniform sampler2D xyzOdd;
    layout(binding = 2) uniform sampler2D inColor;
    //layout(location = 2) uniform float S;
    layout(location = 3) uniform float W;

    void main() {

        // Read depth map to est scale.
        int lvl0 = 3;
        float P0 = (1. / (1<<(lvl0+1)));
        float uoff0 = .5 * (1 - pow(.25,(lvl0+1)/2)) / (1.-.25);
        float voff0 = .25 * (1 - pow(.25,(lvl0)/2)) / (1.-.25);
        vec2 uv0 = (4./3.) * (P0 * v_uv + vec2(uoff0,voff0));

        float s_hpr = 4*4;
        float h_div_2tant = 1;
        //float z = (1. - texture(xyzLvl4, uv0).z / 4.2);
        float z = texture(xyzOdd, uv0).z;

        //float lvl_ = (1-z) * (NLVL + .2);
        //float lvl_ = 1. / (7.1*z);
        float lvl_ = 1 * log(s_hpr * h_div_2tant * (1./z)) / log(2.);

        lvl_ = clamp(lvl_, 0., (NLVL + .01));
        int lvl = int(lvl_);

        vec3 x;
        x = texture(xyzEven, (2./3.) * v_uv).xyz;
        float meanOcc = 0.;

            // Single Level Version
            /*
            float P1 = (1. / (1<<(lvl+1)));
            float uoff1 = .5 * (1 - pow(.25,(lvl+1)/2)) / (1.-.25);
            float voff1 = .25 * (1 - pow(.25,(lvl)/2)) / (1.-.25);
            vec2 uv1 = (4./3.) * (P1 * v_uv + vec2(uoff1,voff1));
            float step = (2./3.) / W;


            for (int dy=-1; dy<2; dy++)
            for (int dx=-1; dx<2; dx++) {
                if (dx != 0 || dy != 0) {
                    //vec2 uv2 = uv1 + vec2(dx * step + off, dy * step + off);
                    vec2 uv2 = uv1 + vec2(dx * step, dy * step);

                    vec3 y;
                    if (lvl % 2 == 0) y = texture(xyzEven, uv2).xyz;
                    else              y = texture(xyzOdd, uv2).xyz;

                    float occ = 1. - dot(normalize(y-x), normalize(-y));
                    meanOcc += occ * (1./8.);
                }
            }
            */

            float sectors[8] = float[](999,999,999,999,999,999,999,999);
            for (int lvl1=0; lvl1<lvl+1; lvl1++) {
                float P1 = (1. / (1<<(lvl1+1)));
                float uoff1 = .5 * (1 - pow(.25,(lvl1+1)/2)) / (1.-.25);
                float voff1 = .25 * (1 - pow(.25,(lvl1)/2)) / (1.-.25);
                vec2 uv1 = (4./3.) * (P1 * v_uv + vec2(uoff1,voff1));
                float step = (2./3.) / W;
                int ii = 0;

                for (int dy=-1; dy<2; dy++)
                for (int dx=-1; dx<2; dx++) {
                    if (dx != 0 || dy != 0) {
                        //vec2 uv2 = uv1 + vec2(dx * step + off, dy * step + off);
                        vec2 uv2 = uv1 + vec2(dx * step, dy * step);

                        //if (uv2.x < (4./3.)*uoff1 || uv2.y < (4./3.)*voff1) continue;

                        vec3 y;
                        if (lvl1 % 2 == 0) y = texture(xyzEven, uv2).xyz;
                        else               y = texture(xyzOdd, uv2).xyz;

                        float occ = 1. - dot(normalize(y-x), normalize(-y));
                        if (occ < sectors[ii]) sectors[ii] = occ;
                        ii += 1;
                    }
                }
            }
            for (int i=0; i<8; i++) meanOcc += (1./8.) * sectors[i];



        vec4 c0 = texture(inColor, (2./3.) * v_uv);
        outColor = c0;
        //outColor.a *= .9;
        //outColor = vec4(lvl / float(NLVL), lvl / float(NLVL), lvl / float(NLVL), 1.);

        //outColor = vec4(1.-meanOcc,0.,meanOcc,1.);

        //const float meanOccThresh = .1 + .1 * log(.1 + 1./z);
        //const float meanOccThresh = .1 + .2 * log(1./(.4+z));
        const float meanOccThresh = .12;
        if (meanOcc < meanOccThresh) outColor.a = 0;
        //if (meanOcc < meanOccThresh && c0.a > 0) outColor = vec4(1.,0,0,1.); // Render discard points in red.
    }
    '''.replace('NLVL', str(nlvls))

    simpleTextured = '''
    #version 440
    in vec2 v_uv;
    layout(location = 0) out vec4 color;
    layout(binding = 0) uniform sampler2D tex;
    void main() {
        vec2 uv = (1) * v_uv;
        color = texture(tex, uv);
    }
    '''

    unproject = unproject.replace('; ', ';\n ')
    pyrDownDepth = pyrDownDepth.replace('; ', ';\n ')
    getMask = getMask.replace('; ', ';\n ')
    #print(' unproject SHADER\n',unproject)
    #print(' pyrDownDepth SHADER\n',pyrDownDepth)
    #print(' getMask SHADER\n',getMask)
    unproject = compileShader(unproject, GL_FRAGMENT_SHADER)
    pyrDownDepth = compileShader(pyrDownDepth, GL_FRAGMENT_SHADER)
    getMask = compileShader(getMask, GL_FRAGMENT_SHADER)
    simpleTextured = compileShader(simpleTextured, GL_FRAGMENT_SHADER)

    unproject = compileProgram(vs, unproject)
    pyrDownDepth = compileProgram(vs, pyrDownDepth)
    getMask = compileProgram(vs, getMask)
    simpleTextured = compileProgram(vs, simpleTextured)
    return locals()
Example #59
0
def OnInit():
    global self_shader, self_vbo
    """Initialize the context once we have a valid OpenGL environ"""
    '''==Aside: Compilation Errors==
    
    As we get more and more complex shaders, you are inevitably
    going to run into situations where your shaders have compilation 
    errors and need to be debugged.  The PyOpenGL convenience 
    wrappers for shaders will raise a RuntimeError instance when/if 
    shader compilation fails.  The second argument to the RuntimeError
    will be the source-code that was being compiled when the failure 
    occurred.  Normally the Python traceback of this error will be 
    sufficient to help you track down the problem (with the appropriate
    references, of course).'''
    ##    try:
    ##        shaders.compileShader( """ void main() {} """, GL_VERTEX_SHADER )
    ##    except (GLError, RuntimeError) as err:
    ##        print('Example of shader compile error', err)
    ##    else:
    ##        raise RuntimeError( """Didn't catch compilation error!""" )
    '''==Varying Values==
    
    In our previous tutorial, we calculated the colour of each 
    fragment as a constant colour (green).  Now we are going to 
    make each vertex a different colour and allow the GL to 
    interpolate between those colours.
    
    We are going to use the legacy OpenGL colour for our vertices,
    that is, the colour that would normally be provided to the 
    legacy (fixed-function) pipeline.  This value shows up as the 
    built-in vec4 "gl_Color".  Within the vertex shader, each call 
    of the vertex shader will have gl_Color assigned.
    
    To communicate the colour for each vertex to the fragment 
    shader, we need to define a "varying" variable.  A varying 
    variable is interpolated across the triangle for each fragment,
    taking the perspectivally correct blended value for the vertices
    which make up each corner of the triangle.  Thus if we were to 
    define one vertex as being black and another as white, the
    fragments generated for the area between them would fade from 
    black to white (via grey).
    
    You will note that we define the varying value *outside* the main 
    function.  The varying value can be loosely thought of as being 
    declared a "global" so that it can be seen in both shaders.  
    However, the varying value is is being processed by intermediate
    clipping and interpolation processes.
    '''
    vertex = shaders.compileShader(
        """
        varying vec4 vertex_color;
        void main() {
            gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex;
            vertex_color = gl_Color;
        }""", GL_VERTEX_SHADER)
    '''Our fragment shader, again, declares the vertex_color
    varying value.  Since we would like the final fragment 
    colour to be the interpolated colour between our vertices,
    we can simply assign vertex_color to gl_FragColor.'''
    fragment = shaders.compileShader(
        """
        varying vec4 vertex_color;
        void main() {
            gl_FragColor = vertex_color;
        }""", GL_FRAGMENT_SHADER)
    self_shader = shaders.compileProgram(vertex, fragment)
    '''Our geometry now has two components for every vertex,
    the first is the vertex position, which is the same set of 
    values as we saw in our previous tutorial.  The first three 
    floats in each vertex (row) are the position.   The last 
    three values represent the colours of each vertex.  Thus 
    the triangle (the first three vertices) will blend from 
    red to yellow to cyan.
    
    As noted in the previous tutorial, this "packed" format 
    tends to be more efficient on modern hardware than having 
    separate data-arrays for each type of data.
    '''
    self_vbo = vbo.VBO(
        array([
            [0, 1, 0, 0, 1, 0],
            [-1, -1, 0, 1, 1, 0],
            [1, -1, 0, 0, 1, 1],
            [2, -1, 0, 1, 0, 0],
            [4, -1, 0, 0, 1, 0],
            [4, 1, 0, 0, 0, 1],
            [2, -1, 0, 1, 0, 0],
            [4, 1, 0, 0, 0, 1],
            [2, 1, 0, 0, 1, 1],
        ], 'f'))
Example #60
0
    def initGL(self):
        """opengl initialization"""
        # load shaders
        vertexShader = self.shaderFromFile(GL_VERTEX_SHADER,
                                           self.__vertexShader)
        geomShader = self.shaderFromFile(GL_GEOMETRY_SHADER, self.__geomShader)
        fragmentShader = self.shaderFromFile(GL_FRAGMENT_SHADER,
                                             self.__fragmentShader)
        self.__shaderProgram = shaders.compileProgram(vertexShader, geomShader,
                                                      fragmentShader)
        if not self.__shaderProgram:
            self.close()

        # obtain location of projection uniform
        self.__viewLocation = glGetUniformLocation(self.__shaderProgram,
                                                   'View')
        self.__projLocation = glGetUniformLocation(self.__shaderProgram,
                                                   'Projection')

        # transform feedback shader and program
        tfShader = self.shaderFromFile(GL_VERTEX_SHADER, self.__tfShader)
        self.__tshaderProgram = glCreateProgram()
        glAttachShader(self.__tshaderProgram, tfShader)

        # specify transform feedback output
        varyings = (ctypes.c_char_p * 2)("outposition", "outvelocity")
        c_array = ctypes.cast(varyings,
                              ctypes.POINTER(ctypes.POINTER(ctypes.c_char)))
        glTransformFeedbackVaryings(self.__tshaderProgram, len(varyings),
                                    c_array, GL_INTERLEAVED_ATTRIBS)

        glLinkProgram(self.__tshaderProgram)

        self.__centerLocation = glGetUniformLocation(self.__tshaderProgram,
                                                     'center')
        self.__radiusLocation = glGetUniformLocation(self.__tshaderProgram,
                                                     'radius')
        self.__gLocation = glGetUniformLocation(self.__tshaderProgram, 'g')
        self.__dtLocation = glGetUniformLocation(self.__tshaderProgram, 'dt')
        self.__bounceLocation = glGetUniformLocation(self.__tshaderProgram,
                                                     'bounce')
        self.__seedLocation = glGetUniformLocation(self.__tshaderProgram,
                                                   'seed')

        # randomly place particles in a cube
        vertexData = []
        for i in xrange(self.__particles):
            # initial position
            pos = glm.vec3(.5 - rand(), .5 - rand(), .5 - rand())
            vertexData.append(glm.vec3(0.0, 20.0, 0.0) + 5.0 * pos)

            # initial velocity
            vertexData.append(glm.vec3(0.0, 0.0, 0.0))

        # generate vbos and vaos
        self.__vao = glGenVertexArrays(self.__bufferCount)
        self.__vbo = glGenBuffers(self.__bufferCount)

        vertexData = np.array(vertexData, dtype=np.float32)
        for i in range(self.__bufferCount):
            glBindVertexArray(self.__vao[i])

            glBindBuffer(GL_ARRAY_BUFFER, self.__vbo[i])

            # fill with initial data
            glBufferData(GL_ARRAY_BUFFER, vertexData.nbytes, vertexData,
                         GL_STATIC_DRAW)

            # set up generic attrib pointers
            glEnableVertexAttribArray(0)
            glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 6 * 4, None)
            # set up generic attrib pointers
            glEnableVertexAttribArray(1)
            glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 6 * 4,
                                  ctypes.c_void_p(3 * 4))

        glBindVertexArray(0)

        # we are blending so no depth testing
        glDisable(GL_DEPTH_TEST)

        # enable blending
        glEnable(GL_BLEND)
        # and set the blend function to result = 1 * source + 1 * destination
        glBlendFunc(GL_ONE, GL_ONE)

        # define sphere for the particles to bounce off
        center = []
        radius = []
        center.append((0.0, 12.0, 1.0))
        radius.append(3)
        center.append((-3.0, 0.0, 0.0))
        radius.append(7)
        center.append((5.0, -10.0, 0.0))
        radius.append(12)
        self.__center = np.array(center, dtype=np.float32)
        self.__radius = np.array(radius, dtype=np.float32)

        # physical parameters
        self.__dt = 1.0 / 60.0
        self.__g = np.array((0.0, -9.81, 0.0), dtype=np.float32)
        self.__bounce = 1.2

        self.__currentBuffer = 0