Ejemplo n.º 1
0
    def paintGL(self):
        # clear the buffer
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        # Run the compute phase
        i = 0
        while (i * MAX_WORKGROUPS < self.count):
            upper = min(self.count, (i+1) * MAX_WORKGROUPS)
            data = self.valueBuffer[i*MAX_WORKGROUPS:upper]
            status = self.statusBuffer[i*MAX_WORKGROUPS:upper]
            
            gl.glBindBufferBase(gl.GL_SHADER_STORAGE_BUFFER, 0, self.ssbos['data'])
            gl.glBufferData(gl.GL_SHADER_STORAGE_BUFFER, 
                            data.nbytes,
                            data, gl.GL_DYNAMIC_COPY)

            gl.glBindBufferBase(gl.GL_SHADER_STORAGE_BUFFER, 1, self.ssbos['status'])
            gl.glBufferData(gl.GL_SHADER_STORAGE_BUFFER, 
                            status.nbytes,
                            status, gl.GL_DYNAMIC_COPY)
            

            gl.glUseProgram(self.compute_program)
            gl.glDispatchCompute(min(MAX_WORKGROUPS, self.count - i * MAX_WORKGROUPS), 1, 1)
            gl.glMemoryBarrier(gl.GL_SHADER_STORAGE_BARRIER_BIT)

            # Read back the modified data.
            gl.glBindBufferBase(gl.GL_SHADER_STORAGE_BUFFER, 0, self.ssbos['data'])
            gl.glGetBufferSubData(gl.GL_SHADER_STORAGE_BUFFER, 
                            0,
                            data.nbytes,
                            self.valueBuffer[i*MAX_WORKGROUPS])
            gl.glBindBufferBase(gl.GL_SHADER_STORAGE_BUFFER, 1, self.ssbos['status'])
            gl.glGetBufferSubData(gl.GL_SHADER_STORAGE_BUFFER, 
                            0,
                            status.nbytes,
                            self.statusBuffer[i*MAX_WORKGROUPS])
            i += 1
        self.iterations += ITER_PER_CYCLE

        # bind the VBO
        self.vbo.bind()
        # tell OpenGL that the VBO contains an array of vertices
        gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
        # these vertices contain 2 single precision coordinates
        gl.glVertexPointer(2, gl.GL_FLOAT, 0, self.vbo)
        
        # Bind statuses
        gl.glBindBuffer(gl.GL_ARRAY_BUFFER, self.ssbos['status'])
        gl.glBufferData(gl.GL_ARRAY_BUFFER, self.statusBuffer.nbytes,
                        self.statusBuffer, gl.GL_DYNAMIC_COPY)
        gl.glVertexAttribIPointer(1, 2, gl.GL_INT, 0, None)
        gl.glEnableVertexAttribArray(1);

        # Use our pipeline.
        gl.glUseProgram(self.render_program)
        # draw "count" points from the VBO
        gl.glDrawArrays(gl.GL_POINTS, 0, self.count)
        # Update the window title.
        self.parent().setWindowTitle("Iterations: %d; zoom; %f" % (self.iterations, self.zoom))
Ejemplo n.º 2
0
    def paintGL(self):
        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
        GL.glLoadIdentity()

        # Draw the numpy array onto the GL frame
        if self.frame is not None and self.frame.img is not None:
            shape = self.frame.img.shape
            # TODO: Flags for horizontal/vertical flipping
            GL.glDrawPixels(shape[1], shape[0], GL.GL_RGB, GL.GL_UNSIGNED_BYTE,
                            np.fliplr(self.frame.img).tostring()[::-1])

        color = (0.5, 0.5, 0.5, 0.5)
        if self.dragging:
            p1 = (self.m_x1, self.m_y1)
            p2 = (self.m_x2, self.m_y2)

            modifiers = QtGui.QApplication.keyboardModifiers()
            if modifiers == QtCore.Qt.ShiftModifier:
                radius = geom.distance(p1, p2)
                p2_c = (int(p1[0]), p1[1]+radius)
                self.drawCircle((p1, p2_c), color=color, filled=True, num_segments=24)
            elif modifiers == QtCore.Qt.ControlModifier:
                self.drawLine((p1, p2), color=color)
            else:
                self.drawRect((p1, p2), color=color)
#        else:
        self.drawCross((self.m_x1, self.m_y1), 20, color)

        # Process job queue
        self.process_paint_jobs()
Ejemplo n.º 3
0
	def Display( self ) :
		# Clear all pixels and depth buffer
		gl.glClear( gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT )
		# Nothing to display
		if not self.element_number : return
		# Display the mesh with solid rendering
		if self.wireframe_mode == 0 :
			# Display the mesh
			self.DisplayMesh()
		# Display the mesh with wireframe rendering
		elif self.wireframe_mode == 1 :
			# 1st pass : wireframe model
			gl.glPolygonMode( gl.GL_FRONT_AND_BACK, gl.GL_LINE )
			self.DisplayMesh( self.wireframe_mode )
			# 2nd pass : solid model
			gl.glPolygonMode( gl.GL_FRONT_AND_BACK, gl.GL_FILL )
			gl.glEnable( gl.GL_POLYGON_OFFSET_FILL )
			gl.glPolygonOffset( 1.0, 1.0 )
			self.DisplayMesh()
			gl.glDisable( gl.GL_POLYGON_OFFSET_FILL )
		# Display the mesh with hidden line removal rendering
		elif self.wireframe_mode == 2 :
			# 1st pass : wireframe model
			gl.glPolygonMode( gl.GL_FRONT_AND_BACK, gl.GL_LINE )
			self.DisplayMesh()
			# 2nd pass : hidden line removal
			gl.glPolygonMode( gl.GL_FRONT_AND_BACK, gl.GL_FILL )
			gl.glEnable( gl.GL_POLYGON_OFFSET_FILL )
			gl.glPolygonOffset( 1.0, 1.0 )
			self.DisplayMesh( self.wireframe_mode )
			gl.glDisable( gl.GL_POLYGON_OFFSET_FILL )
    def render(self):
        viewport = GL.glGetIntegerv(GL.GL_VIEWPORT)
        width = viewport[2]
        height = viewport[3]
        
        # Render the widget using a separate viewport
        side = min(width, height)
        GL.glViewport((width - side) / 2, (height - side) / 2, side, side)

        GL.glClearColor(*self.trolltechPurple.darker().getRgbF())
        GL.glShadeModel(GL.GL_FLAT)
        GL.glEnable(GL.GL_DEPTH_TEST)
        #GL.glEnable(GL.GL_CULL_FACE)
        
        GL.glTranslatef(0.0, 0.0, -10.0)

        GL.glMatrixMode(GL.GL_PROJECTION)
        GL.glLoadIdentity()
        GL.glOrtho(-0.5, +0.5, +0.5, -0.5, 4.0, 15.0)
        GL.glMatrixMode(GL.GL_MODELVIEW)

        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
        GL.glLoadIdentity()
        GL.glTranslated(0.0, 0.0, -10.0)

        GL.glRotated(self.xRot / 16.0, 1.0, 0.0, 0.0)
        GL.glRotated(self.yRot / 16.0, 0.0, 1.0, 0.0)
        GL.glRotated(self.zRot / 16.0, 0.0, 0.0, 1.0)
        
        self.threed_object.render()
        
        # reset the viewport
        GL.glViewport(*viewport)
Ejemplo n.º 5
0
 def drawSelf(self):
     color = self.sceneNode.clearColor
     if color is None:
         GL.glClear(GL.GL_DEPTH_BUFFER_BIT)
     else:
         GL.glClearColor(*color)
         GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
Ejemplo n.º 6
0
def load_and_draw_model(filename):
    ''' Loads a model from an .obj file using objloader.py.
      Assumes there is a .mtl material file with the same name. '''
    GL.glEnable(GL.GL_LIGHTING)
    GL.glEnable(GL.GL_LIGHT0)
    GL.glEnable(GL.GL_DEPTH_TEST)
    GL.glEnable(GL.GL_COLOR_MATERIAL)
    GL.glShadeModel(GL.GL_SMOOTH)
    GL.glClear(GL.GL_DEPTH_BUFFER_BIT)


    # set model color
    GL.glMaterialfv(GL.GL_FRONT, GL.GL_AMBIENT, [0,0,0,0])
    GL.glMaterialfv(GL.GL_FRONT, GL.GL_DIFFUSE, [0.5,0.75,1.0,0.0])
    GL.glMaterialfv(GL.GL_FRONT, GL.GL_SPECULAR, [0.7, 0.6, 0.6, 0.0])
    GL.glMaterialf(GL.GL_FRONT, GL.GL_SHININESS, 0.25*128.0)

    # load from a file
    import objloader
    obj = objloader.OBJ(filename,swapyz=True)
    size = 0.01
    angle = [-0,0,0]
    GL.glScalef(size, size, size)
    GL.glRotatef(angle[0], 1, 0, 0)
    GL.glRotatef(angle[1], 0, 1, 0)
    GL.glRotatef(angle[2], 0, 0, 1)
    GL.glCallList(obj.gl_list)
Ejemplo n.º 7
0
def draw_background(imname):
    ''' Draw background image using a quad. '''

    # load background image (should be .bmp) to OpenGL texture
    bg_image = pygame.image.load(imname).convert()
    bg_data = pygame.image.tostring(bg_image, "RGBA", 1)

    GL.glMatrixMode(GL.GL_MODELVIEW)
    GL.glLoadIdentity()

    GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

    # bind the texture
    GL.glEnable(GL.GL_TEXTURE_2D)
    GL.glBindTexture(GL.GL_TEXTURE_2D, GL.glGenTextures(1))
    GL.glTexImage2D(GL.GL_TEXTURE_2D, 0, GL.GL_RGBA, width, height, 0, GL.GL_RGBA, GL.GL_UNSIGNED_BYTE, bg_data)
    GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MAG_FILTER, GL.GL_NEAREST)
    GL.glTexParameterf(GL.GL_TEXTURE_2D, GL.GL_TEXTURE_MIN_FILTER, GL.GL_NEAREST)

    # create quad to fill the whole window
    GL.glBegin(GL.GL_QUADS)
    GL.glTexCoord2f(0.0, 0.0); GL.glVertex3f(-1.0, -1.0, -1.0)
    GL.glTexCoord2f(1.0, 0.0); GL.glVertex3f(1.0, -1.0, -1.0)
    GL.glTexCoord2f(1.0, 1.0); GL.glVertex3f(1.0, 1.0, -1.0)
    GL.glTexCoord2f(0.0, 1.0); GL.glVertex3f(-1.0, 1.0, -1.0)
    GL.glEnd()

    # clear the texture
    GL.glDeleteTextures(1)
Ejemplo n.º 8
0
    def display(self):
        """ Render the scene. """
        start = time.time()

        GL.glClear(GL.GL_COLOR_BUFFER_BIT |
                   GL.GL_DEPTH_BUFFER_BIT)
        GL.glPushMatrix()

        cam_x = self.zoom * math.sin(self.cam_lat) * math.cos(self.cam_long)
        cam_y = self.zoom * math.sin(self.cam_lat) * math.sin(self.cam_long)
        cam_z = self.zoom * math.cos(self.cam_lat)
        GLU.gluLookAt(cam_x, cam_y, cam_z, 0, 0, 0, 0, 0, 2)

        self.display_box()
        self.display_points()
        self.display_segments()
        self.display_circles()
        self.display_polygons()
        self.display_regions()
        self.display_sphere()

        GL.glPopMatrix()
        GLUT.glutSwapBuffers()

        render_time = time.time() - start
        GLUT.glutSetWindowTitle("%.3f" % render_time)
Ejemplo n.º 9
0
def gl_init( width, height ):
    global __legocaptex,__quadratic
    
    setviewport(width, height)
    
    __legocaptex = layer_manager.load_2d_texture(pygame.image.tostring(__image, "RGBA"), LEGO_CAP_WIDTH, LEGO_CAP_HEIGHT)
    __quadratic = GLU.gluNewQuadric()
    
    GLU.gluQuadricTexture(__quadratic, GLU.GLU_TRUE)
    GLU.gluQuadricDrawStyle(__quadratic,GLU.GLU_FILL)    
    GLU.gluQuadricOrientation(__quadratic, GLU.GLU_OUTSIDE)
    GLU.gluQuadricNormals(__quadratic, GLU.GLU_SMOOTH)
    
    GL.glClearColor( 0.0, 0.2, 0.5, 1.0 )
    
    GL.glEnable(GL.GL_POINT_SMOOTH)
    GL.glEnable(GL.GL_LINE_SMOOTH)
    GL.glEnable(GL.GL_TEXTURE_2D)
    GL.glEnable(GL.GL_ALPHA_TEST)
    GL.glEnable(GL.GL_COLOR_MATERIAL)
    GL.glDisable(GL.GL_CULL_FACE)
    GL.glAlphaFunc(GL.GL_GREATER,0.1)
    
    GL.glClearAccum(0.0, 0.0, 0.0, 1.0)
    GL.glClear(GL.GL_ACCUM_BUFFER_BIT)
    
    #GL.glGenLists(1)
    
    draw_mode_3d()
Ejemplo n.º 10
0
    def on_paint(self, event):
        """Process the drawing event."""
        import OpenGL.GL as gl
        import OpenGL.GLU as glu
        self.canvas.SetCurrent(self.canvas.context)

        if not self.gl_initialized:
            self.initgl()
            self.gl_initialized = True
            self.print_help()

        if self.light:
            gl.glEnable(gl.GL_LIGHTING)
        else:
            gl.glDisable(gl.GL_LIGHTING)

        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
                   # Clear The Screen And The Depth Buffer
        gl.glLoadIdentity(
        )                                     # Reset The View

        gl.glPushMatrix()
        glu.gluLookAt(*(list(rtp_to_xyz(
            *self.camera_pos_rtp)) + list(self.target_pos) + list(self.up)))

        self.draw_cube()

        gl.glPopMatrix()
        gl.glFlush()
        self.SwapBuffers()
        event.Skip()
Ejemplo n.º 11
0
def render():
    gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1)
    for i in range(10):
        gl.glClearColor(0, 0, 0, 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
        yield
    try:
        song_time = 0
        while song_time < length:
            gl.glClearColor(0, 0, 0, 1)
            gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
            gl.glMatrixMode(gl.GL_PROJECTION)
            gl.glLoadIdentity()
            gl.glOrtho(0, 1, height / float(width), 0, -1, 1)
            gl.glMatrixMode(gl.GL_MODELVIEW)
            gl.glLoadIdentity()
            if v:
                v.draw(song_time, display, length)
            renderer.draw(song_time + headstart, layout)
            gl.glFinish()
            gl.glReadBuffer(gl.GL_BACK)
            data = gl.glReadPixelsub(0, 0, width, height, gl.GL_RGB)
            print "\r%.02f%%" % (100 * song_time / length),
            sys.stdout.flush()
            x264.stdin.write(data.tostring())
            song_time += 1/fps
            #yield
    except Exception as e:
        print e
    finally:
        x264.stdin.close()
        x264.wait()
        os._exit(0)
Ejemplo n.º 12
0
    def render(self):
        gl.glClearColor(0, 0, 0, 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

        with self.shader_prog:
            # Activate array
            gl.glBindVertexArray(self.vao_id)

            # FIXME: Why does the following work? tex_uniform is 1,
            # palette_uniform is 0, but I have to set the uniform for
            # tex_uniform to 0 and the uniform for palette_uniform to 1.
            # Obviously I'm not understanding something.
            #
            # See: http://stackoverflow.com/questions/26622204
            # https://www.opengl.org/discussion_boards/showthread.php/174926-when-to-use-glActiveTexture

            # Activate texture
            print(self.tex_uniform, self.palette_uniform, self.sample_texture, self.palette_id)
            gl.glActiveTexture(gl.GL_TEXTURE0 + self.tex_uniform)
            gl.glBindTexture(gl.GL_TEXTURE_2D, self.sample_texture)
            gl.glUniform1i(self.tex_uniform, 0)

            # Activate palette texture
            gl.glActiveTexture(gl.GL_TEXTURE0 + self.palette_uniform)
            gl.glBindTexture(gl.GL_TEXTURE_BUFFER, self.palette_texture)
            gl.glTexBuffer(gl.GL_TEXTURE_BUFFER, gl.GL_RGBA8, self.palette_id)
            gl.glUniform1i(self.palette_uniform, 1)

            # # Activate array
            # gl.glBindVertexArray(self.vao_id)

            # draw triangle
            gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)
Ejemplo n.º 13
0
Archivo: 003-ebo.py Proyecto: lhl/vrdev
def render():
    global shaderProgram
    global VAO
    global EBO
    global indexData

    GL.glClearColor(0, 0, 0, 1)
    GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

    # active shader program
    GL.glUseProgram(shaderProgram)

    try:
        GL.glBindVertexArray(VAO)

       
        # Draw a triangle
        # GL.glDrawArrays(GL.GL_TRIANGLES, 0, 3)

        # draw triangle, starting index of the vertex array, # of vertices (6 = indexData.size), 
        GL.glDrawElements(GL.GL_TRIANGLES, indexData.size, GL.GL_UNSIGNED_INT, None)
    finally:
        # Unbind when we finish
        GL.glBindVertexArray(0)
        GL.glUseProgram(0)
Ejemplo n.º 14
0
 def __clear_screen(self):
     '''
     Clear screen, setup viewport
     '''
     gl.glClearColor(0.05, 0.05, 0.1, 1.0)
     gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT | gl.GL_STENCIL_BUFFER_BIT)
     gl.glViewport(0, 0, self.gui.window_width, self.gui.window_height)
Ejemplo n.º 15
0
    def paint_slid(self):
        gl.glClear(gl.GL_COLOR_BUFFER_BIT);

        # activate the program and set parameters
        gl.glUseProgram(self.program)
        gl.glUniform1i(self.texture1, 0)  # indicate we use GL_TEXTURE0

        # set up the texture to map
        gl.glEnable(gl.GL_TEXTURE_2D)
        gl.glActiveTexture(gl.GL_TEXTURE0)
        if self.usingA:
            gl.glBindTexture(gl.GL_TEXTURE_2D, self.textureB)
        else:
            gl.glBindTexture(gl.GL_TEXTURE_2D, self.textureA)


        # a simple square filling the whole view
        self.square.bind()

        # activate using VBOs for the vertices
        gl.glEnableVertexAttribArray(0)

        # indicate that the VBO has texture and vertex data
        gl.glEnableClientState(gl.GL_VERTEX_ARRAY);
        gl.glEnableClientState(gl.GL_TEXTURE_COORD_ARRAY);

        # indicate where the vertex and texture data is
        gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT,
                                 gl.GL_FALSE, 5*4, None)
        gl.glTexCoordPointer(2, gl.GL_FLOAT, 5*4, self.square + 3*4)

        # draw the square
        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 6)
Ejemplo n.º 16
0
    def expose_cb(self,w,ev):
        style=self.get_style()
        gc=style.bg_gc[gtk.STATE_NORMAL]

        left,top,width,height=self.get_allocation()

        gldrawable = self.get_gl_drawable()
        glcontext = self.get_gl_context()

        gldrawable.gl_begin(glcontext)
        
        GL.glClearColor(1, 1, 1, 0)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
        GL.glViewport(0,0,width,height)

        GL.glMatrixMode(GL.GL_PROJECTION)
        GL.glLoadIdentity()
        GLU.gluPerspective(23, width/height, 5, 20)
        GL.glMatrixMode(GL.GL_MODELVIEW)
        GL.glLoadIdentity()
        
        self.drawit()

        if gldrawable.is_double_buffered():
            gldrawable.swap_buffers()
        else:
            glFlush()

        gldrawable.gl_end()
def display():
    global offsetUniform, theProgram

    GL.glClearColor(0.0, 0.0, 0.0, 0.0)
    GL.glClear(GL.GL_COLOR_BUFFER_BIT)

    GL.glUseProgram(theProgram)

    GL.glUniform2f(offsetUniform, 0.5, 0.5)

    colorData = sizeOfFloat*len(vertexData)/2
    
    GL.glBindBuffer(GL.GL_ARRAY_BUFFER, vertexBufferObject)   
    positionLocation = GL.glGetAttribLocation(theProgram, 'position')
    colorLocation = GL.glGetAttribLocation(theProgram, 'color')
    GL.glEnableVertexAttribArray(positionLocation)
    GL.glVertexAttribPointer(positionLocation,
                             4,
                             GL.GL_FLOAT, False, 0, null)
    GL.glEnableVertexAttribArray(colorLocation)
    GL.glVertexAttribPointer(colorLocation,
                             4,
                             GL.GL_FLOAT, False, 0, c_void_p(colorData))

    GL.glDrawArrays(GL.GL_TRIANGLES, 0, 36)

    GL.glDisableVertexAttribArray(positionLocation)
    GL.glDisableVertexAttribArray(colorLocation)
    GL.glUseProgram(0)
Ejemplo n.º 18
0
    def drawBackground(self, painter, rect):
        
        if not painter.paintEngine().type() == QtGui.QPaintEngine.OpenGL2:
            print painter.paintEngine().type()
            QtCore.qWarning('OpenGLScene: drawBackground needs a QGLWidget '\
                        +'to be set as viewport on the '\
                        +'graphics view')
            return

        painter.beginNativePainting()
        
        GL.glMatrixMode(GL.GL_PROJECTION)
        GL.glPushMatrix()
        GL.glMatrixMode(GL.GL_MODELVIEW)
        GL.glPushMatrix()

        GL.glClearColor(1.0,1.0,1.0,1.0)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)
        # OpenGL stuff goes here...
        
        GL.glMatrixMode(GL.GL_MODELVIEW)
        GL.glPopMatrix()
     
        GL.glMatrixMode(GL.GL_PROJECTION)
        GL.glPopMatrix()

        painter.endNativePainting()
Ejemplo n.º 19
0
def on_display( ):
    global shader

    gl.glClearColor(1,1,1,1)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
    gl.glActiveTexture(gl.GL_TEXTURE0)
    gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
    gl.glEnable(gl.GL_BLEND)

    gl.glColor(0,0,0,1)
    shader.bind()


    radius = 255.0
    theta, dtheta = 0, 5.5/180.0*math.pi
    support = 0.75
    thickness = 1.0
    for i in range(500):
        x =    256+radius*math.cos(theta);
        y = 32+256+radius*math.sin(theta);
        r = 10.1-i*0.02
        circle( (x,y,r), thickness=thickness, support=support )
        radius -= 0.45
        theta += dtheta

    for i in range(0,39):
        r = 4
        thickness = (i+1)/10.0
        x = 20+i*12.5 - r
        y = 16
        circle( (x,y,r), thickness=thickness, support=support )
 
    glut.glutSwapBuffers( )
Ejemplo n.º 20
0
def render():
    while True:
        gl.glClearColor(0, 0.3, 0, 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
        gl.glLoadIdentity()
        renderer.draw(step, layout)
        yield None
Ejemplo n.º 21
0
def display():
    gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
    program.draw(gl.GL_TRIANGLES, indices)
    glut.glutSwapBuffers()

    # Take screenshot in every display()
    screenshot()
	def get_input(get_what):
		textInput = ''
		gl.glClearColor(0,0,0,1)
		gl.glClear(gl.GL_COLOR_BUFFER_BIT)
		stim_display.refresh()
		simple_wait(0.500)
		my_text = get_what+textInput
		drawText( my_text , instruction_font , stim_display_res[0] , xLoc=stim_display_res[0]/2 , yLoc=stim_display_res[1]/2 , fg=[200,200,200,255] )
		stim_display.refresh()
		done = False
		while not done:
			if not stamper_child.qFrom.empty():
				event = stamper_child.qFrom.get()
				if event['type'] == 'key' :
					response = event['value']
					if response=='q':
						exit_safely()
					elif response == 'backspace':
						if textInput!='':
							textInput = textInput[0:(len(textInput)-1)]
							my_text = get_what+textInput
							drawText( my_text , instruction_font , stim_display_res[0] , xLoc=stim_display_res[0]/2 , yLoc=stim_display_res[1]/2 , fg=[200,200,200,255] )
							stim_display.refresh()
					elif response == 'return':
						done = True
					else:
						textInput = textInput + response
						my_text = get_what+textInput
						drawText( my_text , instruction_font , stim_display_res[0] , xLoc=stim_display_res[0]/2 , yLoc=stim_display_res[1]/2 , fg=[200,200,200,255] )
						stim_display.refresh()
		stim_display.refresh()
		return textInput
Ejemplo n.º 23
0
	def drawBackground(self, painter, rect) :

		super(BlobViewScene, self).drawBackground(painter,rect)
		height = float(painter.device().height())
		width = float(painter.device().width())

		painter.beginNativePainting()
		self.setStates()

		GL.glClearColor(0.0, 0.0, 0.0, 0.0)
		GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

		GL.glMatrixMode(GL.GL_PROJECTION)
		GLU.gluPerspective(60.0, width / height, 0.01, 450.0);
		GLU.gluLookAt(-self._distance,0,0,0,0,0,0,0,1);

		GL.glMatrixMode(GL.GL_MODELVIEW);

		view = QtGui.QMatrix4x4()
		view.rotate(self._trackballs[2].rotation())

#		view = np.array(list(view.data())).reshape((4,4))
#		view[2, 3] -= 2.0 * math.exp(self._distance / 1200.0)
#		view = QtGui.QMatrix4x4(*view.reshape((16,)))

		GL.glLoadMatrixf(view.data())
		self.drawAxis()
#		self.drawPoints()
		self.drawSphere()

		self.setDefaultState()
		painter.endNativePainting()
		self._frame+=1
Ejemplo n.º 24
0
    def paintGL(self):
        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

        # Don't load identity matrix. Do all transforms in place against current matrix
        # and take advantage of OpenGL's state-machineness.
        # Sure, you might get round-off error over time, but who cares? If you wanna return
        # to a specific focal point on 'f', that's when you really need to first load the
        # identity matrix before doing the transforms
        #GL.glLoadIdentity() # loads identity matrix into top of matrix stack

        #GLU.gluLookAt() # viewing transform for camera: where placed, where pointed, which way is up
        #GL.glScale() # modelling transformation, lets you stretch your objects

        GL.glEnableClientState(GL.GL_COLOR_ARRAY);
        GL.glEnableClientState(GL.GL_VERTEX_ARRAY);
        GL.glColorPointerub(self.colors) # unsigned byte, ie uint8
        GL.glVertexPointerf(self.points) # float32

        GL.glDrawArrays(GL.GL_POINTS, 0, self.npoints)
        # might consider using buffer objects for even more speed (less unnecessary vertex
        # data from ram to vram, I think). Apparently, buffer objects don't work with
        # color arrays?

        #GL.glFlush() # forces drawing to begin, only makes difference for client-server?
        self.swapBuffers() # doesn't seem to be necessary, even though I'm in double-buffered mode with the back buffer for RGB sid encoding, but do it anyway for completeness
Ejemplo n.º 25
0
  def DrawScreen(self):
    OGL.glClear(OGL.GL_COLOR_BUFFER_BIT | OGL.GL_DEPTH_BUFFER_BIT)	# Clear The Screen And The Depth Buffer
    OGL.glLoadIdentity() # Reset The matrix

    # To calculate our collision detection with the camera, it just takes one function
    # call from the client side.  We just pass in the vertices in the world that we
    # want to check, and then the vertex count.  
    objCamera.CheckCameraCollision(g_vWorld, g_NumberOfVerts)

    # Assign Values to Local Variables to Prevent Long Lines Of Code	
    pos.x, pos.y, pos.z = objCamera.mPos.x, objCamera.mPos.y, objCamera.mPos.z
    view.x, view.y, view.z = objCamera.mView.x, objCamera.mView.y, objCamera.mView.z
    up.x, up.y, up.z = objCamera.mUp.x, objCamera.mUp.y, objCamera.mUp.z

    # use this function for opengl target camera
    OGLU.gluLookAt(pos.x, pos.y, pos.z, view.x, view.y, view.z, up.x, up.y, up.z)

    # Since we have the vertices for the world in the correct order, let's create
    # a loop that goes through all of the vertices and passes them in to be rendered.

    OGL.glBegin(OGL.GL_TRIANGLES)
    # Go through all the vertices and draw them
    for i in range(0,g_NumberOfVerts,3):
      OGL.glColor3ub(i, 2*i, 3*i) # All different colors to see the structure while playing
      OGL.glVertex3f(g_vWorld[i].x, g_vWorld[i].y, g_vWorld[i].z)
      OGL.glVertex3f(g_vWorld[i+1].x, g_vWorld[i+1].y, g_vWorld[i+1].z)
      OGL.glVertex3f(g_vWorld[i+2].x, g_vWorld[i+2].y, g_vWorld[i+2].z)
				
    OGL.glEnd()
Ejemplo n.º 26
0
	def _on_paint(self, event):
		"""
		Respond to paint events.
		Initialize GL if this is the first paint event.
		Resize the view port if the width or height changed.
		Redraw the screen, calling the draw functions.
		"""
		if not self.IsShownOnScreen():	# Cannot realise a GL context on OS X if window is not yet shown
			return
		# create device context (needed on Windows, noop on X)
		dc = None
		if event.GetEventObject():	# Only create DC if paint triggered by WM message (for OS X)
			dc = wx.PaintDC(self)
		self.lock()
		self.SetCurrent(self._gl_ctx)	# Real the explicit GL context

		# check if gl was initialized
		if not self._gl_init_flag:
			GL.glClearColor(*BACKGROUND_COLOR_SPEC)
			for fcn in self._init_fcns: fcn()
			self._gl_init_flag = True

		# check for a change in window size
		if self._resized_flag:
			self.width, self.height = self.GetSize()
			GL.glMatrixMode(GL.GL_PROJECTION)
			GL.glLoadIdentity()
			GL.glOrtho(0, self.width, self.height, 0, 1, 0)
			GL.glMatrixMode(GL.GL_MODELVIEW)
			GL.glLoadIdentity()
			GL.glViewport(0, 0, self.width, self.height)
			for cache in self._gl_caches: cache.changed(True)
			self._resized_flag = False

		# clear buffer if needed
		if self.clear_accum or not self.use_persistence:
			GL.glClear(GL.GL_COLOR_BUFFER_BIT)
			self.clear_accum=False

		# apply fading
		if self.use_persistence:
			GL.glEnable(GL.GL_BLEND)
			GL.glBlendFunc(GL.GL_SRC_ALPHA, GL.GL_ONE_MINUS_SRC_ALPHA)

			GL.glBegin(GL.GL_QUADS)
			GL.glColor4f(1,1,1,self.persist_alpha)
			GL.glVertex2f(0, self.height)
			GL.glVertex2f(self.width, self.height)
			GL.glVertex2f(self.width, 0)
			GL.glVertex2f(0, 0)
			GL.glEnd()

			GL.glDisable(GL.GL_BLEND)

		# draw functions
		for fcn in self._draw_fcns: fcn[1]()

		# show result
		self.SwapBuffers()
		self.unlock()
Ejemplo n.º 27
0
def main_hack():
  pygame.init()
  flags = pygame.OPENGL | pygame.DOUBLEBUF | pygame.HWSURFACE
  screen = pygame.display.set_mode((600, 600), flags)

  Shaders.Setup()

  wpl = WordPictureLoader()
  w = random.choice(wpl.all_words)
  w = 'ox'
  word = wpl.WordPictureForWord(w)
  print w

  glViewport(0, 0, 600, 600)

  clock = pygame.time.Clock()
  t = 0
  while True:
    dt = clock.tick()
    #print clock
    for e in pygame.event.get():
      if e.type == pygame.QUIT:
        return
      if e.type == pygame.KEYDOWN and e.key == pygame.K_ESCAPE:
        return

    t += dt / 1000.
    GL.glClear(GL.GL_COLOR_BUFFER_BIT)
    word.RenderSetup((1, 1, 1, 1), (2.0, 0.3, 0.3, 1.0), 600, 600)
    word.Render(t, -5) # t - 5.0)
    pygame.display.flip()
Ejemplo n.º 28
0
    def display(self):
        now = time.time()
        timedelt = now-self.timestamp
        self.timestamp = now
        self.current_fps = 1.0/timedelt

        hid_js.read_js(self.camera)
        view = self.camera.matrix()

        # updating shared variables in shader data block.  Also see
        # timer()
        self.shader_data_block.map()
        self.shader_data_block.set('u_view', view)
        self.shader_data_block.set("camera_position",
                                   np.array(self.camera.loc,
                                            dtype=np.float32))
        self.light_count += 1
        if self.light_count == 2:
            self.light_count = 0
            self.lights = self.get_lights()
            self.shader_data_block.set("light_diffuse",
                                  np.array(self.lights, dtype=np.float32))
        self.shader_data_block.unmap()

        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)


        for drawable in self.drawables:
            drawable.draw()

        glut.glutSwapBuffers()
Ejemplo n.º 29
0
    def paintEvent(self, event):
        self.makeCurrent()

        GL.glMatrixMode(GL.GL_PROJECTION)
        GL.glPushMatrix()

        GL.glShadeModel(GL.GL_SMOOTH)  # for gradient rendering
        # GL.glDepthFunc(GL.GL_LESS) # The Type Of Depth Test To Do
        GL.glDisable(GL.GL_DEPTH_TEST)  # we do 2D, we need no depth test !
        GL.glMatrixMode(GL.GL_PROJECTION)
        # GL.glEnable(GL.GL_CULL_FACE)

        # Clear The Screen And The Depth Buffer
        GL.glClearColor(1, 1, 1, 0)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)  # | GL.GL_DEPTH_BUFFER_BIT)

        # Reset The View
        self.setupViewport(self.width(), self.height())

        self.drawBackground()
        self.drawGrid()
        self.drawDataQuads()
        self.drawRuler()
        self.drawBorder()

        # revert our changes for cooperation with QPainter
        GL.glShadeModel(GL.GL_FLAT)
        GL.glEnable(GL.GL_DEPTH_TEST)

        GL.glMatrixMode(GL.GL_PROJECTION)
        GL.glPopMatrix()

        painter = QtGui.QPainter(self)
        self.drawTrackerText(painter)
        painter.end()
Ejemplo n.º 30
0
def main_sdl2():
    def pysdl2_init():
        width, height = 1280, 800
        window_name = "Map Edit"
        if SDL_Init(SDL_INIT_EVERYTHING) < 0:
            print("Error: SDL could not initialize! SDL Error: " +
                  SDL_GetError())
            exit(1)
        SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1)
        SDL_GL_SetAttribute(SDL_GL_DEPTH_SIZE, 24)
        SDL_GL_SetAttribute(SDL_GL_STENCIL_SIZE, 8)
        SDL_GL_SetAttribute(SDL_GL_ACCELERATED_VISUAL, 1)
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1)
        SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 16)
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_FLAGS,
                            SDL_GL_CONTEXT_FORWARD_COMPATIBLE_FLAG)
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4)
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1)
        SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK,
                            SDL_GL_CONTEXT_PROFILE_CORE)
        SDL_SetHint(SDL_HINT_MAC_CTRL_CLICK_EMULATE_RIGHT_CLICK, b"1")
        SDL_SetHint(SDL_HINT_VIDEO_HIGHDPI_DISABLED, b"1")
        window = SDL_CreateWindow(window_name.encode('utf-8'),
                                  SDL_WINDOWPOS_CENTERED,
                                  SDL_WINDOWPOS_CENTERED, width, height,
                                  SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE)
        if window is None:
            print("Error: Window could not be created! SDL Error: " +
                  SDL_GetError())
            exit(1)
        gl_context = SDL_GL_CreateContext(window)
        if gl_context is None:
            print("Error: Cannot create OpenGL Context! SDL Error: " +
                  SDL_GetError())
            exit(1)
        SDL_GL_MakeCurrent(window, gl_context)
        if SDL_GL_SetSwapInterval(1) < 0:
            print("Warning: Unable to set VSync! SDL Error: " + SDL_GetError())
            exit(1)
        return window, gl_context

    window, gl_context = pysdl2_init()

    renderer = SDL2Renderer(window)

    running = True

    event = SDL_Event()

    render_3d.init_sdl_window()

    while running:
        while SDL_PollEvent(ctypes.byref(event)) != 0:
            if event.type == SDL_QUIT:
                running = False
                break
            elif event.type == SDL_WINDOWEVENT and event.window.event == SDL_WINDOWEVENT_CLOSE:
                running = False
                break
            renderer.process_event(event)
        renderer.process_inputs()
        imgui.new_frame()
        on_frame()
        gl.glClearColor(1., 1., 1., 1)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        imgui.render()
        renderer.render(imgui.get_draw_data())
        SDL_GL_SwapWindow(window)
    renderer.shutdown()
    SDL_GL_DeleteContext(gl_context)
    SDL_DestroyWindow(window)
    SDL_Quit()
Ejemplo n.º 31
0
def on_display():
    gl.glClearColor(1, 1, 1, 1)
    gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
    paths.draw()
    circles.draw()
    glut.glutSwapBuffers()
def main():
    glfw.init()
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    window = glfw.create_window(800, 600, "LearnOpenGL", None, None)
    if not window:
        print("Window Creation failed!")
        glfw.terminate()

    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, on_resize)

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

    vertices = [
        -0.5,
        -0.5,
        0.0,
        0.5,
        -0.5,
        0.0,
        0.0,
        0.5,
        0.0,
    ]
    vertices = (c_float * len(vertices))(*vertices)

    vao = gl.glGenVertexArrays(1)
    gl.glBindVertexArray(vao)

    vbo = gl.glGenBuffers(1)
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(vertices), vertices,
                    gl.GL_STATIC_DRAW)

    gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE,
                             3 * sizeof(c_float), c_void_p(0))
    gl.glEnableVertexAttribArray(0)

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
    gl.glBindVertexArray(0)

    while not glfw.window_should_close(window):
        process_input(window)

        gl.glClearColor(.2, .3, .3, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        gl.glUseProgram(shader)

        time = glfw.get_time()
        green_val = math.sin(time) / 2.0 + 0.5
        ourColor_location = gl.glGetUniformLocation(shader, "ourColor")
        gl.glUniform4f(ourColor_location, 0.0, green_val, 0.0, 1.0)

        gl.glBindVertexArray(vao)
        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3)

        glfw.poll_events()
        glfw.swap_buffers(window)

    gl.glDeleteVertexArrays(1, id(vao))
    gl.glDeleteBuffers(1, id(vbo))
    glfw.terminate()
Ejemplo n.º 33
0
def main():
    global delta_time, last_frame

    if not glfw.init():
        raise ValueError("Failed to initialize glfw")

    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)

    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    window = glfw.create_window(SRC_WIDTH, SRC_HEIGHT, "learnOpenGL", None,
                                None)
    if not window:
        glfw.terminate()
        raise ValueError("Failed to create window")

    glfw.make_context_current(window)
    glfw.set_framebuffer_size_callback(window, framebuffer_size_callback)
    glfw.set_cursor_pos_callback(window, mouse_callback)
    glfw.set_scroll_callback(window, scroll_callback)

    glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)

    gl.glEnable(gl.GL_DEPTH_TEST)

    lamp_shader = Shader(CURDIR / "shaders/1.lamp.vs",
                         CURDIR / "shaders/1.lamp.fs")
    lighting_shader = Shader(CURDIR / "shaders/3.1.materials.vs",
                             CURDIR / "shaders/3.1.materials.fs")

    vertices = [
        -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.5, -0.5, -0.5, 0.0, 0.0, -1.0, 0.5,
        0.5, -0.5, 0.0, 0.0, -1.0, 0.5, 0.5, -0.5, 0.0, 0.0, -1.0, -0.5, 0.5,
        -0.5, 0.0, 0.0, -1.0, -0.5, -0.5, -0.5, 0.0, 0.0, -1.0, -0.5, -0.5,
        0.5, 0.0, 0.0, 1.0, 0.5, -0.5, 0.5, 0.0, 0.0, 1.0, 0.5, 0.5, 0.5, 0.0,
        0.0, 1.0, 0.5, 0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, 0.0, 0.0, 1.0,
        -0.5, -0.5, 0.5, 0.0, 0.0, 1.0, -0.5, 0.5, 0.5, -1.0, 0.0, 0.0, -0.5,
        0.5, -0.5, -1.0, 0.0, 0.0, -0.5, -0.5, -0.5, -1.0, 0.0, 0.0, -0.5,
        -0.5, -0.5, -1.0, 0.0, 0.0, -0.5, -0.5, 0.5, -1.0, 0.0, 0.0, -0.5, 0.5,
        0.5, -1.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, 0.5, 0.5, -0.5, 1.0,
        0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0, 0.0, 0.5, -0.5, -0.5, 1.0, 0.0,
        0.0, 0.5, -0.5, 0.5, 1.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 0.0, 0.0, -0.5,
        -0.5, -0.5, 0.0, -1.0, 0.0, 0.5, -0.5, -0.5, 0.0, -1.0, 0.0, 0.5, -0.5,
        0.5, 0.0, -1.0, 0.0, 0.5, -0.5, 0.5, 0.0, -1.0, 0.0, -0.5, -0.5, 0.5,
        0.0, -1.0, 0.0, -0.5, -0.5, -0.5, 0.0, -1.0, 0.0, -0.5, 0.5, -0.5, 0.0,
        1.0, 0.0, 0.5, 0.5, -0.5, 0.0, 1.0, 0.0, 0.5, 0.5, 0.5, 0.0, 1.0, 0.0,
        0.5, 0.5, 0.5, 0.0, 1.0, 0.0, -0.5, 0.5, 0.5, 0.0, 1.0, 0.0, -0.5, 0.5,
        -0.5, 0.0, 1.0, 0.0
    ]
    vertices = (c_float * len(vertices))(*vertices)

    cube_vao = gl.glGenVertexArrays(1)
    vbo = gl.glGenBuffers(1)

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, sizeof(vertices), vertices,
                    gl.GL_STATIC_DRAW)

    gl.glBindVertexArray(cube_vao)

    # -- position attribute
    gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE,
                             6 * sizeof(c_float), c_void_p(0))
    gl.glEnableVertexAttribArray(0)
    # -- normal attribute
    gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT,
                             gl.GL_FALSE, 6 * sizeof(c_float),
                             c_void_p(3 * sizeof(c_float)))
    gl.glEnableVertexAttribArray(1)

    # -- second configure light vao (vbo is the same)
    light_vao = gl.glGenVertexArrays(1)
    gl.glBindVertexArray(light_vao)

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, vbo)
    gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE,
                             6 * sizeof(c_float), c_void_p(0))
    gl.glEnableVertexAttribArray(0)

    while not glfw.window_should_close(window):
        # -- time logic
        current_frame = glfw.get_time()
        delta_time = current_frame - last_frame
        last_frame = current_frame

        # -- input
        process_input(window)

        # -- render
        gl.glClearColor(0.1, 0.1, 0.1, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)

        lighting_shader.use()
        lighting_shader.set_vec3("light.position", light_pos)
        lighting_shader.set_vec3("viewPos", camera.position)

        # -- light properties
        light_color = Vector3()
        light_color.x = math.sin(glfw.get_time() * 2.0)
        light_color.y = math.sin(glfw.get_time() * 0.7)
        light_color.z = math.sin(glfw.get_time() * 1.3)

        diffuse_color = light_color * 0.5
        ambient_color = light_color * 0.2
        lighting_shader.set_vec3("light.ambient", ambient_color)
        lighting_shader.set_vec3("light.diffuse", diffuse_color)
        lighting_shader.set_vec3("light.specular", Vector3([1.0, 1.0, 1.0]))

        # -- material properties
        lighting_shader.set_vec3("material.ambient", Vector3([1.0, 0.5, 0.31]))
        lighting_shader.set_vec3("material.diffuse", Vector3([1.0, 0.5, 0.31]))
        lighting_shader.set_vec3("material.specular", Vector3([0.5, 0.5, 0.5]))
        lighting_shader.set_float("material.shininess", 32.0)

        # -- view.projection transformations
        projection = Matrix44.perspective_projection(camera.zoom,
                                                     SRC_WIDTH / SRC_HEIGHT,
                                                     0.1, 100.0)
        view = camera.get_view_matrix()
        lighting_shader.set_mat4("projection", projection)
        lighting_shader.set_mat4("view", view)

        # -- world transformation
        model = Matrix44.identity()
        lighting_shader.set_mat4("model", model)

        # -- render cube
        gl.glBindVertexArray(cube_vao)
        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36)

        # -- draw lamp object
        lamp_shader.use()
        lamp_shader.set_mat4("projection", projection)
        lamp_shader.set_mat4("view", view)

        model = Matrix44.identity()
        model *= Matrix44.from_translation(light_pos)
        model *= Matrix44.from_scale(Vector3([.2, .2, .2]))
        lamp_shader.set_mat4("model", model)

        gl.glBindVertexArray(light_vao)
        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36)

        glfw.swap_buffers(window)
        glfw.poll_events()

    gl.glDeleteVertexArrays(1, id(cube_vao))
    gl.glDeleteVertexArrays(1, id(light_vao))
    gl.glDeleteBuffers(1, id(vbo))
    glfw.terminate()
Ejemplo n.º 34
0
def on_draw():
    global cyl
    gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
    cyl.draw()
    glut.glutSwapBuffers()
Ejemplo n.º 35
0
    def post_render(self):
        """ Dispatch commands to gpu. """

        # Use texture unit 0 - we bind it to a uniform later.
        GL.glActiveTexture(GL.GL_TEXTURE0)

        exposure = 1.0
        gamma = 2.2

        # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
        # Render the scene to the FBO
        with Bind(self.__fbo,
                  self.__anim_shader,
                  TextureUnitBinding(self.__texture_array, GL.GL_TEXTURE0)):

            # Clear the buffer.
            GL.glClear(GL.GL_COLOR_BUFFER_BIT)

            # Set uniform state.
            GL.glUniform1i(self.__anim_shader.get_uniform_location("texture_array"), 0)
            GL.glUniform2f(self.__anim_shader.get_uniform_location("view_position"),
                           *self.__view.position)
            GL.glUniform2f(self.__anim_shader.get_uniform_location("view_size"),
                           *self.__view.size)
            GL.glUniform1f(self.__anim_shader.get_uniform_location("view_zoom"),
                           self.__view.zoom)
            GL.glUniform1f(self.__anim_shader.get_uniform_location("gamma"), gamma)

            # Dispatch commands to the GPU.
            self.__command_buffers.dispatch()

        # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
        # Ping pong gaussian blur the brightness image.
        passes = 2
        with Bind(self.__gaussian_blur_shader,
                  self.__ndc_quad):
            GL.glUniform1i(self.__gaussian_blur_shader.get_uniform_location("image"), 0)

            # The first pass, using the main fbo colour attachment as input.
            with Bind(self.__gaussian_blur_fbo0,
                      self.__fbo.get_texture(GL.GL_COLOR_ATTACHMENT1)):
                GL.glUniform1i(self.__gaussian_blur_shader.get_uniform_location("horizontal"), 0)
                GL.glClear(GL.GL_COLOR_BUFFER_BIT)
                self.__ndc_quad.draw(GL.GL_QUADS)

            # Subsequent passes, do a 'ping pong'.  The result should end up in the second
            # fbo.
            assert passes > 0
            for i in range(1, passes*2+2):
                fbos = (self.__gaussian_blur_fbo0, self.__gaussian_blur_fbo1)
                from_fbo = fbos[(i+1)%2]
                to_fbo = fbos[i%2]
                with Bind(to_fbo, from_fbo.get_texture(GL.GL_COLOR_ATTACHMENT0)):
                    GL.glUniform1i(self.__gaussian_blur_shader.get_uniform_location("horizontal"), i%2)
                    GL.glClear(GL.GL_COLOR_BUFFER_BIT)
                    self.__ndc_quad.draw(GL.GL_QUADS)

        # * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
        # Blend the brightness image with the main framebuffer.
        with Bind(self.__fbo_shader,
                  self.__ndc_quad,
                  TextureUnitBinding(self.__fbo.get_texture(GL.GL_COLOR_ATTACHMENT0), GL.GL_TEXTURE0),
                  TextureUnitBinding(self.__gaussian_blur_fbo1.get_texture(GL.GL_COLOR_ATTACHMENT0),
                                     GL.GL_TEXTURE1)):
            GL.glUniform1f(self.__fbo_shader.get_uniform_location("exposure"), exposure)
            GL.glUniform1f(self.__fbo_shader.get_uniform_location("gamma"), gamma)
            GL.glUniform1i(self.__fbo_shader.get_uniform_location("rendered_scene"), 0)
            GL.glUniform1i(self.__fbo_shader.get_uniform_location("bright_regions"), 1)
            self.__ndc_quad.draw(GL.GL_QUADS)

        # We're not rendering any more.
        self.__view = None
Ejemplo n.º 36
0
    vs[:, 2] *= -1  # TODO
    vts = np.float32(np.float32(vts) * [xsc, ysc])
    ISCV.undistort_points(vs, -float(Kox), -float(Koy), float(dist[0]),
                          float(dist[1]), vs)
    vs = vbo.VBO(vs, usage='GL_STATIC_DRAW_ARB')
    vts = vbo.VBO(vts, usage='GL_STATIC_DRAW_ARB')
    quads = vbo.VBO(quads,
                    target=GL.GL_ELEMENT_ARRAY_BUFFER,
                    usage='GL_STATIC_DRAW_ARB')
    return vs, vts, quads


def quad_render(tid, (vs, vts, quads), scale=1.0):
    # render the movie texture with the x2ds into the texture coords in the buffer
    GL.glClearColor(1, 0, 0, 1)
    GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
    GL.glShadeModel(GL.GL_FLAT)
    GL.glDisable(GL.GL_LIGHTING)
    GL.glEnable(GL.GL_TEXTURE_2D)
    GL.glBindTexture(GL.GL_TEXTURE_2D, tid)
    GL.glMatrixMode(GL.GL_PROJECTION)
    GL.glLoadIdentity()
    GL.glMatrixMode(GL.GL_MODELVIEW)
    GL.glLoadIdentity()
    GLU.gluOrtho2D(-1 / scale, 1 / scale, -1 / scale,
                   1 / scale)  # (-1,-1) at bottom-left
    GL.glEnableClientState(GL.GL_VERTEX_ARRAY)
    vs.bind()
    GL.glVertexPointerf(vs)
    GL.glEnableClientState(GL.GL_TEXTURE_COORD_ARRAY)
    vts.bind()
Ejemplo n.º 37
0
def main():
    if not glfw.init():
        return -1

    if not glfw.init():
        return -1

    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 2)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 1)

    window = glfw.create_window(800, 600, "Oculus Test", None, None)

    if not window:
        glfw.terminate()

    glfw.make_context_current(window)

    glfw.swap_interval(0)

    if failure(initialize()):
        return -1

    if failure(create()):
        shutdown()
        return -1

    hmdInfo = getHmdInfo()

    for eye, fov in enumerate(hmdInfo.defaultEyeFov):
        setEyeRenderFov(eye, fov)

    texSizeLeft = calcEyeBufferSize(EYE_LEFT)
    texSizeRight = calcEyeBufferSize(EYE_RIGHT)

    bufferW = texSizeLeft[0] + texSizeRight[0]
    bufferH = max(texSizeLeft[1], texSizeRight[1])

    createTextureSwapChainGL(TEXTURE_SWAP_CHAIN0, bufferW, bufferH)

    for eye in range(EYE_COUNT):
        setEyeColorTextureSwapChain(eye, TEXTURE_SWAP_CHAIN0)

    eye_w = int(bufferW / 2)
    eye_h = bufferH
    viewports = ((0, 0, eye_w, eye_h), (eye_w, 0, eye_w, eye_h))
    for eye, vp in enumerate(viewports):
        setEyeRenderViewport(eye, vp)

    setHighQuality(True)

    fboId = GL.GLuint()
    GL.glGenFramebuffers(1, ctypes.byref(fboId))
    GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, fboId)
    depthRb_id = GL.GLuint()
    GL.glGenRenderbuffers(1, ctypes.byref(depthRb_id))
    GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, depthRb_id)
    GL.glRenderbufferStorage(GL.GL_RENDERBUFFER, GL.GL_DEPTH24_STENCIL8,
                             int(bufferW),
                             int(bufferH))  # buffer size used here!
    GL.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_DEPTH_ATTACHMENT,
                                 GL.GL_RENDERBUFFER, depthRb_id)
    GL.glFramebufferRenderbuffer(GL.GL_FRAMEBUFFER, GL.GL_STENCIL_ATTACHMENT,
                                 GL.GL_RENDERBUFFER, depthRb_id)
    GL.glBindRenderbuffer(GL.GL_RENDERBUFFER, 0)
    GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0)

    mirrorFbo = GL.GLuint()
    GL.glGenFramebuffers(1, ctypes.byref(mirrorFbo))
    createMirrorTexture(800, 600, mirrorOptions=MIRROR_OPTION_DEFAULT)

    frame_index = 0

    projectionMatrix = []
    for eye in range(EYE_COUNT):
        projectionMatrix.append(getEyeProjectionMatrix(eye))

    planePose = LibOVRPose((0., 0., -2.))

    # begin application loop
    while not glfw.window_should_close(window):
        waitToBeginFrame(frame_index)

        abs_time = getPredictedDisplayTime(frame_index)

        tracking_state = getTrackingState(abs_time, True)

        calcEyePoses(tracking_state.headPose.thePose)

        beginFrame(frame_index)

        GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, fboId)

        _, swapIdx = getTextureSwapChainCurrentIndex(TEXTURE_SWAP_CHAIN0)
        _, tex_id = getTextureSwapChainBufferGL(TEXTURE_SWAP_CHAIN0, swapIdx)

        GL.glFramebufferTexture2D(GL.GL_DRAW_FRAMEBUFFER,
                                  GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D,
                                  tex_id, 0)

        for eye in range(EYE_COUNT):
            vp = getEyeRenderViewport(eye)
            GL.glViewport(*vp)
            GL.glScissor(*vp)

            P = projectionMatrix[eye]
            MV = getEyeViewMatrix(eye)

            GL.glEnable(GL.GL_SCISSOR_TEST)
            GL.glEnable(GL.GL_DEPTH_TEST)
            GL.glMatrixMode(GL.GL_PROJECTION)
            GL.glLoadTransposeMatrixf(P)

            GL.glMatrixMode(GL.GL_MODELVIEW)
            GL.glLoadTransposeMatrixf(MV)

            GL.glClearColor(0.0, 0.0, 0.0, 1.0)
            GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

            GL.glPushMatrix()
            GL.glMultTransposeMatrixf(planePose.modelMatrix)
            GL.glBegin(GL.GL_QUADS)
            GL.glColor3f(1.0, 0.0, 0.0)
            GL.glVertex3f(-1.0, -1.0, 0.0)
            GL.glColor3f(0.0, 1.0, 0.0)
            GL.glVertex3f(-1.0, 1.0, 0.0)
            GL.glColor3f(0.0, 0.0, 1.0)
            GL.glVertex3f(1.0, 1.0, 0.0)
            GL.glColor3f(1.0, 1.0, 1.0)
            GL.glVertex3f(1.0, -1.0, 0.0)
            GL.glEnd()
            GL.glPopMatrix()

        GL.glDisable(GL.GL_DEPTH_TEST)

        commitTextureSwapChain(TEXTURE_SWAP_CHAIN0)

        GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, 0)

        endFrame(frame_index)

        frame_index += 1

        GL.glBindFramebuffer(GL.GL_READ_FRAMEBUFFER, mirrorFbo)
        GL.glBindFramebuffer(GL.GL_DRAW_FRAMEBUFFER, 0)

        _, mirrorId = getMirrorTexture()

        GL.glFramebufferTexture2D(GL.GL_READ_FRAMEBUFFER,
                                  GL.GL_COLOR_ATTACHMENT0, GL.GL_TEXTURE_2D,
                                  mirrorId, 0)

        GL.glViewport(0, 0, 800, 600)
        GL.glScissor(0, 0, 800, 600)
        GL.glClearColor(0.0, 0.0, 0.0, 1.0)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT)
        GL.glBlitFramebuffer(0, 0, 800, 600, 0, 600, 800, 0,
                             GL.GL_COLOR_BUFFER_BIT, GL.GL_NEAREST)

        GL.glBindFramebuffer(GL.GL_FRAMEBUFFER, 0)

        glfw.swap_buffers(window)

        updateInputState(CONTROLLER_TYPE_TOUCH)
        A = getButton(CONTROLLER_TYPE_TOUCH, BUTTON_A, 'falling')
        B = getButton(CONTROLLER_TYPE_TOUCH, BUTTON_B, 'falling')

        if A[0]:
            recenterTrackingOrigin()
        elif B[0]:
            break

        glfw.poll_events()

        _, sessionStatus = getSessionStatus()
        if sessionStatus.shouldQuit:
            break

    destroyMirrorTexture()
    destroyTextureSwapChain(TEXTURE_SWAP_CHAIN0)
    destroy()
    # shutdown()  causes access violation on exit

    return 0
Ejemplo n.º 38
0
    def paintGL(self, p, opt, widget):
        p.beginNativePainting()
        import OpenGL.GL as gl

        ## set clipping viewport
        view = self.getViewBox()
        if view is not None:
            rect = view.mapRectToItem(self, view.boundingRect())
            #gl.glViewport(int(rect.x()), int(rect.y()), int(rect.width()), int(rect.height()))

            #gl.glTranslate(-rect.x(), -rect.y(), 0)

            gl.glEnable(gl.GL_STENCIL_TEST)
            gl.glColorMask(gl.GL_FALSE, gl.GL_FALSE, gl.GL_FALSE,
                           gl.GL_FALSE)  # disable drawing to frame buffer
            gl.glDepthMask(gl.GL_FALSE)  # disable drawing to depth buffer
            gl.glStencilFunc(gl.GL_NEVER, 1, 0xFF)
            gl.glStencilOp(gl.GL_REPLACE, gl.GL_KEEP, gl.GL_KEEP)

            ## draw stencil pattern
            gl.glStencilMask(0xFF)
            gl.glClear(gl.GL_STENCIL_BUFFER_BIT)
            gl.glBegin(gl.GL_TRIANGLES)
            gl.glVertex2f(rect.x(), rect.y())
            gl.glVertex2f(rect.x() + rect.width(), rect.y())
            gl.glVertex2f(rect.x(), rect.y() + rect.height())
            gl.glVertex2f(rect.x() + rect.width(), rect.y() + rect.height())
            gl.glVertex2f(rect.x() + rect.width(), rect.y())
            gl.glVertex2f(rect.x(), rect.y() + rect.height())
            gl.glEnd()

            gl.glColorMask(gl.GL_TRUE, gl.GL_TRUE, gl.GL_TRUE, gl.GL_TRUE)
            gl.glDepthMask(gl.GL_TRUE)
            gl.glStencilMask(0x00)
            gl.glStencilFunc(gl.GL_EQUAL, 1, 0xFF)

        try:
            x, y = self.getData()
            pos = np.empty((len(x), 2))
            pos[:, 0] = x
            pos[:, 1] = y
            gl.glEnableClientState(gl.GL_VERTEX_ARRAY)
            try:
                gl.glVertexPointerf(pos)
                pen = fn.mkPen(self.opts['pen'])
                color = pen.color()
                gl.glColor4f(color.red() / 255.,
                             color.green() / 255.,
                             color.blue() / 255.,
                             color.alpha() / 255.)
                width = pen.width()
                if pen.isCosmetic() and width < 1:
                    width = 1
                gl.glPointSize(width)
                gl.glEnable(gl.GL_LINE_SMOOTH)
                gl.glEnable(gl.GL_BLEND)
                gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)
                gl.glHint(gl.GL_LINE_SMOOTH_HINT, gl.GL_NICEST)
                gl.glDrawArrays(gl.GL_LINE_STRIP, 0, pos.size / pos.shape[-1])
            finally:
                gl.glDisableClientState(gl.GL_VERTEX_ARRAY)
        finally:
            p.endNativePainting()
Ejemplo n.º 39
0
    def view(self):
        pangolin.CreateWindowAndBind('Viewer', 1024, 768)
        gl.glEnable(gl.GL_DEPTH_TEST)
        gl.glEnable(gl.GL_BLEND)
        gl.glBlendFunc(gl.GL_SRC_ALPHA, gl.GL_ONE_MINUS_SRC_ALPHA)

        viewpoint_x = 0
        viewpoint_y = -7
        viewpoint_z = -18
        viewpoint_f = 1000

        proj = pangolin.ProjectionMatrix(1024, 768, viewpoint_f, viewpoint_f,
                                         512, 389, 0.1, 300)
        look_view = pangolin.ModelViewLookAt(viewpoint_x, viewpoint_y,
                                             viewpoint_z, 0, 0, 0, 0, -1, 0)

        # Camera Render Object (for view / scene browsing)
        scam = pangolin.OpenGlRenderState(proj, look_view)

        # Add named OpenGL viewport to window and provide 3D Handler
        dcam = pangolin.CreateDisplay()
        dcam.SetBounds(0.0, 1.0, 175 / 1024., 1.0, -1024 / 768.)
        dcam.SetHandler(pangolin.Handler3D(scam))

        # image
        width, height = 376, 240
        dimg = pangolin.Display('image')
        dimg.SetBounds(0, height / 768., 0.0, width / 1024., 1024 / 768.)
        dimg.SetLock(pangolin.Lock.LockLeft, pangolin.Lock.LockTop)

        texture = pangolin.GlTexture(width, height, gl.GL_RGB, False, 0,
                                     gl.GL_RGB, gl.GL_UNSIGNED_BYTE)
        image = np.ones((height, width, 3), 'uint8')

        # axis
        axis = pangolin.Renderable()
        axis.Add(pangolin.Axis())

        trajectory = DynamicArray()
        camera = None
        image = None

        while not pangolin.ShouldQuit():
            if not self.pose_queue.empty():
                while not self.pose_queue.empty():
                    pose = self.pose_queue.get()
                trajectory.append(pose[:3, 3])
                camera = pose.T

            if not self.image_queue.empty():
                while not self.image_queue.empty():
                    img = self.image_queue.get()
                img = img[::-1, :, ::-1]
                img = cv2.resize(img, (width, height))
                image = img.copy()

            gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
            gl.glClearColor(1.0, 1.0, 1.0, 1.0)
            dcam.Activate(scam)

            # draw axis
            axis.Render()

            # draw current camera
            if camera is not None:
                gl.glLineWidth(1)
                gl.glColor3f(0.0, 0.0, 1.0)
                pangolin.DrawCameras(np.array([camera]), 0.5)

            # show trajectory
            if len(trajectory) > 0:
                gl.glPointSize(2)
                gl.glColor3f(0.0, 0.0, 0.0)
                pangolin.DrawPoints(trajectory.array())

            # show image
            if image is not None:
                texture.Upload(image, gl.GL_RGB, gl.GL_UNSIGNED_BYTE)
                dimg.Activate()
                gl.glColor3f(1.0, 1.0, 1.0)
                texture.RenderToViewport()

            pangolin.FinishFrame()
Ejemplo n.º 40
0
def display():
    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
    gl.glDrawArrays(gl.GL_TRIANGLE_STRIP, 0, 4)
    glut.glutSwapBuffers()
Ejemplo n.º 41
-1
 def paintGL(self):
     GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
     
     GL.glPushMatrix()
     GL.glLoadIdentity()
     GLU.gluLookAt(self.camera.eye.x, self.camera.eye.y, self.camera.eye.z,
         self.camera.at.x , self.camera.at.y, self.camera.at.z ,
         self.camera.up.x , self.camera.up.y, self.camera.up.z)
     
     GL.glLightfv(GL.GL_LIGHT0, GL.GL_POSITION, (GL.GLfloat *4) ( self.camera.eye.x, self.camera.eye.y, self.camera.eye.z, 1 ))
     
     if self.wireframe:
         GL.glDisable(GL.GL_LIGHTING)
         GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_LINE)
         GL.glColor3f(0, 1, 0)
     else:
         GL.glEnable(GL.GL_LIGHTING)
         GL.glPolygonMode(GL.GL_FRONT_AND_BACK, GL.GL_FILL)
         GL.glMaterialfv(GL.GL_FRONT_AND_BACK, GL.GL_DIFFUSE, (GL.GLfloat * 4) ( 1, 1, 1, 1 ))
         
     if self.display_object:
         self.display_object.draw()
     
     GL.glDisable(GL.GL_LIGHTING)
     if self.grid:
         glutils.draw_grid()
         
     if self.frameRef:
         glutils.draw_frame()
     GL.glEnable(GL.GL_LIGHTING)
     
     GL.glPopMatrix()