Esempio n. 1
0
def main():
    global angles, angley, anglez, scale, carcass, sphere
    if not glfw.init():
        return
    window = glfw.create_window(640, 640, "Lab2", None, None)
    if not window:
        glfw.terminate()
        return
    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    glfw.set_framebuffer_size_callback(window, resize_callback)
    glfw.set_window_pos_callback(window, drag_callback)
    l_cube = Cube(0, 0, 0, 1)
    # r_cube = Cube(0, 0, 0, 1)
    sphere.recount(parts)
    while not glfw.window_should_close(window):
        glEnable(GL_DEPTH_TEST)
        glDepthFunc(GL_LESS)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        set_projection()
        glLoadIdentity()
        sphere.draw(scale, angles, [0.3, 0.0, 0.4], carcass)
        # r_cube.draw(scale, angles, [0.3, 0.2, 0.4], carcass)
        l_cube.draw(0.5, [0, 0, 0], [-0.5, 0.0, -0.25], False)
        glfw.swap_buffers(window)
        glfw.poll_events()
    glfw.destroy_window(window)
    glfw.terminate()
Esempio n. 2
0
def main():
    if not glfw.init():
        return
    window = glfw.create_window(640, 480, "ラララ", None, None)
    if not window:
        glfw.terminate()
        return

    #init
    glfw.make_context_current(window)
    gluOrtho2D(0.0, 640, 0.0, 480) #where is this in glfw?

    # loop
    while not glfw.window_should_close(window):

        glClear(GL_COLOR_BUFFER_BIT)
        randomWidth()
    
        drawLine(100.0, 400.0, 200.0, 400.0)
        drawLine(440.0, 400.0, 540.0, 400.0)
        drawLine(320.0, 350.0, 320.0, 330.0)
        drawLine(100.0, 400.0, 200.0, 400.0)
        drawLine(300.0, 200.0, 340.0, 200.0)
        
        glfw.swap_buffers(window)
        glfw.poll_events()
        glfw.swap_interval(2)
    glfw.terminate()
Esempio n. 3
0
File: main.py Progetto: Tofs/Pygel
def main():
    global window
    initLogger()
    Utils.init()

    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(640, 480, "Hello World", None, None)
    if not window:
        glfw.terminate()
        print("fail Window")
        return
    # Make the window's context current
    glfw.make_context_current(window)

    vertexPos, vertexColor, triangle = tmf.load("testData.tmf")

    #define input
    inputHandler.addEvent(KillProgram, "Esc")
    inputHandler.addEvent(Culling, "c")

    print vertexPos
    VAO, VertexSize, indexs = Utils.createVAO(vertexPos, vertexColor, triangle, 4)
    shaderProgram = ShaderM.compileShaderFromFile("shaders/basic.vert", "shaders/basic.frag")

    objectToRender = { "Indexs" : indexs, "VAO" : VAO, "VertexCount" : VertexSize, "ShaderProgram" : shaderProgram}

    mainLoop(objectToRender,window)
    glfw.terminate()
Esempio n. 4
0
def main():
    global R, T
    if not glfw.init(): return
    window = glfw.create_window(480, 480, "2015004584", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.set_key_callback(window, key_callback)
    glfw.make_context_current(window)
    glfw.swap_interval(0)

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

        clear()
        axis()

        glMultMatrixf(R.T)
        glMultMatrixf(T.T)
        render()

        glfw.swap_buffers(window)

    glfw.terminate()
Esempio n. 5
0
    def init(self):
        if not glfw.init():
            raise Exception('glfw failed to initialize')

        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 2)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL.GL_TRUE)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

        self.window = glfw.create_window(
            self.initial_width, self.initial_height,
            self.title, None, None
        )
        if not self.window:
            glfw.terminate()
            raise Exception('glfw failed to create a window')

        glfw.make_context_current(self.window)
        glfw.set_framebuffer_size_callback(self.window, self._reshape_callback)
        glfw.set_key_callback(self.window, self._key_callback)
        glfw.set_mouse_button_callback(self.window, self._mouse_button_callback)

        GL.glEnable(GL.GL_CULL_FACE)
        GL.glCullFace(GL.GL_BACK)
        GL.glFrontFace(GL.GL_CW)

        GL.glEnable(GL.GL_DEPTH_TEST)
        GL.glDepthMask(GL.GL_TRUE)
        GL.glDepthFunc(GL.GL_LEQUAL)
        GL.glDepthRange(0.0, 1.0)
        GL.glEnable(depth_clamp.GL_DEPTH_CLAMP)
Esempio n. 6
0
def main():
	# Initialize the library
	if not glfw.init():
		return
	
	glfw.set_error_callback(error_callback)

	# Create a windowed mode window and its OpenGL context
	window = glfw.create_window(640, 480, "Hello World", None, None)
	if not window:
		glfw.terminate()
		return

	# Make the window's context current
	glfw.make_context_current(window)

	program = common2d.init_shader_program()

	# Loop until the user closes the window
	while not glfw.window_should_close(window):
		# Render here
		common2d.display(program)

		# Swap front and back buffers
		glfw.swap_buffers(window)

		# Poll for and process events
		glfw.poll_events()

	glfw.terminate()
Esempio n. 7
0
def main():
    global vertices, window_height, window_width, to_redraw

    if not glfw.init():
        return

    window = glfw.create_window(400, 400, "Lab4", None, None)
    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    glfw.set_framebuffer_size_callback(window, resize_callback)

    glfw.set_mouse_button_callback(window, mouse_button_callback)
    glEnable(GL_DEPTH_TEST)
    glDepthFunc(GL_LESS)
    glClearColor(0, 0, 0, 0)

    while not glfw.window_should_close(window):
        # print(vertices)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        draw()

        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.destroy_window(window)
    glfw.terminate()
Esempio n. 8
0
 def dispose_gl(self):
     if self.window is not None:
         glfw.make_context_current(self.window)
         if self.renderer is not None:
             self.renderer.dispose_gl()
     glfw.terminate()
     self._is_initialized = False
def main():
    init()

    window = create_window(500, 500, "Hi", None, None)
    make_context_current(window)
    initial_setup()
    colors = {
        "front": (1, 0, 0),
        "back": (0, 1, 0),
        "left": (1, 1, 0),
        "right": (1, 0, 1),
        "up": (0, 0, 1),
        "down": (0, 1, 1),
    }
    glClearColor(1, 1, 1, 1)
    glEnable(GL_DEPTH_TEST)
    set_lightning()
    while not window_should_close(window):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glRotate(1, 0, 1, 0)
        draw_cube(0, 0, 0, 5, colors)
        swap_buffers(window)
        poll_events()

    terminate()
Esempio n. 10
0
    def __init__(self):

        self.dir = Dir.empty
        self.run = True
        self.snake = Player()

        if not glfw.init():
            return
        self.window = glfw.create_window(400, 300, "Hello, World!", None, None)
        if not self.window:
            glfw.terminate()
            return
        glfw.make_context_current(self.window)
        glfw.set_key_callback(self.window, self.key_callback)

        while self.run and not glfw.window_should_close(self.window):

            # Update player's position
            self.snake.play(self.dir)
            sleep(0.075)

            self.draw()
            glfw.swap_buffers(self.window)
            glfw.poll_events()

            if self.snake.alive is False:
                sleep(1.075)
                self.run = False
                
        glfw.terminate()
Esempio n. 11
0
def opengl_init():
	global window
	# Initialize the library
	if not glfw.init():
		print("Failed to initialize GLFW\n",file=sys.stderr)
		return False

	glfw.window_hint(glfw.SAMPLES, 4)
	glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
	glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
	glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
	glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

	# Open Window and create its OpenGL context
	window = glfw.create_window(1024, 768, "Tutorial 04", None, None) #(in the accompanying source code this variable will be global)

	if not window:
		print("Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n",file=sys.stderr)
		glfw.terminate()
		return False

	# Initialize GLEW
	glfw.make_context_current(window)
	glewExperimental = True

	# GLEW is a framework for testing extension availability.  Please see tutorial notes for
	# more information including why can remove this code.
	if glewInit() != GLEW_OK:
		print("Failed to initialize GLEW\n",file=sys.stderr);
		return False
	return True
Esempio n. 12
0
def main():
    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(window_width, window_height, "Hello World", None, None)
    if not window:
        glfw.terminate()
        return

    # Make the window's context current
    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, on_window_size)

    initGL(window)
    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Render here, e.g. using pyOpenGL
        display()

        # Swap front and back buffers
        glfw.swap_buffers(window)

        # Poll for and process events
        glfw.poll_events()

    glfw.terminate()
Esempio n. 13
0
    def __init__(self, objects=[], options={}):
        super().__init__()

        self.parseOptions(options)

        self.cameraCursor = [0.0, 0.0]
        self.cameraMove = False
        self.cameraRotate = False
        self.redisplay = True
        self.titleText = 'OpenGL 4.1 render'

        glfw.init()

        try:
            self.window = glfw.create_window(*self.viewport, self.titleText, None, None)
            glfw.make_context_current(self.window)
        except:
            print('Window initialization failed')
            glfw.terminate()
            exit()

        self.initGraphics()
        self.updateMatrix(self.viewport)

        glfw.set_key_callback(self.window, self.handleKeyEvent)
        glfw.set_mouse_button_callback(self.window, self.handleMouseButtonEvent)
        glfw.set_cursor_pos_callback(self.window, self.handleCursorMoveEvent)
        glfw.set_scroll_callback(self.window, self.handleScrollEvent)
        glfw.set_window_refresh_callback(self.window, self.handleResizeEvent)

        self.objects = set()
        self.appendRenderObjects(self.makeRenderObjects(objects))
Esempio n. 14
0
 def run(self):
     # Initialize the library
     if not glfw.init():
         return
     # Create a windowed mode window and its OpenGL context
     self.window = glfw.create_window(640, 480, "Hello World", None, None)
     if not self.window:
         glfw.terminate()
         return
 
     renderer = RiftGLRendererCompatibility()
     # Paint a triangle in the center of the screen
     renderer.append(TriangleDrawerCompatibility())
 
     # Make the window's context current
     glfw.make_context_current(self.window)
 
     # Initialize Oculus Rift
     renderer.init_gl()
     renderer.rift.recenter_pose()
     
     glfw.set_key_callback(self.window, self.key_callback)
 
     # Loop until the user closes the window
     while not glfw.window_should_close(self.window):
         # Render here, e.g. using pyOpenGL
         renderer.display_rift_gl()
 
         # Swap front and back buffers
         glfw.swap_buffers(self.window)
 
         # Poll for and process events
         glfw.poll_events()
 
     glfw.terminate()
Esempio n. 15
0
 def init_gl(self):
     if self._is_initialized:
         return # only initialize once
     glfw.make_context_current(self.window)
     if self.renderer is not None:
         self.renderer.init_gl()
     self._is_initialized = True
Esempio n. 16
0
def opengl_init():
	global window
	# Initialize the library
	if not glfw.init():
		print("Failed to initialize GLFW\n",file=sys.stderr)
		return False

	# Open Window and create its OpenGL context
	window = glfw.create_window(1024, 768, "VAO Test", None, None) #(in the accompanying source code this variable will be global)
	glfw.window_hint(glfw.SAMPLES, 4)
	glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
	glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
	glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
	glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

	if not window:
		print("Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n",file=sys.stderr)
		glfw.terminate()
		return False

	# Initialize GLEW
	glfw.make_context_current(window)
	glewExperimental = True


	# !!NOTE: The most recent GLEW package for python is 8 years old, ARB functionality
	# is available in Pyopengl natively.

	if glewInit() != GLEW_OK:
	 	print("Failed to initialize GLEW\n",file=sys.stderr);
	 	return False
	return True
Esempio n. 17
0
    def __init__(self, width=640, height=480, fullscreen=False, aspect=None):
        self.gl = gl
        if not glfw.init():
            raise Exception("GLFW init failed")

        glfw.window_hint(glfw.CLIENT_API, glfw.OPENGL_ES_API)
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 2)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 0)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 0)
        glfw.window_hint(glfw.DOUBLEBUFFER, True)
        glfw.window_hint(glfw.DEPTH_BITS, 24)
        glfw.window_hint(glfw.ALPHA_BITS, 0)
        if platform.system() == "Linux":
            try:
                glfw.window_hint(GLFW_CONTEXT_CREATION_API, GLFW_EGL_CONTEXT_API)
            except:
                pass

        monitor = glfw.get_primary_monitor() if fullscreen else None
        self.window = glfw.create_window(width, height, "BlitzLoop Karaoke",
                                         monitor, None)
        self.x = 0
        self.y = 0
        glfw.make_context_current(self.window)
        BaseDisplay.__init__(self, width, height, fullscreen, aspect)
        self._on_reshape(self.window, width, height)
        if fullscreen:
            self.saved_size = (0, 0, width, height)
            glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_HIDDEN)

        glfw.set_key_callback(self.window, self._on_keyboard)
        glfw.set_window_pos_callback(self.window, self._on_move)
        glfw.set_window_size_callback(self.window, self._on_reshape)

        self._initialize()
Esempio n. 18
0
 def on_resize(self, window, w, h):
     active_window = glfw.get_current_context()
     glfw.make_context_current(window)
     # norm_size = normalize((w,h),glfwGetWindowSize(window))
     # fb_size = denormalize(norm_size,glfwGetFramebufferSize(window))
     self.adjust_gl_view(w, h, window)
     glfw.make_context_current(active_window)
     self.width, self.height = w, h
Esempio n. 19
0
 def init(this):
     if not glfw.init():
         return
     this.windowID = glfw.create_window(640, 480, "Test", None, None)
     glfw.show_window(this.windowID)
     glfw.make_context_current(this.windowID)
     glfw.swap_interval(1)
     glClearColor(0, 0, 0, 1);
Esempio n. 20
0
def draw_a_triangle():
    
    if not glfw.init():
        return -1;
    # Create a windowed mode window and its OpenGL context
    
    glfw.window_hint(glfw.SAMPLES, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    window = glfw.create_window(1024, 768, "Triangle", None, None);
    if window == None:
        glfw.terminate()
        return -1
    # Make the window's context current
    
    glfw.make_context_current(window)
#     glfw.Experimental = True
    glClearColor(0.0, 0.1, 0.2, 1.0)
    
    flatten = lambda l: [u for t in l for u in t]
    vertices = [(-1.0, -1.0, 0.0),
                (1.0, -1.0, 0.0),
                (0.0, 1.0, 0.0)]
    indices = range(3)
    vao_handle = glGenVertexArrays(1)
    glBindVertexArray(vao_handle)
    program_handle = tools.load_program("../shader/simple.v.glsl",
                                        "../shader/simple.f.glsl")
    
    f_vertices = flatten(vertices)
    c_vertices = (c_float*len(f_vertices))(*f_vertices)
    v_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, v_buffer)
    glBufferData(GL_ARRAY_BUFFER, c_vertices, GL_STATIC_DRAW)
    glEnableVertexAttribArray(0)
    glBindBuffer(GL_ARRAY_BUFFER, v_buffer)
    glVertexAttribPointer(0,
        #glGetAttribLocation(program_handle, "vertexPosition_modelspace"),
        3, GL_FLOAT, False, 0, None)
    
    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Render here
        glClear(GL_COLOR_BUFFER_BIT)
        glUseProgram(program_handle)
        
        glDrawArrays(GL_TRIANGLES, 0, 3)
        glDisableVertexAttribArray(vao_handle)
        
        # Swap front and back buffers 
        glfw.swap_buffers(window)
        # Poll for and process events
        glfw.poll_events()
    glfw.terminate();
    
    pass
Esempio n. 21
0
def show(molecule, width=500, height=500,
         show_bonds=True, bonds_method='radii', bonds_param=None,
         camera=None, title='mogli'):
    """
    Interactively show the given molecule with OpenGL. By default, bonds are
    drawn, if this is undesired the show_bonds parameter can be set to False.
    For information on the bond calculation, see Molecule.calculate_bonds.
    If you pass a tuple of camera position, center of view and an up vector to
    the camera parameter, the camera will be set accordingly. Otherwise the
    molecule will be viewed in the direction of the z axis, with the y axis
    pointing upward.
    """
    global _camera
    molecule.positions -= np.mean(molecule.positions, axis=0)
    max_atom_distance = np.max(la.norm(molecule.positions, axis=1))
    if show_bonds:
        molecule.calculate_bonds(bonds_method, bonds_param)

    # If GR3 was initialized earlier, it would use a different context, so
    # it will be terminated first.
    gr3.terminate()

    # Initialize GLFW and create an OpenGL context
    glfw.init()
    glfw.window_hint(glfw.SAMPLES, 16)
    window = glfw.create_window(width, height, title, None, None)
    glfw.make_context_current(window)
    glEnable(GL_MULTISAMPLE)

    # Set up the camera (it will be changed during mouse rotation)
    if camera is None:
        camera_distance = -max_atom_distance*2.5
        camera = ((0, 0, camera_distance),
                  (0, 0, 0),
                  (0, 1, 0))
    camera = np.array(camera)
    _camera = camera

    # Create the GR3 scene
    gr3.setbackgroundcolor(255, 255, 255, 0)
    _create_gr3_scene(molecule, show_bonds)
    # Configure GLFW
    glfw.set_cursor_pos_callback(window, _mouse_move_callback)
    glfw.set_mouse_button_callback(window, _mouse_click_callback)
    glfw.swap_interval(1)
    # Start the GLFW main loop
    while not glfw.window_should_close(window):
        glfw.poll_events()
        width, height = glfw.get_window_size(window)
        glViewport(0, 0, width, height)
        _set_gr3_camera()
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        gr3.drawimage(0, width, 0, height,
                      width, height, gr3.GR3_Drawable.GR3_DRAWABLE_OPENGL)
        glfw.swap_buffers(window)
    glfw.terminate()
    gr3.terminate()
Esempio n. 22
0
 def render_scene(self):
     "render scene one time"
     self.init_gl() # should be a no-op after the first frame is rendered
     glfw.make_context_current(self.window)
     self.renderer.render_scene()
     # Done rendering
     # glfw.swap_buffers(self.window) # avoid double buffering to avoid stalling
     glFlush() # single buffering
     glfw.poll_events()
Esempio n. 23
0
 def initGL(self):
     if not glfw.init():
         sys.exit(1)
     self.window = glfw.create_window(640, 480, "Hello", None, None)
     print self.window
     glfw.make_context_current(self.window)
     glfw.swap_interval(1)
     glfw.set_key_callback(self.window, self.key_callback)
     glClearColor(0.5, 0.5, 0.5, 1)
Esempio n. 24
0
def main():
    # Initialize the library
    if not glfw.init():
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(640, 480, "Hello World", None, None)
    if not window:
        glfw.terminate()
        return

    # Make the window's context current
    glfw.make_context_current(window)

    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Render here, e.g. using pyOpenGL

        # Swap front and back buffers
        glfw.swap_buffers(window)
        
        gl_begin( GL_TRIANGLES )
        glColor3f( 1.0, 0.0, 0.0 )
        glVertex3f( 0.0, 1.0, 0.0 )
        glColor3f( 0.0, 1.0, 0.0 ) 
        glVertex3f( -1.0, -1.0, 1.0 )
        glColor3f( 0.0, 0.0, 1.0 ) 
        glVertex3f( 1.0, -1.0, 1.0)
        
        glColor3f( 1.0, 0.0, 0.0 ) 
        glVertex3f( 0.0, 1.0, 0.0)
        glColor3f( 0.0, 1.0, 0.0 ) 
        glVertex3f( -1.0, -1.0, 1.0)
        glColor3f( 0.0, 0.0, 1.0 )
        glVertex3f( 0.0, -1.0, -1.0)
        
        #glColor3f( 1.0f, 0.0f, 0.0f ) 
        #glVertex3f( 0.0f, 1.0f, 0.0f)
        #glColor3f( 0.0f, 1.0f, 0.0f ) 
        #glVertex3f( 0.0f, -1.0f, -1.0f)
        #glColor3f( 0.0f, 0.0f, 1.0f ) 
        #glVertex3f( 1.0f, -1.0f, 1.0f)
        
        
        #glColor3f( 1.0f, 0.0f, 0.0f )
        #glVertex3f( -1.0f, -1.0f, 1.0f)
        #glColor3f( 0.0f, 1.0f, 0.0f )
        #glVertex3f( 0.0f, -1.0f, -1.0f)
        #glColor3f( 0.0f, 0.0f, 1.0f )
        #glVertex3f( 1.0f, -1.0f, 1.0f)
        
        glEnd()

        # Poll for and process events
        glfw.poll_events()

    glfw.terminate()
Esempio n. 25
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

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

        # Configure the OpenGL context
        glfw.window_hint(glfw.CONTEXT_CREATION_API, glfw.NATIVE_CONTEXT_API)
        glfw.window_hint(glfw.CLIENT_API, glfw.OPENGL_API)
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, self.gl_version[0])
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, self.gl_version[1])
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
        glfw.window_hint(glfw.RESIZABLE, self.resizable)
        glfw.window_hint(glfw.DOUBLEBUFFER, True)
        glfw.window_hint(glfw.DEPTH_BITS, 24)
        glfw.window_hint(glfw.SAMPLES, self.samples)

        monitor = None
        if self.fullscreen:
            # Use the primary monitors current resolution
            monitor = glfw.get_primary_monitor()
            mode = glfw.get_video_mode(monitor)
            self.width, self.height = mode.size.width, mode.size.height

            # Make sure video mode switching will not happen by
            # matching the desktops current video mode
            glfw.window_hint(glfw.RED_BITS, mode.bits.red)
            glfw.window_hint(glfw.GREEN_BITS, mode.bits.green)
            glfw.window_hint(glfw.BLUE_BITS, mode.bits.blue)
            glfw.window_hint(glfw.REFRESH_RATE, mode.refresh_rate)

        self.window = glfw.create_window(self.width, self.height, self.title, monitor, None)

        if not self.window:
            glfw.terminate()
            raise ValueError("Failed to create window")

        if not self.cursor:
            glfw.set_input_mode(self.window, glfw.CURSOR, glfw.CURSOR_DISABLED)

        self.buffer_width, self.buffer_height = glfw.get_framebuffer_size(self.window)
        glfw.make_context_current(self.window)

        if self.vsync:
            glfw.swap_interval(1)

        glfw.set_key_callback(self.window, self.key_event_callback)
        glfw.set_cursor_pos_callback(self.window, self.mouse_event_callback)
        glfw.set_mouse_button_callback(self.window, self.mouse_button_callback)
        glfw.set_window_size_callback(self.window, self.window_resize_callback)

        self.ctx = moderngl.create_context(require=self.gl_version_code)
        self.print_context_info()
        self.set_default_viewport()
Esempio n. 26
0
    def start(self):
        if not glfw.init():
            return

        glfw.window_hint(glfw.SAMPLES, 4)

        # try stereo if refresh rate is at least 100Hz
        window = None
        stereo_available = False

        _, _, refresh_rate = glfw.get_video_mode(glfw.get_primary_monitor())
        if refresh_rate >= 100:
            glfw.window_hint(glfw.STEREO, 1)
            window = glfw.create_window(500, 500, "Simulate", None, None)
            if window:
                stereo_available = True

        # no stereo: try mono
        if not window:
            glfw.window_hint(glfw.STEREO, 0)
            window = glfw.create_window(500, 500, "Simulate", None, None)

        if not window:
            glfw.terminate()
            return

        self.running = True

        # Make the window's context current
        glfw.make_context_current(window)

        width, height = glfw.get_framebuffer_size(window)
        width1, height = glfw.get_window_size(window)
        self._scale = width * 1.0 / width1

        self.window = window

        mjlib.mjv_makeObjects(byref(self.objects), 1000)

        mjlib.mjv_defaultCamera(byref(self.cam))
        mjlib.mjv_defaultOption(byref(self.vopt))
        mjlib.mjr_defaultOption(byref(self.ropt))

        mjlib.mjr_defaultContext(byref(self.con))

        if self.model:
            mjlib.mjr_makeContext(self.model.ptr, byref(self.con), 150)
            self.autoscale()
        else:
            mjlib.mjr_makeContext(None, byref(self.con), 150)

        glfw.set_cursor_pos_callback(window, self.handle_mouse_move)
        glfw.set_mouse_button_callback(window, self.handle_mouse_button)
        glfw.set_scroll_callback(window, self.handle_scroll)
Esempio n. 27
0
 def __init__(self, name, width, height, fullscreen=False):
     if not glfw.init():
         raise GlfwError("Could not initialize GLFW")
     monitor = glfw.get_primary_monitor() if fullscreen else None
     self.win = glfw.create_window(width, height, name, monitor, None)
     if not self.win:
         glfw.terminate()
         raise GlfwError("Could not create GLFW window")
     glfw.make_context_current(self.win)
     glfw.set_key_callback(self.win, self.key_cb)
     self.key_callbacks = []
Esempio n. 28
0
File: 003-ebo.py Progetto: lhl/vrdev
def main():
    # Initialize the library
    if not glfw.init():
        return

    # Set some window hints
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3);
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3);
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL.GL_TRUE);
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE);
    glfw.window_hint(glfw.SAMPLES, 16)

    # This works as expected
    glfw.window_hint(glfw.RESIZABLE, 0)

    # These should work, but don't :(
    # could control focus w/ http://crunchbang.org/forums/viewtopic.php?id=22226
    # ended up using xdotool, see run.py
    glfw.window_hint(glfw.FOCUSED, 0)

    # I've set 'shader-*' to raise in openbox-rc as workaround
    # Looking at the code and confirming version 3.1.2 and it should work
    glfw.window_hint(glfw.FLOATING, 1)

    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(300, 300, "shader-test", None, None)
    if not window:
        glfw.terminate()
        return

    # Move Window
    glfw.set_window_pos(window, 1600, 50)

    # Make the window's context current
    glfw.make_context_current(window)

    # vsync
    glfw.swap_interval(1)

    # Setup GL shaders, data, etc.
    initialize()

    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Render here, e.g. using pyOpenGL
        render()

        # Swap front and back buffers
        glfw.swap_buffers(window)

        # Poll for and process events
        glfw.poll_events()

    glfw.terminate()
Esempio n. 29
0
 def __init__(self, width=800, height=600, title="aiv"):
     glfw.init()
     glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
     glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
     glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, 1)
     glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
     self.window = glfw.create_window(width, height, title, None, None)
     glfw.make_context_current(self.window)
     glfw.swap_interval(1)
     self.time = glfw.get_time()
     self.delta_time = 0
     self.aspect_ratio = float(width) / float(height)
Esempio n. 30
0
    def run(self):
        glfw.make_context_current(self._wnd)
        self._ctx = ModernGL.create_context()

        self.initialize(self._ctx)

        while not glfw.window_should_close(self._wnd):
            width, height = self.size()
            self._ctx.viewport = (0, 0, width, height)
            self.render(self._ctx)
            glfw.swap_buffers(self._wnd)
            glfw.wait_events()
Esempio n. 31
0
def main():
    global rotation_angle
    global d_x

    # Initialize the library
    if not glfw.init():
        print("library is not initialized")
        return
    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(640, 480, "Hello World", None, None)
    if not window:
        glfw.terminate()
        return

    # Make the window's context current
    glfw.make_context_current(window)

    print(glfw.__version__)

    glfw.set_key_callback(window, on_key)
    #glfw.set_mouse_button_callback(window, on_mouse)
    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Render here, e.g. using pyOpenGL

        width, height = glfw.get_framebuffer_size(window)
        ratio = width / float(height)

        rotation_angle += 0.1

        # Set viewport
        gl.glViewport(0, 0, width, height)
        # Clear color buffer
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        # Select and setup the projection matrix
        gl.glMatrixMode(gl.GL_PROJECTION)
        gl.glLoadIdentity()
        gl.glOrtho(-ratio, ratio, -1, 1, 1, -1)

        # Select and setup the modelview matrix
        gl.glMatrixMode(gl.GL_MODELVIEW)
        gl.glLoadIdentity()
        gl.glRotatef(rotation_angle, 0, 0, 1)
        gl.glBegin(gl.GL_POLYGON)
        gl.glColor3f(color.red, color.green, color.blue)
        gl.glVertex3f(-0.5 + d_x, -0.5, 0)
        gl.glColor3f(color.red, color.green, color.blue)
        gl.glVertex3f(-0.5 + d_x, +0.5, 0)
        gl.glColor3f(color.red, color.green, color.blue)
        gl.glVertex3f(0.5 + d_x, +0.5, 0)
        gl.glColor3f(color.red, color.green, color.blue)
        gl.glVertex3f(0.5 + d_x, -0.5, 0)
        gl.glEnd()

        # Swap front and back buffers
        glfw.swap_buffers(window)

        # Poll for and process events
        glfw.poll_events()

    # terminating the whole proccess
    glfw.destroy_window(window)
    glfw.terminate()
Esempio n. 32
0
def main():
    # initialize glfw
    if not glfw.init():
        return

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

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    vertices = [-0.5, -0.5, 0.0, 0.5, -0.5, 0.0, 0.0, 0.5, 0.0]
    vertices = np.array(vertices, dtype=np.float32)

    vertex_shader = """
    #version 330 core
    layout (location = 0) in vec3 aPos;
    
    void main()
    {
        gl_Position = vec4(aPos.x, aPos.y, aPos.z, 1.0);
    }
    """

    fragment_shader = """
    #version 330 core
    out vec4 FragColor;
    
    void main()
    {
        FragColor = vec4(1.0f, 0.5f, 0.2f, 1.0f);
    } 
    """

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

    VAO = glGenVertexArrays(1)
    VBO = glGenBuffers(
        1)  # vertex buffer object, which stores vertices in the GPU's memory.
    glBindVertexArray(VAO)

    glBindBuffer(GL_ARRAY_BUFFER, VBO)  # now, all calls will configure VBO
    glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices,
                 GL_STATIC_DRAW)  # copy user-defined data into VBO

    glVertexAttribPointer(0, 3, GL_FLOAT,
                          GL_FALSE, 3 * np.dtype(np.float32).itemsize,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    glBindBuffer(GL_ARRAY_BUFFER, 0)

    glBindVertexArray(0)

    glfw.set_framebuffer_size_callback(window, framebuffer_size_callback)

    # render loop
    while not glfw.window_should_close(window):
        # input
        process_input(window)

        # rendering commands here
        glClearColor(0.2, 0.3, 0.3, 1.0)  # state-setting function
        glClear(GL_COLOR_BUFFER_BIT)  # state-using function

        # render triangle
        glUseProgram(shader)
        glBindVertexArray(VAO)
        glDrawArrays(GL_TRIANGLES, 0, 3)

        # check and call events and swap the buffers
        glfw.swap_buffers(window)
        glfw.poll_events()
    glfw.terminate()
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(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", None,
                                None)

    if window == 0:
        print("Failed to create GLFW window")
        glfw.terminate()
        return -1

    glfw.make_context_current(window)
    glfw.set_framebuffer_size_callback(window, frame_size_callback)

    vertexShader = gl.glCreateShader(gl.GL_VERTEX_SHADER)
    gl.glShaderSource(vertexShader, vertexShaderSource)
    gl.glCompileShader(vertexShader)

    success = gl.glGetShaderiv(vertexShader, gl.GL_COMPILE_STATUS)
    if not success:
        infoLog = gl.glGetShaderInfoLog(vertexShader)
        print("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n", infoLog)

    fragmentShader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
    gl.glShaderSource(fragmentShader, fragmentShaderSource)
    gl.glCompileShader(fragmentShader)
    success = gl.glGetShaderiv(fragmentShader, gl.GL_COMPILE_STATUS)
    if not success:
        infoLog = gl.glGetShaderInfoLog(fragmentShader)
        print("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n", infoLog)

    shaderProgram = gl.glCreateProgram()
    gl.glAttachShader(shaderProgram, vertexShader)
    gl.glAttachShader(shaderProgram, fragmentShader)
    gl.glLinkProgram(shaderProgram)
    success = gl.glGetProgramiv(shaderProgram, gl.GL_LINK_STATUS)
    if not success:
        infoLog = gl.glGetProgramInfoLog(shaderProgram)
        print("ERROR::SHADER::PROGRAM::LINKING_FAILED\n", infoLog)

    gl.glDeleteShader(vertexShader)
    gl.glDeleteShader(fragmentShader)

    vertices = np.array(
        [
            -0.5,
            -0.5,
            0,  # left
            0.5,
            -0.5,
            0,  # right
            0,
            0.5,
            0  # top
        ],
        dtype=np.float32)

    VAO = gl.glGenVertexArrays(1)
    VBO = gl.glGenBuffers(1)
    gl.glBindVertexArray(VAO)

    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, VBO)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, sys.getsizeof(vertices), vertices,
                    gl.GL_STATIC_DRAW)

    gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, 12, None)
    gl.glEnableVertexAttribArray(0)
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
    gl.glBindVertexArray(0)
    while not glfw.window_should_close(window):
        processInput(window)
        gl.glClearColor(0.2, 0.3, 0.3, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)
        gl.glUseProgram(shaderProgram)
        gl.glBindVertexArray(VAO)
        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3)
        glfw.swap_buffers(window)
        glfw.poll_events()

    # gl.glDeleteVertexArrays(1, VAO) 这里有点问题。暂时不知道怎么解决
    # gl.glDeleteBuffers(1, VBO)
    glfw.terminate()
    return 0
Esempio n. 34
0
def main():
    init()

    window = glfw.create_window(800, 600, "Chapter5", None, None)
    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_input_mode(window, glfw.STICKY_KEYS, GL_TRUE)
    glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)
    glfw.set_key_callback(window, key_callback)
    glfw.set_cursor_pos(window, 400, 300)
    glEnable(GL_DEPTH_TEST)
    glDepthFunc(GL_LESS)
    glClearColor(0.3, 0.3, 0.3, 1)

    vertex_array_id = glGenVertexArrays(1)
    glBindVertexArray(vertex_array_id)
    program_id = load_shaders('res/glsl/chapter8.vs', 'res/glsl/chapter8.fs')
    tex = texture.load('res/texture/eye.bmp')
    texture_id = glGetUniformLocation(program_id, 'TextureSampler')

    res_x, res_y = glfw.get_window_size(window)
    cam = camera.Camera(0, 0, 2, res_x, res_y)
    model = np.matrix(np.identity(4), dtype=np.float32)

    projection_id = glGetUniformLocation(program_id, 'projection')
    view_id = glGetUniformLocation(program_id, 'view')
    model_id = glGetUniformLocation(program_id, 'model')

    scene = load('res/model/sphere.obj')
    mesh = scene.meshes[0]
    vertex = mesh.vertices
    uv = mesh.texturecoords
    normal = mesh.normals
    index = mesh.faces

    vertex_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
    glBufferData(GL_ARRAY_BUFFER, vertex.nbytes, vertex, GL_STATIC_DRAW)

    uv_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, uv_buffer)
    glBufferData(GL_ARRAY_BUFFER, uv.nbytes, uv, GL_STATIC_DRAW)

    normal_buffer = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, normal_buffer)
    glBufferData(GL_ARRAY_BUFFER, normal.nbytes, normal, GL_STATIC_DRAW)

    element_buffer = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_buffer)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, index.nbytes, index, GL_STATIC_DRAW)

    while not glfw.window_should_close(window) and glfw.get_key(
            window, glfw.KEY_ESCAPE) != glfw.PRESS:
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        cam.controller(window)

        glUseProgram(program_id)
        glUniformMatrix4fv(projection_id, 1, GL_FALSE, cam.projection)
        glUniformMatrix4fv(view_id, 1, GL_FALSE, cam.view)
        glUniformMatrix4fv(model_id, 1, GL_FALSE, model)

        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_2D, tex)
        glUniform1i(texture_id, 0)

        glEnableVertexAttribArray(0)
        glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, None)

        glEnableVertexAttribArray(1)
        glBindBuffer(GL_ARRAY_BUFFER, uv_buffer)
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 0, None)

        glEnableVertexAttribArray(2)
        glBindBuffer(GL_ARRAY_BUFFER, normal_buffer)
        glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, None)

        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, element_buffer)
        glDrawElements(GL_TRIANGLES, index.nbytes, GL_UNSIGNED_INT, None)

        glDisableVertexAttribArray(0)
        glDisableVertexAttribArray(1)
        glDisableVertexAttribArray(2)

        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()
Esempio n. 35
0
def main():
    # 以下初始化glfw和窗口
    if not glfw.init():
        return

    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)

    # 新建窗口
    window = glfw.create_window(width, height, "Hello Window", None, None)
    if not window:
        glfw.terminate()
        return

    # 设置context
    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, resize_callback)
    ctx = moderngl.create_context(require=410)

    img = Image.open('./res/container.jpg')
    texture = ctx.texture(img.size, 3, img.tobytes())
    texture.use(0)  # bind texture

    img2 = Image.open('./res/awesome.png')
    img2 = img2.transpose(Image.FLIP_TOP_BOTTOM)
    texture2 = ctx.texture(img2.size, 4, img2.tobytes())
    texture2.use(1)

    # 顶点数组
    vertices = numpy.array([
        0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.5, -0.5, 0.0, 0.0, 1.0, 0.0,
        1.0, 0.0, -0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, -0.5, 0.5, 0.0,
        1.0, 1.0, 0.0, 0.0, 1.0
    ],
                           dtype='f4')

    # 建立vbo
    vbo = ctx.buffer(vertices.tobytes())

    # 顶点index
    indice = numpy.array([0, 1, 3, 1, 2, 3], dtype='u4')
    ebo = ctx.buffer(indice.tobytes())

    # 读取shader
    f = open('shaders/texture.vert')
    vert = f.read()
    f.close()

    f = open('shaders/texture.frag')
    frag = f.read()
    f.close()

    # 编译shader
    program = ctx.program(vertex_shader=vert, fragment_shader=frag)

    program['ourTexture'].write(numpy.array([0], 'i4').tobytes())
    program['texture2'].write(numpy.array([1], 'i4').tobytes())

    # 建立vao
    vao = ctx.simple_vertex_array(program,
                                  vbo,
                                  'aPos',
                                  'aColor',
                                  'aTexCoord',
                                  index_buffer=ebo)

    # 主循环
    while not glfw.window_should_close(window):
        process_input(window)

        ctx.viewport = (0, 0, width, height
                        )  # 这个就是glViewport(),设置opengl的窗口大小,不设置其实也无所谓
        ctx.clear(0.2, 0.3, 0.3, 1.0)

        vao.render()
        glfw.poll_events()

        glfw.swap_buffers(window)

    glfw.terminate()
Esempio n. 36
0
def main():
    # initialize glfw
    if not glfw.init():
        return

    w_width, w_height = 1280, 720
    aspect_ratio = w_width / w_height

    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 2)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, window_resize)
    glfw.set_key_callback(window, key_callback)
    glfw.set_cursor_pos_callback(window, mouse_callback)

    cube = [
        #Badan Mobil
        #front
        -1.0, -1.0, 1.0,
        1.0, -1.0, 1.0,
        1.0, 1.0, 1.0,
        -1.0, 1.0, 1.0,

        #right
        1.0, -1.0, 1.0,
        1.0, -1.0, -2.0,
        1.0, 1.0, -2.0,
        1.0, 1.0, 1.0,

        #back
        -1.0, -1.0, -2.0,
        1.0, -1.0, -2.0,
        1.0, 1.0, -2.0,
        -1.0, 1.0, -2.0,

        #left
        -1.0, -1.0, 1.0,
        -1.0, -1.0, -2.0,
        -1.0, 1.0, -2.0,
        -1.0, 1.0, 1.0,

        #top
        -1.0, 1.0, 1.0,
        1.0, 1.0, 1.0,
        1.0, 1.0, -2.0,
        -1.0, 1.0, -2.0,

        #bottom
        -1.0, -1.0, 1.0,
        1.0, -1.0, 1.0,
        1.0, -1.0, -2.0,
        -1.0, -1.0, -2.0,

        #Depan Mobil
        #front
        -1.0, -1.0, 2.0,
        1.0, -1.0, 2.0,
        1.0, 0, 2.0,
        -1.0, 0, 2.0,

        #right
        1.0, -1.0, 2.0,
        1.0, -1.0, 1.0,
        1.0, 0, 1.0,
        1.0, 0, 2.0,

        #back
        -1.0, -1.0, 1.0,
        1.0, -1.0, 1.0,
        1.0, 0, 1.0,
        -1.0, 0, 1.0,

        #left
        -1.0, -1.0, 2.0, 
        -1.0, -1.0, 1.0,
        -1.0, 0, 1.0,
        -1.0, 0, 2.0,

        #top
        -1.0, 0, 2.0,
        1.0, 0, 2.0,
        1.0, 0, 1.0,
        -1.0, 0, 1.0,

        #bottom
        -1.0, -1.0, 2.0,
        1.0, -1.0, 2.0, 
        1.0, -1.0, 1.0,
        -1.0, -1.0, 1.0
    ]

    cube = numpy.array(cube, dtype=numpy.float32)
    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,

        24,25,26,26,27,24,
        28,29,30,30,31,28,
        32,33,34,34,34,32,
        36,37,38,38,39,36,
        40,41,42,42,43,40,
        44,45,46,46,47,44
    ]

    indices = numpy.array(indices, dtype=numpy.uint32)

    car_program = compile_shader("Shaders/CarShader.vs", "Shaders/CarShader.fs")
    wheel_program = compile_shader("Shaders/WheelShader.vs", "Shaders/WheelShader.fs")
    glClearColor(0.2, 0.3, 0.2, 1.0)
    glEnable(GL_DEPTH_TEST)

    projection = matrix44.create_perspective_projection_matrix(45.0, aspect_ratio, 0.1, 100.0)

    car_model_loc = glGetUniformLocation(car_program, "model")
    car_view_loc = glGetUniformLocation(car_program, "view")
    car_proj_loc = glGetUniformLocation(car_program, "proj")

    wheel_model_loc = glGetUniformLocation(wheel_program, "model")
    wheel_view_loc = glGetUniformLocation(wheel_program, "view")
    wheel_proj_loc = glGetUniformLocation(wheel_program, "proj")
    circle = generateCircleArray(0, 0, 0, 0.4, 0.2)

    VAO = glGenVertexArrays(1)
    glBindVertexArray(VAO)
    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, circle.itemsize * 3, ctypes.c_void_p(0))
        
    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW)


    while not glfw.window_should_close(window):
        glfw.poll_events()
        do_movement()
        view = cam.get_view_matrix()
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        #Gambar Roda
        glBindBuffer(GL_ARRAY_BUFFER, VBO)
        glBufferData(GL_ARRAY_BUFFER, circle.itemsize * len(circle), circle, GL_STATIC_DRAW)

        glEnableVertexAttribArray(0)

        glUseProgram(wheel_program)

        wheel_positions = [(1.0, -1.0, 1.0), (-1.2, -1.0, 1.0), (-1.2, -1.0, -2.0), (1.0, -1.0, -2.0)]

        glUniformMatrix4fv(wheel_proj_loc, 1, GL_FALSE, projection)

        glUniformMatrix4fv(wheel_view_loc, 1, GL_FALSE, view)

        for i in range(len(wheel_positions)):
            wheel_model = matrix44.create_from_translation(wheel_positions[i])
            glUniformMatrix4fv(wheel_model_loc, 1, GL_FALSE, wheel_model)
            glDrawArrays(GL_TRIANGLES, 0, len(circle))


        #Gambar Mobil
        glBindBuffer(GL_ARRAY_BUFFER, VBO)
        glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW)

        # position
        glEnableVertexAttribArray(0)

        glUseProgram(car_program)

        glUniformMatrix4fv(car_proj_loc, 1, GL_FALSE, projection)

        glUniformMatrix4fv(car_view_loc, 1, GL_FALSE, view)

        car_model = matrix44.create_from_translation((0,0,0))
        glUniformMatrix4fv(car_model_loc, 1, GL_FALSE, car_model)
        glDrawElements(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT, None)

        glfw.swap_buffers(window)

    glfw.terminate()
Esempio n. 37
0
    def __init__(self, **kwargs):
        super().__init__(**kwargs)

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

        # Configure the OpenGL context
        glfw.window_hint(glfw.CONTEXT_CREATION_API, glfw.NATIVE_CONTEXT_API)
        glfw.window_hint(glfw.CLIENT_API, glfw.OPENGL_API)
        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, self.gl_version[0])
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, self.gl_version[1])
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
        glfw.window_hint(glfw.RESIZABLE, self.resizable)
        glfw.window_hint(glfw.DOUBLEBUFFER, True)
        glfw.window_hint(glfw.DEPTH_BITS, 24)
        glfw.window_hint(glfw.SAMPLES, self.samples)

        monitor = None
        if self.fullscreen:
            monitor = glfw.get_primary_monitor()
            mode = glfw.get_video_mode(monitor)
            self._width, self._height = mode.size.width, mode.size.height

            glfw.window_hint(glfw.RED_BITS, mode.bits.red)
            glfw.window_hint(glfw.GREEN_BITS, mode.bits.green)
            glfw.window_hint(glfw.BLUE_BITS, mode.bits.blue)
            glfw.window_hint(glfw.REFRESH_RATE, mode.refresh_rate)

        self._window = glfw.create_window(self.width, self.height, self.title,
                                          monitor, None)
        self._has_focus = True

        if not self._window:
            glfw.terminate()
            raise ValueError("Failed to create window")

        self.cursor = self._cursor

        self._buffer_width, self._buffer_height = glfw.get_framebuffer_size(
            self._window)
        glfw.make_context_current(self._window)

        if self.vsync:
            glfw.swap_interval(1)

        glfw.set_key_callback(self._window, self.glfw_key_event_callback)
        glfw.set_cursor_pos_callback(self._window,
                                     self.glfw_mouse_event_callback)
        glfw.set_mouse_button_callback(self._window,
                                       self.glfw_mouse_button_callback)
        glfw.set_scroll_callback(self._window, self.glfw_mouse_scroll_callback)
        glfw.set_window_size_callback(self._window,
                                      self.glfw_window_resize_callback)
        glfw.set_char_callback(self._window, self.glfw_char_callback)
        glfw.set_window_focus_callback(self._window, self.glfw_window_focus)
        glfw.set_cursor_enter_callback(self._window, self.glfw_cursor_enter)
        glfw.set_window_iconify_callback(self._window,
                                         self.glfw_window_iconify)

        self.init_mgl_context()
        self.set_default_viewport()
Esempio n. 38
0
def main():
    global hdrbuffer, blurbuffer, cube

    if not glfw.init():
        print('Failed to initialize GLFW.')
        return

    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)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
    glfw.window_hint(glfw.SAMPLES, config['sampling_level'])

    if config['fullscreen']:
        global width, height
        mode = glfw.get_video_mode(glfw.get_primary_monitor())
        width, height = mode.size.width, mode.size.height
        window = glfw.create_window(mode.size.width, mode.size.height,
                                    config['app_name'],
                                    glfw.get_primary_monitor(), None)
    else:
        window = glfw.create_window(width, height, config['app_name'], None,
                                    None)
    if not window:
        print('Failed to create GLFW Window.')
        glfw.terminate()
        return

    glfw.make_context_current(window)
    glfw.set_input_mode(window, glfw.CURSOR, glfw.CURSOR_DISABLED)
    glfw.set_framebuffer_size_callback(window, resizeCallback)
    glfw.set_cursor_pos_callback(window, mouseMove)
    glfw.set_key_callback(window, keyCallback)

    glEnable(GL_DEPTH_TEST)
    glEnable(GL_MULTISAMPLE)
    glEnable(GL_CULL_FACE)
    glCullFace(GL_BACK)

    program = getLinkedProgram('resources/shaders/vert.vs',
                               'resources/shaders/frag.fs')
    depthProgram = getLinkedProgram('resources/shaders/shadow_depth.vs',
                                    'resources/shaders/shadow_depth.fs')
    blurProgram = getLinkedProgram('resources/shaders/blur.vs',
                                   'resources/shaders/blur.fs')
    hdrProgram = getLinkedProgram('resources/shaders/hdr.vs',
                                  'resources/shaders/hdr.fs')

    blurProgram.use()
    blurProgram.setInt('image', 0)

    hdrProgram.use()
    hdrProgram.setInt('sceneMap', 0)
    hdrProgram.setInt('bloomMap', 1)

    hdrbuffer = HDRbuffer()
    hdrbuffer.create(width, height)
    blurbuffer = Blurbuffer()
    blurbuffer.create(width, height)

    bloom = Bloom(hdrbuffer, hdrProgram, blurbuffer, blurProgram)

    lightPos = glm.vec3(10, 100, 0)
    perspective = glm.perspective(45, width / height, config['near_plane'],
                                  config['far_plane'])

    shadow = Shadow(lightPos, config['near_plane'], config['far_plane'])
    shadow.create(config['shadow_width'], config['shadow_height'])

    cube = Model('resources/models/cube.json')
    texture = loadTexture2D('resources/textures/diffuse.jpg')
    normal = loadTexture2D('resources/textures/normal.jpg')
    specular = loadTexture2D('resources/textures/specular.jpg')
    depth = loadTexture2D('resources/textures/depth.jpg')

    blockPositions = generateVoxelPositions(config['world_width'],
                                            config['world_height'],
                                            config['world_width'])
    cube.setMultiplePositions(blockPositions)
    blockPositions.clear()

    lastTime = glfw.get_time()
    while not glfw.window_should_close(window):
        if config['debug_mode']:
            print(glGetError())

        currentTime = glfw.get_time()
        deltaTime = currentTime - lastTime
        lastTime = currentTime

        lightPos.x = config['world_width'] / 2
        lightPos.z = math.sin(currentTime * 0.1) * config['world_depth'] * 2
        lightPos.y = config['world_height'] * 2
        shadow.updateMatrix(lightPos, config['near_plane'],
                            config['far_plane'])

        moveInput(window, deltaTime)

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glClearColor(0.1, 0.2, 0.8, 1)

        shadow.castShadow(depthProgram)
        cube.drawMultiple(depthProgram)
        shadow.endCastShadow(program)

        hdrbuffer.bind()
        glViewport(0, 0, width, height)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        program.use()
        program.setMat4('viewProject', perspective * camera.getViewMatrix())
        program.setVec3('viewPos', camera.position)
        program.setVec3('lightPos', lightPos)

        glActiveTexture(GL_TEXTURE1)
        program.setInt('mat.diffuseMap', 1)
        texture.bind()

        glActiveTexture(GL_TEXTURE2)
        program.setInt('mat.normalMap', 2)
        normal.bind()

        glActiveTexture(GL_TEXTURE3)
        program.setInt('mat.specularMap', 3)
        specular.bind()

        glActiveTexture(GL_TEXTURE4)
        program.setInt('mat.depthMap', 4)
        depth.bind()
        program.setFloat('mat.shininess', 128)
        program.setFloat('mat.heightScale', 0.12)

        cube.drawMultiple(program)
        hdrbuffer.unbind()
        hdrbuffer.finalize()

        bloom.drawProcessedScene()

        glfw.poll_events()
        glfw.swap_buffers(window)

    glfw.terminate()
Esempio n. 39
0
def world(
    timebase,
    eye_procs_alive,
    ipc_pub_url,
    ipc_sub_url,
    ipc_push_url,
    user_dir,
    version,
    preferred_remote_port,
    hide_ui,
    debug,
):
    """Reads world video and runs plugins.

    Creates a window, gl context.
    Grabs images from a capture.
    Maps pupil to gaze data
    Can run various plug-ins.

    Reacts to notifications:
        ``eye_process.started``
        ``start_plugin``
        ``should_stop``

    Emits notifications:
        ``eye_process.should_start``
        ``eye_process.should_stop``
        ``world_process.started``
        ``world_process.stopped``
        ``recording.should_stop``: Emits on camera failure
        ``launcher_process.should_stop``

    Emits data:
        ``gaze``: Gaze data from current gaze mapping plugin.``
        ``*``: any other plugin generated data in the events
               that it not [dt,pupil,gaze].
    """

    # We defer the imports because of multiprocessing.
    # Otherwise the world process each process also loads the other imports.
    # This is not harmful but unnecessary.

    # general imports
    from time import sleep
    import logging

    # networking
    import zmq
    import zmq_tools

    # zmq ipc setup
    zmq_ctx = zmq.Context()
    ipc_pub = zmq_tools.Msg_Dispatcher(zmq_ctx, ipc_push_url)
    notify_sub = zmq_tools.Msg_Receiver(zmq_ctx, ipc_sub_url, topics=("notify",))

    # log setup
    logging.getLogger("OpenGL").setLevel(logging.ERROR)
    logger = logging.getLogger()
    logger.handlers = []
    logger.setLevel(logging.NOTSET)
    logger.addHandler(zmq_tools.ZMQ_handler(zmq_ctx, ipc_push_url))
    # create logger for the context of this function
    logger = logging.getLogger(__name__)

    def launch_eye_process(eye_id, delay=0):
        n = {
            "subject": "eye_process.should_start.{}".format(eye_id),
            "eye_id": eye_id,
            "delay": delay,
        }
        ipc_pub.notify(n)

    def stop_eye_process(eye_id):
        n = {
            "subject": "eye_process.should_stop.{}".format(eye_id),
            "eye_id": eye_id,
            "delay": 0.2,
        }
        ipc_pub.notify(n)

    def start_stop_eye(eye_id, make_alive):
        if make_alive:
            launch_eye_process(eye_id)
        else:
            stop_eye_process(eye_id)

    def detection_enabled_getter() -> bool:
        return g_pool.pupil_detection_enabled

    def detection_enabled_setter(is_on: bool):
        g_pool.pupil_detection_enabled = is_on
        n = {"subject": "set_pupil_detection_enabled", "value": is_on}
        ipc_pub.notify(n)

    try:
        from background_helper import IPC_Logging_Task_Proxy

        IPC_Logging_Task_Proxy.push_url = ipc_push_url

        from tasklib.background.patches import IPCLoggingPatch

        IPCLoggingPatch.ipc_push_url = ipc_push_url

        from OpenGL.GL import GL_COLOR_BUFFER_BIT

        # display
        import glfw
        from gl_utils import GLFWErrorReporting

        GLFWErrorReporting.set_default()

        from version_utils import parse_version
        from pyglui import ui, cygl, __version__ as pyglui_version

        assert parse_version(pyglui_version) >= parse_version(
            "1.27"
        ), "pyglui out of date, please upgrade to newest version"
        from pyglui.cygl.utils import Named_Texture
        import gl_utils

        # helpers/utils
        from file_methods import Persistent_Dict
        from methods import normalize, denormalize, delta_t, get_system_info, timer
        from uvc import get_time_monotonic

        logger.info("Application Version: {}".format(version))
        logger.info("System Info: {}".format(get_system_info()))
        logger.debug(f"Debug flag: {debug}")

        import audio

        # Plug-ins
        from plugin import (
            Plugin,
            System_Plugin_Base,
            Plugin_List,
            import_runtime_plugins,
        )
        from plugin_manager import Plugin_Manager
        from calibration_choreography import (
            available_calibration_choreography_plugins,
            CalibrationChoreographyPlugin,
            patch_loaded_plugins_with_choreography_plugin,
        )

        available_choreography_plugins = available_calibration_choreography_plugins()

        from gaze_mapping import registered_gazer_classes
        from gaze_mapping.gazer_base import GazerBase
        from pupil_detector_plugins.detector_base_plugin import PupilDetectorPlugin
        from fixation_detector import Fixation_Detector
        from recorder import Recorder
        from display_recent_gaze import Display_Recent_Gaze
        from time_sync import Time_Sync
        from network_api import NetworkApiPlugin
        from pupil_groups import Pupil_Groups
        from surface_tracker import Surface_Tracker_Online
        from log_display import Log_Display
        from annotations import Annotation_Capture
        from log_history import Log_History
        from blink_detection import Blink_Detection
        from video_capture import (
            source_classes,
            manager_classes,
            Base_Manager,
            Base_Source,
        )
        from pupil_data_relay import Pupil_Data_Relay
        from remote_recorder import Remote_Recorder
        from accuracy_visualizer import Accuracy_Visualizer

        from system_graphs import System_Graphs
        from camera_intrinsics_estimation import Camera_Intrinsics_Estimation
        from hololens_relay import Hololens_Relay
        from head_pose_tracker.online_head_pose_tracker import Online_Head_Pose_Tracker

        # UI Platform tweaks
        if platform.system() == "Linux":
            scroll_factor = 10.0
            window_position_default = (30, 30)
        elif platform.system() == "Windows":
            scroll_factor = 10.0
            window_position_default = (8, 90)
        else:
            scroll_factor = 1.0
            window_position_default = (0, 0)

        process_was_interrupted = False

        def interrupt_handler(sig, frame):
            import traceback

            trace = traceback.format_stack(f=frame)
            logger.debug(f"Caught signal {sig} in:\n" + "".join(trace))
            nonlocal process_was_interrupted
            process_was_interrupted = True

        signal.signal(signal.SIGINT, interrupt_handler)

        icon_bar_width = 50
        window_size = None
        camera_render_size = None
        content_scale = 1.0

        # g_pool holds variables for this process they are accessible to all plugins
        g_pool = SimpleNamespace()
        g_pool.debug = debug
        g_pool.app = "capture"
        g_pool.process = "world"
        g_pool.user_dir = user_dir
        g_pool.version = version
        g_pool.timebase = timebase
        g_pool.zmq_ctx = zmq_ctx
        g_pool.ipc_pub = ipc_pub
        g_pool.ipc_pub_url = ipc_pub_url
        g_pool.ipc_sub_url = ipc_sub_url
        g_pool.ipc_push_url = ipc_push_url
        g_pool.eye_procs_alive = eye_procs_alive
        g_pool.preferred_remote_port = preferred_remote_port

        def get_timestamp():
            return get_time_monotonic() - g_pool.timebase.value

        g_pool.get_timestamp = get_timestamp
        g_pool.get_now = get_time_monotonic

        # manage plugins
        runtime_plugins = import_runtime_plugins(
            os.path.join(g_pool.user_dir, "plugins")
        )
        runtime_plugins = [
            p for p in runtime_plugins if not issubclass(p, PupilDetectorPlugin)
        ]
        user_plugins = [
            Pupil_Groups,
            NetworkApiPlugin,
            Time_Sync,
            Surface_Tracker_Online,
            Annotation_Capture,
            Log_History,
            Fixation_Detector,
            Blink_Detection,
            Remote_Recorder,
            Accuracy_Visualizer,
            Camera_Intrinsics_Estimation,
            Hololens_Relay,
            Online_Head_Pose_Tracker,
        ]

        system_plugins = (
            [
                Log_Display,
                Display_Recent_Gaze,
                Recorder,
                Pupil_Data_Relay,
                Plugin_Manager,
                System_Graphs,
            ]
            + manager_classes
            + source_classes
        )
        plugins = (
            system_plugins
            + user_plugins
            + runtime_plugins
            + available_choreography_plugins
            + registered_gazer_classes()
        )
        user_plugins += [
            p
            for p in runtime_plugins
            if not isinstance(
                p,
                (
                    Base_Manager,
                    Base_Source,
                    System_Plugin_Base,
                    CalibrationChoreographyPlugin,
                    GazerBase,
                ),
            )
        ]
        g_pool.plugin_by_name = {p.__name__: p for p in plugins}

        default_capture_name = "UVC_Source"
        default_capture_settings = {
            "preferred_names": [
                "Pupil Cam1 ID2",
                "Logitech Camera",
                "(046d:081d)",
                "C510",
                "B525",
                "C525",
                "C615",
                "C920",
                "C930e",
            ],
            "frame_size": (1280, 720),
            "frame_rate": 30,
        }

        default_plugins = [
            (default_capture_name, default_capture_settings),
            ("Pupil_Data_Relay", {}),
            ("UVC_Manager", {}),
            ("NDSI_Manager", {}),
            ("HMD_Streaming_Manager", {}),
            ("File_Manager", {}),
            ("Log_Display", {}),
            ("Dummy_Gaze_Mapper", {}),
            ("Display_Recent_Gaze", {}),
            # Calibration choreography plugin is added below by calling
            # patch_loaded_plugins_with_choreography_plugin
            ("Recorder", {}),
            ("NetworkApiPlugin", {}),
            ("Fixation_Detector", {}),
            ("Blink_Detection", {}),
            ("Accuracy_Visualizer", {}),
            ("Plugin_Manager", {}),
            ("System_Graphs", {}),
        ]

        def consume_events_and_render_buffer():
            gl_utils.glViewport(0, 0, *camera_render_size)
            for p in g_pool.plugins:
                p.gl_display()

            gl_utils.glViewport(0, 0, *window_size)
            try:
                clipboard = glfw.get_clipboard_string(main_window).decode()
            except (AttributeError, glfw.GLFWError):
                # clipboard is None, might happen on startup
                clipboard = ""
            g_pool.gui.update_clipboard(clipboard)
            user_input = g_pool.gui.update()
            if user_input.clipboard != clipboard:
                # only write to clipboard if content changed
                glfw.set_clipboard_string(main_window, user_input.clipboard)

            for button, action, mods in user_input.buttons:
                x, y = glfw.get_cursor_pos(main_window)
                pos = gl_utils.window_coordinate_to_framebuffer_coordinate(
                    main_window, x, y, cached_scale=None
                )
                pos = normalize(pos, camera_render_size)
                # Position in img pixels
                pos = denormalize(pos, g_pool.capture.frame_size)

                for plugin in g_pool.plugins:
                    if plugin.on_click(pos, button, action):
                        break

            for key, scancode, action, mods in user_input.keys:
                for plugin in g_pool.plugins:
                    if plugin.on_key(key, scancode, action, mods):
                        break

            for char_ in user_input.chars:
                for plugin in g_pool.plugins:
                    if plugin.on_char(char_):
                        break

            glfw.swap_buffers(main_window)

        # Callback functions
        def on_resize(window, w, h):
            nonlocal window_size
            nonlocal camera_render_size
            nonlocal content_scale
            if w == 0 or h == 0:
                return

            # Always clear buffers on resize to make sure that there are no overlapping
            # artifacts from previous frames.
            gl_utils.glClear(GL_COLOR_BUFFER_BIT)
            gl_utils.glClearColor(0, 0, 0, 1)

            content_scale = gl_utils.get_content_scale(window)
            framebuffer_scale = gl_utils.get_framebuffer_scale(window)
            g_pool.gui.scale = content_scale
            window_size = w, h
            camera_render_size = w - int(icon_bar_width * g_pool.gui.scale), h
            g_pool.gui.update_window(*window_size)
            g_pool.gui.collect_menus()

            for p in g_pool.plugins:
                p.on_window_resize(window, *camera_render_size)

            # Minimum window size required, otherwise parts of the UI can cause openGL
            # issues with permanent effects. Depends on the content scale, which can
            # potentially be dynamically modified, so we re-adjust the size limits every
            # time here.
            min_size = int(2 * icon_bar_width * g_pool.gui.scale / framebuffer_scale)
            glfw.set_window_size_limits(
                window,
                min_size,
                min_size,
                glfw.DONT_CARE,
                glfw.DONT_CARE,
            )

            # Needed, to update the window buffer while resizing
            consume_events_and_render_buffer()

        def on_window_key(window, key, scancode, action, mods):
            g_pool.gui.update_key(key, scancode, action, mods)

        def on_window_char(window, char):
            g_pool.gui.update_char(char)

        def on_window_mouse_button(window, button, action, mods):
            g_pool.gui.update_button(button, action, mods)

        def on_pos(window, x, y):
            x, y = gl_utils.window_coordinate_to_framebuffer_coordinate(
                window, x, y, cached_scale=None
            )
            g_pool.gui.update_mouse(x, y)
            pos = x, y
            pos = normalize(pos, camera_render_size)
            # Position in img pixels
            pos = denormalize(pos, g_pool.capture.frame_size)
            for p in g_pool.plugins:
                p.on_pos(pos)

        def on_scroll(window, x, y):
            g_pool.gui.update_scroll(x, y * scroll_factor)

        def on_drop(window, paths):
            for plugin in g_pool.plugins:
                if plugin.on_drop(paths):
                    break

        tick = delta_t()

        def get_dt():
            return next(tick)

        # load session persistent settings
        session_settings = Persistent_Dict(
            os.path.join(g_pool.user_dir, "user_settings_world")
        )
        if parse_version(session_settings.get("version", "0.0")) != g_pool.version:
            logger.info(
                "Session setting are from a different version of this app. I will not use those."
            )
            session_settings.clear()

        g_pool.min_data_confidence = 0.6
        g_pool.min_calibration_confidence = session_settings.get(
            "min_calibration_confidence", 0.8
        )
        g_pool.pupil_detection_enabled = session_settings.get(
            "pupil_detection_enabled", True
        )
        g_pool.active_gaze_mapping_plugin = None
        g_pool.capture = None

        audio.set_audio_mode(
            session_settings.get("audio_mode", audio.get_default_audio_mode())
        )

        def handle_notifications(noti):
            subject = noti["subject"]
            if subject == "set_pupil_detection_enabled":
                g_pool.pupil_detection_enabled = noti["value"]
            elif subject == "start_plugin":
                try:
                    g_pool.plugins.add(
                        g_pool.plugin_by_name[noti["name"]], args=noti.get("args", {})
                    )
                except KeyError as err:
                    logger.error(f"Attempt to load unknown plugin: {err}")
            elif subject == "stop_plugin":
                for p in g_pool.plugins:
                    if p.class_name == noti["name"]:
                        p.alive = False
                        g_pool.plugins.clean()
            elif subject == "eye_process.started":
                noti = {
                    "subject": "set_pupil_detection_enabled",
                    "value": g_pool.pupil_detection_enabled,
                }
                ipc_pub.notify(noti)
            elif subject == "set_min_calibration_confidence":
                g_pool.min_calibration_confidence = noti["value"]
            elif subject.startswith("meta.should_doc"):
                ipc_pub.notify(
                    {"subject": "meta.doc", "actor": g_pool.app, "doc": world.__doc__}
                )
                for p in g_pool.plugins:
                    if (
                        p.on_notify.__doc__
                        and p.__class__.on_notify != Plugin.on_notify
                    ):
                        ipc_pub.notify(
                            {
                                "subject": "meta.doc",
                                "actor": p.class_name,
                                "doc": p.on_notify.__doc__,
                            }
                        )
            elif subject == "world_process.adapt_window_size":
                set_window_size()
            elif subject == "world_process.should_stop":
                glfw.set_window_should_close(main_window, True)

        width, height = session_settings.get(
            "window_size", (1280 + icon_bar_width, 720)
        )

        # window and gl setup
        glfw.init()
        glfw.window_hint(glfw.SCALE_TO_MONITOR, glfw.TRUE)
        if hide_ui:
            glfw.window_hint(glfw.VISIBLE, 0)  # hide window
        main_window = glfw.create_window(
            width, height, "Pupil Capture - World", None, None
        )

        window_position_manager = gl_utils.WindowPositionManager()
        window_pos = window_position_manager.new_window_position(
            window=main_window,
            default_position=window_position_default,
            previous_position=session_settings.get("window_position", None),
        )
        glfw.set_window_pos(main_window, window_pos[0], window_pos[1])

        glfw.make_context_current(main_window)
        cygl.utils.init()
        g_pool.main_window = main_window

        def reset_restart():
            logger.warning("Resetting all settings and restarting Capture.")
            glfw.set_window_should_close(main_window, True)
            ipc_pub.notify({"subject": "clear_settings_process.should_start"})
            ipc_pub.notify({"subject": "world_process.should_start", "delay": 2.0})

        def toggle_general_settings(collapsed):
            # this is the menu toggle logic.
            # Only one menu can be open.
            # If no menu is opened, the menubar should collapse.
            g_pool.menubar.collapsed = collapsed
            for m in g_pool.menubar.elements:
                m.collapsed = True
            general_settings.collapsed = collapsed

        # setup GUI
        g_pool.gui = ui.UI()
        g_pool.menubar = ui.Scrolling_Menu(
            "Settings", pos=(-400, 0), size=(-icon_bar_width, 0), header_pos="left"
        )
        g_pool.iconbar = ui.Scrolling_Menu(
            "Icons", pos=(-icon_bar_width, 0), size=(0, 0), header_pos="hidden"
        )
        g_pool.quickbar = ui.Stretching_Menu("Quick Bar", (0, 100), (120, -100))
        g_pool.gui.append(g_pool.menubar)
        g_pool.gui.append(g_pool.iconbar)
        g_pool.gui.append(g_pool.quickbar)

        general_settings = ui.Growing_Menu("General", header_pos="headline")

        def set_window_size():
            # Get current capture frame size
            f_width, f_height = g_pool.capture.frame_size

            # Get current display scale factor
            content_scale = gl_utils.get_content_scale(main_window)
            framebuffer_scale = gl_utils.get_framebuffer_scale(main_window)
            display_scale_factor = content_scale / framebuffer_scale

            # Scale the capture frame size by display scale factor
            f_width *= display_scale_factor
            f_height *= display_scale_factor

            # Increas the width to account for the added scaled icon bar width
            f_width += icon_bar_width * display_scale_factor

            # Set the newly calculated size (scaled capture frame size + scaled icon bar width)
            glfw.set_window_size(main_window, int(f_width), int(f_height))

        general_settings.append(ui.Button("Reset window size", set_window_size))
        general_settings.append(
            ui.Selector(
                "Audio mode",
                None,
                getter=audio.get_audio_mode,
                setter=audio.set_audio_mode,
                selection=audio.get_audio_mode_list(),
            )
        )

        general_settings.append(
            ui.Switch(
                "pupil_detection_enabled",
                label="Pupil detection",
                getter=detection_enabled_getter,
                setter=detection_enabled_setter,
            )
        )
        general_settings.append(
            ui.Switch(
                "eye0_process",
                label="Detect eye 0",
                setter=lambda alive: start_stop_eye(0, alive),
                getter=lambda: eye_procs_alive[0].value,
            )
        )
        general_settings.append(
            ui.Switch(
                "eye1_process",
                label="Detect eye 1",
                setter=lambda alive: start_stop_eye(1, alive),
                getter=lambda: eye_procs_alive[1].value,
            )
        )

        general_settings.append(
            ui.Info_Text("Capture Version: {}".format(g_pool.version))
        )
        general_settings.append(
            ui.Button("Restart with default settings", reset_restart)
        )

        g_pool.menubar.append(general_settings)
        icon = ui.Icon(
            "collapsed",
            general_settings,
            label=chr(0xE8B8),
            on_val=False,
            off_val=True,
            setter=toggle_general_settings,
            label_font="pupil_icons",
        )
        icon.tooltip = "General Settings"
        g_pool.iconbar.append(icon)

        user_plugin_separator = ui.Separator()
        user_plugin_separator.order = 0.35
        g_pool.iconbar.append(user_plugin_separator)

        loaded_plugins = session_settings.get("loaded_plugins", default_plugins)

        # Resolve the active calibration choreography plugin
        loaded_plugins = patch_loaded_plugins_with_choreography_plugin(
            loaded_plugins, app=g_pool.app
        )
        session_settings["loaded_plugins"] = loaded_plugins

        # plugins that are loaded based on user settings from previous session
        g_pool.plugins = Plugin_List(g_pool, loaded_plugins)

        if not g_pool.capture:
            # Make sure we always have a capture running. Important if there was no
            # capture stored in session settings.
            g_pool.plugins.add(
                g_pool.plugin_by_name[default_capture_name], default_capture_settings
            )

        # Register callbacks main_window
        glfw.set_framebuffer_size_callback(main_window, on_resize)
        glfw.set_key_callback(main_window, on_window_key)
        glfw.set_char_callback(main_window, on_window_char)
        glfw.set_mouse_button_callback(main_window, on_window_mouse_button)
        glfw.set_cursor_pos_callback(main_window, on_pos)
        glfw.set_scroll_callback(main_window, on_scroll)
        glfw.set_drop_callback(main_window, on_drop)

        # gl_state settings
        gl_utils.basic_gl_setup()
        g_pool.image_tex = Named_Texture()

        toggle_general_settings(True)

        # now that we have a proper window we can load the last gui configuration
        g_pool.gui.configuration = session_settings.get("ui_config", {})
        # If previously selected plugin was not loaded this time, we will have an
        # expanded menubar without any menu selected. We need to ensure the menubar is
        # collapsed in this case.
        if all(submenu.collapsed for submenu in g_pool.menubar.elements):
            g_pool.menubar.collapsed = True

        # create a timer to control window update frequency
        window_update_timer = timer(1 / 60)

        def window_should_update():
            return next(window_update_timer)

        # trigger setup of window and gl sizes
        on_resize(main_window, *glfw.get_framebuffer_size(main_window))

        if session_settings.get("eye1_process_alive", True):
            launch_eye_process(1, delay=0.6)
        if session_settings.get("eye0_process_alive", True):
            launch_eye_process(0, delay=0.3)

        ipc_pub.notify({"subject": "world_process.started"})
        logger.warning("Process started.")

        if platform.system() == "Darwin":
            # On macOS, calls to glfw.swap_buffers() deliberately take longer in case of
            # occluded windows, based on the swap interval value. This causes an FPS drop
            # and leads to problems when recording. To side-step this behaviour, the swap
            # interval is set to zero.
            #
            # Read more about window occlusion on macOS here:
            # https://developer.apple.com/library/archive/documentation/Performance/Conceptual/power_efficiency_guidelines_osx/WorkWhenVisible.html
            glfw.swap_interval(0)

        # Event loop
        while not glfw.window_should_close(main_window) and not process_was_interrupted:

            # fetch newest notifications
            new_notifications = []
            while notify_sub.new_data:
                t, n = notify_sub.recv()
                new_notifications.append(n)

            # notify each plugin if there are new notifications:
            for n in new_notifications:
                handle_notifications(n)
                for p in g_pool.plugins:
                    p.on_notify(n)

            # a dictionary that allows plugins to post and read events
            events = {}
            # report time between now and the last loop interation
            events["dt"] = get_dt()

            # allow each Plugin to do its work.
            for p in g_pool.plugins:
                p.recent_events(events)

            # check if a plugin need to be destroyed
            g_pool.plugins.clean()

            # "blacklisted" events that were already sent
            del events["pupil"]
            del events["gaze"]
            # delete if exists. More expensive than del, so only use it when key might not exist
            events.pop("annotation", None)

            # send new events to ipc:
            if "frame" in events:
                del events["frame"]  # send explicitly with frame publisher
            if "depth_frame" in events:
                del events["depth_frame"]
            if "audio_packets" in events:
                del events["audio_packets"]
            del events["dt"]  # no need to send this
            for data in events.values():
                assert isinstance(data, (list, tuple))
                for d in data:
                    ipc_pub.send(d)

            glfw.make_context_current(main_window)
            # render visual feedback from loaded plugins
            glfw.poll_events()
            if window_should_update() and gl_utils.is_window_visible(main_window):

                gl_utils.glViewport(0, 0, *camera_render_size)
                for p in g_pool.plugins:
                    p.gl_display()

                gl_utils.glViewport(0, 0, *window_size)
                try:
                    clipboard = glfw.get_clipboard_string(main_window).decode()
                except (AttributeError, glfw.GLFWError):
                    # clipboard is None, might happen on startup
                    clipboard = ""
                g_pool.gui.update_clipboard(clipboard)
                user_input = g_pool.gui.update()
                if user_input.clipboard != clipboard:
                    # only write to clipboard if content changed
                    glfw.set_clipboard_string(main_window, user_input.clipboard)

                for button, action, mods in user_input.buttons:
                    x, y = glfw.get_cursor_pos(main_window)
                    pos = gl_utils.window_coordinate_to_framebuffer_coordinate(
                        main_window, x, y, cached_scale=None
                    )
                    pos = normalize(pos, camera_render_size)
                    # Position in img pixels
                    pos = denormalize(pos, g_pool.capture.frame_size)

                    for plugin in g_pool.plugins:
                        if plugin.on_click(pos, button, action):
                            break

                for key, scancode, action, mods in user_input.keys:
                    for plugin in g_pool.plugins:
                        if plugin.on_key(key, scancode, action, mods):
                            break

                for char_ in user_input.chars:
                    for plugin in g_pool.plugins:
                        if plugin.on_char(char_):
                            break

                glfw.swap_buffers(main_window)

        session_settings["loaded_plugins"] = g_pool.plugins.get_initializers()
        session_settings["ui_config"] = g_pool.gui.configuration
        session_settings["version"] = str(g_pool.version)
        session_settings["eye0_process_alive"] = eye_procs_alive[0].value
        session_settings["eye1_process_alive"] = eye_procs_alive[1].value
        session_settings[
            "min_calibration_confidence"
        ] = g_pool.min_calibration_confidence
        session_settings["pupil_detection_enabled"] = g_pool.pupil_detection_enabled
        session_settings["audio_mode"] = audio.get_audio_mode()

        if not hide_ui:
            glfw.restore_window(main_window)  # need to do this for windows os
            session_settings["window_position"] = glfw.get_window_pos(main_window)
            session_window_size = glfw.get_window_size(main_window)
            if 0 not in session_window_size:
                f_width, f_height = session_window_size
                if platform.system() in ("Windows", "Linux"):
                    f_width, f_height = (
                        f_width / content_scale,
                        f_height / content_scale,
                    )
                session_settings["window_size"] = int(f_width), int(f_height)

        session_settings.close()

        # de-init all running plugins
        for p in g_pool.plugins:
            p.alive = False
        g_pool.plugins.clean()

        g_pool.gui.terminate()
        glfw.destroy_window(main_window)
        glfw.terminate()

    except Exception:
        import traceback

        trace = traceback.format_exc()
        logger.error("Process Capture crashed with trace:\n{}".format(trace))

    finally:
        # shut down eye processes:
        stop_eye_process(0)
        stop_eye_process(1)

        logger.info("Process shutting down.")
        ipc_pub.notify({"subject": "world_process.stopped"})
        sleep(1.0)
Esempio n. 40
0
def main():
    glfw.init()

    glfw.window_hint(glfw.RESIZABLE, False)
    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)

    w = glfw.create_window(800, 600, 'Window Title', None, None)

    glfw.make_context_current(w)

    ###############

    face = freetype.Face("/usr/share/fonts/TTF/IBMPlexSans-Regular.ttf")

    # Figure out DPI's of different monitors
    # Perhaps take these into account if you care, as well as window scale.
    # But what if your window is split across screens?
    for monitor in glfw.get_monitors():
        name = glfw.get_monitor_name(monitor).decode('utf8')
        pw, ph = glfw.get_monitor_physical_size(monitor)
        videomode = glfw.get_video_mode(monitor)  # in mm
        vw, vh = videomode.size.width, videomode.size.height
        # print(name, 25.4*vw/pw, 25.4*vh/ph) # convert to pixels per inch
        print(name, (1 / 72) * 25.4 * vw / pw,
              (1 / 72) * 25.4 * vh / ph)  # pixels per point

    # Set char size via physical size calculation
    # width, height in 1/64 of points
    # A point is one 1/72 of an inch. My monitors have 1.35 to 1.84 pixels per point.
    # Device resolution in dots per inch.
    # pixel_size = point_size * resolution / 72
    # face.set_char_size(width=16*64) #,height=0,hres=72,vres=72

    # Set size of EM square via pixels directly
    face.set_pixel_sizes(20, 0)
    baseline_height = 20 * face.height / face.units_per_EM
    print(baseline_height)

    ###############

    # disable byte-alignment restriction
    # normally, textures need to occupy a multiple of 4 in memory
    # but glyphs are single-color so they don't satisfy this
    glPixelStorei(GL_UNPACK_ALIGNMENT, 1)

    glyphs = {}
    for i in range(face.num_glyphs):
        face.load_glyph(i)  #flags=FT_LOAD_RENDER - renders glyph after loading

        texture = glGenTextures(1)

        # all of these numbers are pixels*64 by default
        # so divide by 64 to make these just pixels
        glyphs[i] = {
            "texture": texture,
            "w": face.glyph.metrics.width / 64,
            "h": face.glyph.metrics.height / 64,
            "hori": {
                "advance": face.glyph.metrics.horiAdvance / 64,
                "bearingX": face.glyph.metrics.horiBearingX / 64,
                "bearingY": face.glyph.metrics.horiBearingY / 64,
            },
            "vert": {
                "advance": face.glyph.metrics.vertAdvance / 64,
                "bearingX": face.glyph.metrics.vertBearingX / 64,
                "bearingY": face.glyph.metrics.vertBearingY / 64,
            }
        }

        bitmap = face.glyph.bitmap

        glBindTexture(GL_TEXTURE_2D, texture)
        glTexImage2D(GL_TEXTURE_2D, 0, GL_RED, bitmap.width, bitmap.rows, 0,
                     GL_RED, GL_UNSIGNED_BYTE, bitmap.buffer)
        # target, level, internalformat, width, height, border=0, format, type,data

        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S,
                        GL_CLAMP_TO_EDGE)  # these two seem
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T,
                        GL_CLAMP_TO_EDGE)  # to be optional
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
        glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

    ##################

    shaderProgram = make_shader_program()
    glUseProgram(shaderProgram)

    posParamsUniform = glGetUniformLocation(shaderProgram, "posParams")

    def set_pos(x, y, dx, dy):
        s = 1
        glUniform4f(posParamsUniform, s * x, s * y, s * dx, s * dy)
        # location, count, transpose, value

    vao = glGenVertexArrays(1)
    glBindVertexArray(vao)

    vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    # two triangles to make a rectangle
    # coordinates are in screen space
    # to get texture coordinates to x->x and y->1-y
    vertices = [0.0, 1.0] + [0.0,0.0] + [1.0,0.0] +\
                [0.0, 1.0] + [1.0,0.0] + [1.0,1.0]
    glBufferData(GL_ARRAY_BUFFER, len(vertices)*ctypes.sizeof(ctypes.c_float), \
            (ctypes.c_float*len(vertices))(*vertices), GL_STATIC_DRAW)

    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    glEnable(GL_BLEND)  # need this because the shader uses alphas
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)

    fbsize = {}
    fbsize["w"], fbsize["h"] = glfw.get_framebuffer_size(w)

    while not glfw.window_should_close(w):
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glClear(GL_COLOR_BUFFER_BIT)

        x, y = -1.0, 1.0
        y -= baseline_height * 2 / fbsize["h"]

        for i in range(face.num_glyphs):
            bx = glyphs[i]["hori"]["bearingX"] * 2 / fbsize["w"]
            by = glyphs[i]["hori"]["bearingY"] * 2 / fbsize["h"]
            width = glyphs[i]["w"] * 2 / fbsize["w"]
            height = glyphs[i]["h"] * 2 / fbsize["h"]

            set_pos(x + bx, y + by - height, width, height)

            x += glyphs[i]["hori"]["advance"] * 2 / fbsize["w"]

            glBindTexture(GL_TEXTURE_2D, glyphs[i]["texture"])
            glDrawArrays(GL_TRIANGLES, 0, 6)

            if i + 1 < face.num_glyphs:
                x += face.get_kerning(i, i + 1).x

                if x + glyphs[i +
                              1]["hori"]["advance"] * 2 / fbsize["w"] >= 1.0:
                    x = -1.0
                    y -= baseline_height * 2 / fbsize["h"]

            if y <= -1.0:
                break

        glfw.swap_buffers(w)
        glfw.poll_events()

    glDeleteBuffers(1, vbo)
    glDeleteVertexArrays(1, vao)

    glDeleteProgram(shaderProgram)

    glfw.terminate()
Esempio n. 41
0
def main():
    if not glfw.init():
        return

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

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)
    #           positions           colors
    quad = [    -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.5, 0.5, 0.0,      0.0, 0.0, 1.0
                -0.5, 0.5, 0.0,    1.0, 0.0, 1.0]

    quad = numpy.array(quad, dtype=numpy.float32)

    indices = [0, 1, 2,
               2, 3, 0]

    indices = numpy.array(indices, dtype=numpy.uint32)

    vertex_shader = """
    #version 410
    in vec3 position;
    in vec3 color;
    
    out vec3 newColor;
    void main()
    {
        gl_Position = vec4(position, 1.0f);
        newColor = color;
    }
    """
    fragment_shader = """
    #version 410
    in vec3 newColor;
    
    out vec4 outColor;
    void main()
    {
        outColor = vec4(newColor, 1.0f);
    }
    """
    shader = OpenGL.GL.shaders.compileProgram(OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
                                              OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, 96, quad, GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, 24, indices, GL_STATIC_DRAW)

    position = glGetAttribLocation(shader, "position")
    glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0))
    glEnableVertexAttribArray(position)

    color = glGetAttribLocation(shader, "color")
    glVertexAttribPointer(color, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12))
    glEnableVertexAttribArray(color)

    glUseProgram(shader)

    glClearColor(0.2, 0.3, 0.2, 1.0)

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

        glClear(GL_COLOR_BUFFER_BIT)

        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None)

        glfw.swap_buffers(window)

    glfw.terminate()
Esempio n. 42
0
def main():
    # glfw: initialize and configure
    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)

    # for Apple devices uncomment the following line
    # glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)

    # glfw: window creation
    window = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "Learn OpenGL", None,
                                None)
    if window is None:
        glfw.terminate()
        raise Exception("Failed to create GLFW window")

    glfw.make_context_current(window)
    glfw.set_framebuffer_size_callback(window, framebuffer_size_callback)

    # build and compile our shader program
    # vertex shader
    vertexShader = gl.glCreateShader(gl.GL_VERTEX_SHADER)
    gl.glShaderSource(
        vertexShader,
        vertexShaderSource)  # INFO: Changed method head in PyOpenGL
    gl.glCompileShader(vertexShader)

    # check for shader compile errors
    success = gl.glGetShaderiv(vertexShader, gl.GL_COMPILE_STATUS)
    if not success:
        info_log = gl.glGetShaderInfoLog(vertexShader, 512, None)
        raise Exception("ERROR::SHADER::VERTEX::COMPILATION_FAILED\n%s" %
                        info_log)

    # fragment shader
    fragmentShader = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
    gl.glShaderSource(fragmentShader, fragmentShaderSource)  # Changed!
    gl.glCompileShader(fragmentShader)

    # check for shader compile errors
    success = gl.glGetShaderiv(fragmentShader, gl.GL_COMPILE_STATUS)
    if not success:
        info_log = gl.glGetShaderInfoLog(fragmentShader, 512, None)
        raise Exception("ERROR::SHADER::FRAGMENT::COMPILATION_FAILED\n%s" %
                        info_log)

    # link shaders
    shaderProgram = gl.glCreateProgram()
    gl.glAttachShader(shaderProgram, vertexShader)
    gl.glAttachShader(shaderProgram, fragmentShader)
    gl.glLinkProgram(shaderProgram)

    # check for linking errors
    success = gl.glGetProgramiv(shaderProgram, gl.GL_LINK_STATUS)
    if not success:
        info_log = gl.glGetProgramInfoLog(shaderProgram, 512, None)
        raise Exception("ERROR::SHADER::PROGRAM::LINKING_FAILED\n%s" %
                        info_log)

    gl.glDeleteShader(vertexShader)
    gl.glDeleteShader(fragmentShader)

    # set up vertex data (and buffer(s)) and configure vertex attributes
    vertices = np.array(
        [
            0.5,
            0.5,
            0.0,  # left
            0.5,
            -0.5,
            0.0,  # right
            -0.5,
            -0.5,
            0.0,  # top
            -0.5,
            0.5,
            0.0
        ],
        dtype=np.float32)

    indices = np.array(
        [  # note that we start from 0!
            0,
            1,
            3,  # first triangle
            1,
            2,
            3  # second triangle
        ],
        dtype=np.int32
    )  # INFO: Stored as np.array with float32 for compatibility

    VAO = gl.glGenVertexArrays(1)
    VBO = gl.glGenBuffers(1)
    EBO = gl.glGenBuffers(1)
    # bind the Vertex Array Object first, then bind and set vertex buffer(s), and then configure vertex attributes(s).
    gl.glBindVertexArray(VAO)

    # store vertices in buffer
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, VBO)
    gl.glBufferData(gl.GL_ARRAY_BUFFER, vertices.nbytes, vertices,
                    gl.GL_STATIC_DRAW)  # INFO: use np.array with nsize

    # store indices in buffer
    gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, EBO)
    gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, indices.nbytes, indices,
                    gl.GL_STATIC_DRAW)
    # ToDo fix size of float
    gl.glVertexAttribPointer(
        0, 3, gl.GL_FLOAT, 3 * 4, 0,
        c_void_p(0))  # INFO: replaced (gl.void*)0 with c_void_p
    gl.glEnableVertexAttribArray(0)

    # note that this is allowed, the call to glVertexAttribPointer registered VBO as the vertex attribute's bound vertex buffer object so afterwards we can safely unbind
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)

    # You can unbind the VAO afterwards so other VAO calls won't accidentally modify this VAO, but this rarely happens. Modifying other
    # VAOs requires a call to glBindVertexArray anyways so we generally don't unbind VAOs (nor VBOs) when it's not directly necessary.
    gl.glBindVertexArray(0)

    gl.glPolygonMode(gl.GL_FRONT_AND_BACK,
                     gl.GL_LINE)  # for activating wireframe mode

    # main event loop
    while not glfw.window_should_close(window):
        # input
        process_input(window)

        # render
        gl.glClearColor(0.2, 0.3, 0.3, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        # draw our first triangle
        gl.glUseProgram(shaderProgram)
        gl.glBindVertexArray(VAO)
        gl.glDrawElements(gl.GL_TRIANGLES, 6, gl.GL_UNSIGNED_INT, None)
        # gl.glBindVertexArray(0) # no need to unbind it every time

        # glfw: swap buffers and poll IO events (keys pressed/released, mouse moved etc.)
        glfw.swap_buffers(window)
        glfw.poll_events()

    # optional: de-allocate all resources once they've outlived their purpose:
    gl.glDeleteVertexArrays(1, VAO)
    gl.glDeleteBuffers(1, VBO)
    gl.glDeleteBuffers(1, EBO)
    gl.glDeleteProgram(shaderProgram)

    # glfw: terminate, clearing all previously allocated GLFW resources.
    glfw.terminate()
    return 0
Esempio n. 43
0
    def __init__(
        self,
        g_pool,
        window_size=window_size_default,
        window_position=None,
        gui_scale=1.0,
        ui_config={},
    ):
        super().__init__(g_pool)

        self.texture = np.zeros((1, 1, 3), dtype=np.uint8) + 128

        glfw.init()
        glfw.window_hint(glfw.SCALE_TO_MONITOR, glfw.TRUE)
        if g_pool.hide_ui:
            glfw.window_hint(glfw.VISIBLE, 0)  # hide window

        main_window = glfw.create_window(*window_size, "Pupil Service", None,
                                         None)

        window_position_manager = gl_utils.WindowPositionManager()
        window_position = window_position_manager.new_window_position(
            window=main_window,
            default_position=window_position_default,
            previous_position=window_position,
        )
        glfw.set_window_pos(main_window, *window_position)

        glfw.make_context_current(main_window)
        cygl.utils.init()
        g_pool.main_window = main_window

        g_pool.gui = ui.UI()
        g_pool.menubar = ui.Scrolling_Menu("Settings",
                                           pos=(0, 0),
                                           size=(0, 0),
                                           header_pos="headline")
        g_pool.gui.append(g_pool.menubar)

        # Callback functions
        def on_resize(window, w, h):
            # Always clear buffers on resize to make sure that there are no overlapping
            # artifacts from previous frames.
            gl_utils.glClear(GL_COLOR_BUFFER_BIT)
            gl_utils.glClearColor(0, 0, 0, 1)

            self.window_size = w, h
            self.content_scale = gl_utils.get_content_scale(window)
            g_pool.gui.scale = self.content_scale
            g_pool.gui.update_window(w, h)
            g_pool.gui.collect_menus()

            # Needed, to update the window buffer while resizing
            self.update_ui()

        def on_window_key(window, key, scancode, action, mods):
            g_pool.gui.update_key(key, scancode, action, mods)

        def on_window_char(window, char):
            g_pool.gui.update_char(char)

        def on_window_mouse_button(window, button, action, mods):
            g_pool.gui.update_button(button, action, mods)

        def on_pos(window, x, y):
            x, y = gl_utils.window_coordinate_to_framebuffer_coordinate(
                window, x, y, cached_scale=None)
            g_pool.gui.update_mouse(x, y)

        def on_scroll(window, x, y):
            g_pool.gui.update_scroll(x, y * scroll_factor)

        def set_window_size():
            # Get default window size
            f_width, f_height = window_size_default

            # Get current display scale factor
            content_scale = gl_utils.get_content_scale(main_window)
            framebuffer_scale = gl_utils.get_framebuffer_scale(main_window)
            display_scale_factor = content_scale / framebuffer_scale

            # Scale the capture frame size by display scale factor
            f_width *= display_scale_factor
            f_height *= display_scale_factor

            # Set the newly calculated size (scaled capture frame size + scaled icon bar width)
            glfw.set_window_size(main_window, int(f_width), int(f_height))

        def reset_restart():
            logger.warning("Resetting all settings and restarting Capture.")
            glfw.set_window_should_close(main_window, True)
            self.notify_all({"subject": "clear_settings_process.should_start"})
            self.notify_all({
                "subject": "service_process.should_start",
                "delay": 2.0
            })

        g_pool.menubar.append(ui.Button("Reset window size", set_window_size))

        for *_, (ip, port, *_) in socket.getaddrinfo(
                "localhost",
                g_pool.preferred_remote_port,
                family=socket.AF_INET,
                type=socket.SOCK_STREAM,
        ):
            pupil_remote_addr = f"{ip}:{port}"
            break
        else:
            pupil_remote_addr = "unknown"

        g_pool.menubar.append(
            ui.Text_Input(
                "pupil_remote_addr",
                getter=lambda: pupil_remote_addr,
                setter=lambda x: None,
                label="Pupil Remote address",
            ))
        g_pool.menubar.append(
            ui.Switch(
                "eye0_process",
                label="Detect eye 0",
                setter=lambda alive: self.start_stop_eye(0, alive),
                getter=lambda: g_pool.eye_procs_alive[0].value,
            ))
        g_pool.menubar.append(
            ui.Switch(
                "eye1_process",
                label="Detect eye 1",
                setter=lambda alive: self.start_stop_eye(1, alive),
                getter=lambda: g_pool.eye_procs_alive[1].value,
            ))

        g_pool.menubar.append(
            ui.Info_Text("Service Version: {}".format(g_pool.version)))

        g_pool.menubar.append(
            ui.Button("Restart with default settings", reset_restart))

        # Register callbacks main_window
        glfw.set_framebuffer_size_callback(main_window, on_resize)
        glfw.set_key_callback(main_window, on_window_key)
        glfw.set_char_callback(main_window, on_window_char)
        glfw.set_mouse_button_callback(main_window, on_window_mouse_button)
        glfw.set_cursor_pos_callback(main_window, on_pos)
        glfw.set_scroll_callback(main_window, on_scroll)
        g_pool.gui.configuration = ui_config
        gl_utils.basic_gl_setup()

        on_resize(g_pool.main_window, *glfw.get_framebuffer_size(main_window))
Esempio n. 44
0
File: app.py Progetto: qwder/pyxel
    def __init__(self, module, width, height, caption, scale, palette, fps,
                 border_width, border_color):
        if glfw.get_version() < tuple(map(int, GLFW_VERSION.split('.'))):
            raise RuntimeError(
                'glfw version is lower than {}'.format(GLFW_VERSION))

        if width > APP_SCREEN_MAX_SIZE or height > APP_SCREEN_MAX_SIZE:
            raise ValueError('screen size is larger than {}x{}'.format(
                APP_SCREEN_MAX_SIZE, APP_SCREEN_MAX_SIZE))

        self._module = module
        self._palette = palette[:]
        self._pil_palette = self._get_pil_palette(palette)
        self._fps = fps
        self._border_width = border_width
        self._border_color = border_color
        self._next_update_time = 0
        self._one_frame_time = 1 / fps
        self._key_state = {}
        self._update = None
        self._draw = None
        self._capture_start = 0
        self._capture_index = 0
        self._capture_images = [None] * APP_GIF_CAPTURE_COUNT

        self._perf_monitor_is_enabled = False
        self._perf_fps_count = 0
        self._perf_fps_start_time = 0
        self._perf_fps = 0
        self._perf_update_count = 0
        self._perf_update_total_time = 0
        self._perf_update_time = 0
        self._perf_draw_count = 0
        self._perf_draw_total_time = 0
        self._perf_draw_time = 0

        module.width = width
        module.height = height
        module.mouse_x = 0
        module.mouse_y = 0
        module.frame_count = 0

        # initialize window
        if not glfw.init():
            exit()

        monitor = glfw.get_primary_monitor()
        display_width, display_height = glfw.get_video_mode(monitor)[0]

        if scale == 0:
            scale = max(
                min((display_width // width) - APP_SCREEN_SCALE_ADJUST,
                    (display_height // height) - APP_SCREEN_SCALE_ADJUST), 1)

        window_width = width * scale + border_width
        window_height = height * scale + border_width
        self._window = glfw.create_window(window_width, window_height, caption,
                                          None, None)

        if not self._window:
            glfw.terminate()
            exit()

        glfw.set_window_pos(self._window, (display_width - window_width) // 2,
                            (display_height - window_height) // 2)

        glfw.make_context_current(self._window)
        glfw.set_window_size_limits(self._window, width, height,
                                    glfw.DONT_CARE, glfw.DONT_CARE)
        self._hidpi_scale = (glfw.get_framebuffer_size(self._window)[0] /
                             glfw.get_window_size(self._window)[0])
        self._update_viewport()

        glfw.set_key_callback(self._window, self._key_callback)
        glfw.set_cursor_pos_callback(self._window, self._cursor_pos_callback)
        glfw.set_mouse_button_callback(self._window,
                                       self._mouse_button_callback)

        glfw.set_window_icon(self._window, 1, [self._get_icon_image()])

        # initialize renderer
        self._renderer = Renderer(width, height)

        # initialize audio player
        self._audio_player = AudioPlayer()

        # export module functions
        module.btn = self.btn
        module.btnp = self.btnp
        module.btnr = self.btnr
        module.run = self.run
        module.quit = self.quit
        module.image = self._renderer.image
        module.clip = self._renderer.draw_command.clip
        module.pal = self._renderer.draw_command.pal
        module.cls = self._renderer.draw_command.cls
        module.pix = self._renderer.draw_command.pix
        module.line = self._renderer.draw_command.line
        module.rect = self._renderer.draw_command.rect
        module.rectb = self._renderer.draw_command.rectb
        module.circ = self._renderer.draw_command.circ
        module.circb = self._renderer.draw_command.circb
        module.blt = self._renderer.draw_command.blt
        module.text = self._renderer.draw_command.text
        module.sound = self._audio_player.sound
        module.play = self._audio_player.play
        module.stop = self._audio_player.stop
Esempio n. 45
0
def main():

    #  glfw: initialize and configure
    # -------------------------------
    if not glfw.init():
        return

    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.SAMPLES, 4)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    # glfw window creation
    # --------------------
    screen_width = 800
    screen_height = 600
    window = glfw.create_window(screen_width, screen_height, "LearnOpenGL", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.set_framebuffer_size_callback(window, framebuffer_size_callback)

    glfw.make_context_current(window)

    # configure global opengl state
    # -----------------------------
    glEnable(GL_DEPTH_TEST)
    glDepthFunc(GL_LEQUAL)  # set depth function to less than AND equal for skybox depth trick.

    # build and compile shaders
    # -------------------------
    pbrShader = Shader(pbr_vertex_shader, pbr_fragment_shader)
    equirectangularToCubemapShader = Shader(cubemap_vertex_shader, cubemap_fragment_shader)
    backgroundShader = Shader(background_vertex_shader, background_fragment_shader)

    pbrShader.use()
    pbrShader.set_vec3("albedo", glm.vec3(0.5, 0.0, 0.0))
    pbrShader.set_float("ao", 1.0)

    backgroundShader.use()
    backgroundShader.set_int("environmentMap", 0)

    # lights
    # ------
    lightPositions = [glm.vec3(-10.0, 10.0, 10.0),
                      glm.vec3(10.0, 10.0, 10.0),
                      glm.vec3(-10.0, -10.0, 10.0),
                      glm.vec3(10.0, -10.0, 10.0)
                      ]

    lightColor = [glm.vec3(300.0, 300.0, 300.0),
                  glm.vec3(300.0, 300.0, 300.0),
                  glm.vec3(300.0, 300.0, 300.0),
                  glm.vec3(300.0, 300.0, 300.0)]

    nrRows = 7
    nrColumns = 7
    spacing = 2.5

    # pbr: setup framebuffer
    # ----------------------
    captureFBO = glGenFramebuffers(1)
    captureRBO = glGenRenderbuffers(1)

    glBindFramebuffer(GL_FRAMEBUFFER, captureFBO)
    glBindRenderbuffer(GL_RENDERBUFFER, captureRBO)
    glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, 512, 512)
    glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, captureRBO)

    # pbr: load the HDR environment map
    # ---------------------------------
    envmap = load_hdr(
        '/home/jack/Documents/_datasets/envmaps_reexposed_rotated/test/output-04-26-9C4A4385-9C4A4385_Panorama_hdr_inpainted-result_000.exr')
    hdrTexture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, hdrTexture)
    height, width = envmap.shape[0:2]
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB16F, width, height, 0, GL_RGB, GL_FLOAT, envmap)

    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

    # pbr: setup cubemap to render to and attach to framebuffer
    # ---------------------------------------------------------
    envCubemap = glGenTextures(1)
    glBindTexture(GL_TEXTURE_CUBE_MAP, envCubemap)
    for i in range(6):
        glTexImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, 0, GL_RGB16F, 512, 512, 0, GL_RGB, GL_FLOAT, None)

    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE)
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE)
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE)
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
    glTexParameteri(GL_TEXTURE_CUBE_MAP, GL_TEXTURE_MAG_FILTER, GL_LINEAR)

    # pbr: set up projection and view matrices for capturing data onto the 6 cubemap face directions
    # ----------------------------------------------------------------------------------------------
    captureProjection = glm.perspective(glm.radians(90.0), 1.0, 0.1, 10.0)
    captureViews = [glm.lookAt(glm.vec3(0.0, 0.0, 0.0), glm.vec3(1.0, 0.0, 0.0), glm.vec3(0.0, -1.0, 0.0)),
                    glm.lookAt(glm.vec3(0.0, 0.0, 0.0), glm.vec3(-1.0, 0.0, 0.0), glm.vec3(0.0, -1.0, 0.0)),
                    glm.lookAt(glm.vec3(0.0, 0.0, 0.0), glm.vec3(0.0, 1.0, 0.0), glm.vec3(0.0, 0.0, 1.0)),
                    glm.lookAt(glm.vec3(0.0, 0.0, 0.0), glm.vec3(0.0, -1.0, 0.0), glm.vec3(0.0, 0.0, -1.0)),
                    glm.lookAt(glm.vec3(0.0, 0.0, 0.0), glm.vec3(0.0, 0.0, 1.0), glm.vec3(0.0, -1.0, 0.0)),
                    glm.lookAt(glm.vec3(0.0, 0.0, 0.0), glm.vec3(0.0, 0.0, -1.0), glm.vec3(0.0, -1.0, 0.0))]

    # pbr: convert HDR equirectangular environment map to cubemap equivalent
    # ----------------------------------------------------------------------
    equirectangularToCubemapShader.use()
    equirectangularToCubemapShader.set_int("equirectangularMap", 0)
    equirectangularToCubemapShader.set_mat4("projection", captureProjection)
    glActiveTexture(GL_TEXTURE0)
    glBindTexture(GL_TEXTURE_2D, hdrTexture)

    glViewport(0, 0, 512, 512)
    glBindFramebuffer(GL_FRAMEBUFFER, captureFBO)
    cubeVBO = []

    for i in range(6):
        equirectangularToCubemapShader.set_mat4("view", captureViews[i])
        glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + i, envCubemap, 0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        renderCube(cubeVBO)

    glBindFramebuffer(GL_FRAMEBUFFER, 0)

    # initialize static shader uniforms before rendering
    # --------------------------------------------------
    projection = glm.perspective(glm.radians(140.0), screen_width / screen_height, 0.1, 100.0)
    pbrShader.use()
    pbrShader.set_mat4("projection", projection)
    backgroundShader.use()
    backgroundShader.set_mat4("projection", projection)

    # then before rendering, configure the viewport to the original framebuffer's screen dimensions
    scrWidth, scrHeight = glfw.get_framebuffer_size(window)
    glViewport(0, 0, scrWidth, scrHeight)
    skyboxVBO = []

    # render loop
    while not glfw.window_should_close(window):
        process_input(window)

        glClearColor(0.2, 0.3, 0.3, 1.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # render scene, supplying the convoluted irradiance map to the final shader.
        pbrShader.use()
        view = camera.GetViewMatrix()
        pbrShader.set_mat4("view", view)
        pbrShader.set_vec3("camPos", camera.position)

        # for row in range(nrRows):
        #     pbrShader.set_float("metallic", row/nrRows)
        #     for col in range(nrColumns):
        #         pbrShader.set_float("roughness", glm.clamp(col/nrColumns, 0.05, 1.0))
        #
        #         model = glm.mat4()
        #         model = glm.translate(model, glm.vec3((col-nrColumns/2)*spacing,
        #                                               (row-nrRows*2)*spacing,
        #                                               -2.0))
        #         pbrShader.set_mat4("model", model)
        #         renderSphere()

        # render skybox(render as last to prevent overdraw)
        backgroundShader.use()
        backgroundShader.set_mat4("view", view)
        glActiveTexture(GL_TEXTURE0)
        glBindTexture(GL_TEXTURE_CUBE_MAP, envCubemap)
        renderCube(skyboxVBO)

        # glfw: swap buffers and poll IO events(keys pressed / released, mouse movedetc.)
        # -------------------------------------------------------------------------------
        glfw.swap_buffers(window)
        glfw.poll_events()
Esempio n. 46
0
def main():
    # initialize glfw
    if not glfw.init():
        return

    w_width, w_height = 1280, 720
    aspect_ratio = w_width / w_height

    window = glfw.create_window(w_width, w_height, "My OpenGL window", None,
                                None)

    if not window:
        glfw.terminate()
        return

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

    #        positions        texture_coords
    cube = [
        -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 = numpy.array(cube, dtype=numpy.float32)

    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
    ]

    indices = numpy.array(indices, dtype=numpy.uint32)

    vertex_shader = """
    #version 330
    in layout(location = 0) vec3 position;
    in layout(location = 1) vec2 texture_cords;
    in layout(location = 2) float offset;
    uniform mat4 mvp;
    out vec2 textures;
    void main()
    {
        vec3 final_pos = vec3(position.x + offset, position.y + offset, position.z);
        gl_Position =  mvp * vec4(final_pos, 1.0f);
        textures = texture_cords;
    }
    """

    fragment_shader = """
    #version 330
    in vec2 textures;
    out vec4 color;
    uniform sampler2D tex_sampler;
    void main()
    {
        color = texture(tex_sampler, textures);
    }
    """
    shader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
        OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube,
                 GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices),
                 indices, GL_STATIC_DRAW)

    # position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 5,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

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

    # instances
    # instance_array = []
    # for i in range(0, 20, 1):
    #    instance_array.append(i)

    # instance_array = numpy.array(instance_array, numpy.float32)

    instance_array = numpy.array(numpy.arange(0, 20, 1), numpy.float32)

    instanceVBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, instanceVBO)
    glBufferData(GL_ARRAY_BUFFER,
                 instance_array.itemsize * len(instance_array), instance_array,
                 GL_STATIC_DRAW)

    glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, 0, ctypes.c_void_p(0))
    glEnableVertexAttribArray(2)
    glVertexAttribDivisor(2, 1)

    texture = TextureLoader.load_texture(
        "resources/images/planks_brown_10_diff_1k.jpg")

    glUseProgram(shader)

    glClearColor(0.2, 0.3, 0.2, 1.0)
    glEnable(GL_DEPTH_TEST)

    model = matrix44.create_from_translation(Vector3([-14.0, -8.0, 0.0]))
    view = matrix44.create_from_translation(Vector3([0.0, 0.0, -20.0]))
    projection = matrix44.create_perspective_projection_matrix(
        45.0, aspect_ratio, 0.1, 100.0)

    mv = matrix44.multiply(model, view)
    mvp = matrix44.multiply(mv, projection)

    mvp_loc = glGetUniformLocation(shader, "mvp")
    glUniformMatrix4fv(mvp_loc, 1, GL_FALSE, mvp)

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

        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        glDrawElementsInstanced(GL_TRIANGLES, len(indices), GL_UNSIGNED_INT,
                                None, 20)

        glfw.swap_buffers(window)

    glfw.terminate()
Esempio n. 47
0
def main():

    # declare draw method so it can be reused during resizing
    def draw():
        gl.glClearColor(0.2, 0.3, 0.3, 1.0)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT)

        shaderProgram.use()

        vao.bind()

        # update shader uniform
        timeValue = glfw.get_time()
        greenValue = np.sin(timeValue) / 2.0 + 0.5
        vertexColorLocation = gl.glGetUniformLocation(shaderProgram.Program,
                                                      "ourColor")
        gl.glUniform4f(vertexColorLocation, 0.0, greenValue, 0.0, 1.0)

        gl.glDrawElements(gl.GL_TRIANGLES, 3 * indices.shape[0],
                          gl.GL_UNSIGNED_INT, None)

        vao.unbind()

        glfw.swap_buffers(window)

    # declaring resize callback in main to allow access to variables
    def window_size_callback(window, width, height):
        gl.glViewport(0, 0, width, height)
        # calling draw to allow drawing while resizing
        draw()

    # glfw: initialize and configure

    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)  # No deprecated functions
    glfw.window_hint(glfw.RESIZABLE, gl.GL_TRUE)

    # checking if run on Mac OS X
    if sys.platform == 'darwin':
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)

    # glfw window creation
    window = glfw.create_window(WIDTH, HEIGHT, 'LearnOpenGL', None,
                                None)  # tutorial: (800, 600...
    if window is None:
        glfw.terminate()
        raise Exception("ERROR: Failed to create GLFW window")

    glfw.make_context_current(window)

    glfw.set_key_callback(window, key_callback)

    width, height = glfw.get_framebuffer_size(window)
    glfw.set_window_size_callback(window, window_size_callback)

    shaderProgram = ShaderProgram(vertexShaderSource, fragmentShaderSource)

    # set up vertex data (and buffer(s)) and configure vertex attributes

    vertices = np.array(
        [
            [0.5, -0.5, 0.0, 1.0, 0.0, 0.0],  # bottom right
            [-0.5, -0.5, 0.0, 0.0, 1.0, 0.0],  # bottom left
            [0.0, 0.5, 0.0, 0.0, 0.0, 1.0]
        ],  # top   
        dtype=np.float32)

    indices = np.array([[0, 1, 2]], dtype=np.int32)

    vao = VAO()
    vbo = VBO(vertices)
    ebo = EBO(indices)

    stride = vertices.itemsize * vertices.shape[1]
    offset0 = gl.ctypes.c_void_p(vertices.itemsize * 0)
    offset1 = gl.ctypes.c_void_p(vertices.itemsize * 3)

    gl.glVertexAttribPointer(0, 3, gl.GL_FLOAT, gl.GL_FALSE, stride, offset0)
    gl.glEnableVertexAttribArray(0)  # location = 0

    gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, stride, offset1)
    gl.glEnableVertexAttribArray(1)  # location = 1

    vbo.unbind()
    vao.unbind()
    ebo.unbind()

    # to put in wireframe mode
    # gl.glPolygonMode(gl.GL_FRONT_AND_BACK, gl.GL_LINE)

    # render loop
    while not glfw.window_should_close(window):
        glfw.poll_events()

        draw()

    del vbo, ebo, vao
    glfw.terminate()

    return 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/2.2.basic_lighting.vs",
                             CURDIR / "shaders/2.2.basic_lighting.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("objectColor", Vector3([1.0, 0.5, 0.31]))
        lighting_shader.set_vec3("lightColor", Vector3([1.0, 1.0, 1.0]))
        lighting_shader.set_vec3("lightPos", light_pos)
        lighting_shader.set_vec3("viewPos", camera.position)

        # -- 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()
Esempio n. 49
0
    def test(config):

        import time

        W, H = 640, 360
        glfw.init()
        win = glfw.create_window(W, H, "Mesh Object", None, None)
        glfw.make_context_current(win)

        meshShader = MeshObject.getShader()

        vertexMat4 = np.array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
                              dtype=np.float32).reshape((4, 4))
        normalMat4 = np.array([1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1],
                              dtype=np.float32).reshape((4, 4))
        vertices = np.array([
            -0.5,
            -0.5,
            0.5,
            1.0,
            0.5,
            0.5,
            0.5,
            1.0,
            0.5,
            -0.5,
            0.5,
            1.0,
            0.5,
            -0.5,
            -0.5,
            1.0,
        ],
                            dtype=np.float32)
        normals = np.array([
            0.0,
            0.0,
            1.0,
            1.0,
            0.0,
            1.0,
            1.0,
            0.0,
            1.0,
            1.0,
            0.0,
            0.0,
        ],
                           dtype=np.float32)
        indices = np.array([0, 1, 2, 1, 2, 3], dtype=np.uint32)

        meshObject = MeshObject(
            [123456789, vertexMat4, normalMat4, vertices, normals, indices])

        glUseProgram(meshShader)
        projection = glm.perspective(glm.radians(75), W / H, 0.25, 5.0)
        glUniformMatrix4fv(meshShader.uProjection, 1, False,
                           glm.value_ptr(projection))

        rotation = glm.mat4()

        glClearColor(0.1, 0.3, 0.4, 1.0)
        glEnable(GL_DEPTH_TEST)
        while not glfw.window_should_close(win):

            start = time.time()
            rotation = glm.rotate(rotation, glm.radians(45 / 30), (0, 1, 0))

            modelview = glm.mat4()
            modelview = glm.translate(modelview, (0, 0, -1.5))
            modelview = modelview * rotation

            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
            glUseProgram(meshShader)
            glUniformMatrix4fv(meshShader.uModelview, 1, False,
                               glm.value_ptr(modelview))
            meshObject.draw(meshShader)

            glfw.swap_buffers(win)
            glfw.poll_events()

            tic = time.time() - start
            delay = 1 / 30 - tic
            if delay > 0:
                time.sleep(delay)

        glfw.terminate()
def main():

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

    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)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)

    w_width, w_height = 800, 600

    window = glfw.create_window(w_width, w_height, "My OpenGL window", None, None)

    if not window:
        glfw.terminate()
        return

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

    #        positions         colors          texture coords
    cube = [-0.5, -0.5,  0.5,  1.0, 0.0, 0.0,  0.0, 0.0,
             0.5, -0.5,  0.5,  0.0, 1.0, 0.0,  1.0, 0.0,
             0.5,  0.5,  0.5,  0.0, 0.0, 1.0,  1.0, 1.0,
            -0.5,  0.5,  0.5,  1.0, 1.0, 1.0,  0.0, 1.0,

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

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

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

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

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

    cube = numpy.array(cube, dtype = numpy.float32)

    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]

    indices = numpy.array(indices, dtype= numpy.uint32)

    VAO = glGenVertexArrays(1)
    glBindVertexArray(VAO)

    shader = ShaderLoader.compile_shader("shaders/video_14_vert.vs", "shaders/video_14_frag.fs")

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, cube.itemsize * len(cube), cube, GL_STATIC_DRAW)

    EBO = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, indices.itemsize * len(indices), indices, GL_STATIC_DRAW)

    #position
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 8, ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)
    #color
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, cube.itemsize * 8, ctypes.c_void_p(12))
    glEnableVertexAttribArray(1)
    #texture
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, cube.itemsize * 8, ctypes.c_void_p(24))
    glEnableVertexAttribArray(2)

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

    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("res/crate.jpg")
    img_data = numpy.array(list(image.getdata()), numpy.uint8)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, image.width, image.height, 0, GL_RGB, GL_UNSIGNED_BYTE, img_data)
    
    glClearColor(0.2, 0.3, 0.2, 1.0)
    glEnable(GL_DEPTH_TEST)
    

    view = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0, -3.0]))
    projection = pyrr.matrix44.create_perspective_projection_matrix(45.0, w_width / w_height, 0.1, 100.0)
    model = pyrr.matrix44.create_from_translation(pyrr.Vector3([0.0, 0.0, 0.0]))

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

    glUniformMatrix4fv(view_loc, 1, GL_FALSE, view)
    glUniformMatrix4fv(proj_loc, 1, GL_FALSE, projection)
    glUniformMatrix4fv(model_loc, 1, GL_FALSE, model)
    glUseProgram(0)

    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() )

        glUseProgram(shader)

        transformLoc = glGetUniformLocation(shader, "transform")
        glUniformMatrix4fv(transformLoc, 1, GL_FALSE, rot_x * rot_y)

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

        glUseProgram(0)
        glfw.swap_buffers(window)

    glDeleteProgram(shader)
    glDeleteVertexArrays(1, [VAO])
    glDeleteBuffers(2, [VBO, EBO])
    
    glfw.terminate()
Esempio n. 51
0
def main():
    # 以下初始化glfw和窗口
    if not glfw.init():
        return

    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)

    # 新建窗口
    window = glfw.create_window(width, height, "Hello Window", None, None)
    if not window:
        glfw.terminate()
        return

    # 设置context
    glfw.make_context_current(window)
    glfw.set_window_size_callback(window, resize_callback)
    ctx = moderngl.create_context(require=410)

    # 顶点数组
    vertices = numpy.array([0, 0, 0.0, 0.5, -0.5, 0.0, 0.0, 0.5, 0.0],
                           dtype='f4')

    # 建立vbo
    vbo = ctx.buffer(vertices.tobytes())

    # 顶点index
    indice = numpy.array([0, 1, 2], dtype='u4')
    ebo = ctx.buffer(indice.tobytes())

    # 读取shader
    f = open('shaders/transform.vert')
    vert = f.read()
    f.close()

    f = open('shaders/orange.frag')
    frag = f.read()
    f.close()

    # 编译shader
    program = ctx.program(vertex_shader=vert, fragment_shader=frag)

    angle = 0

    # 建立vao
    vao = ctx.simple_vertex_array(program, vbo, 'aPos', index_buffer=ebo)

    # 主循环
    while not glfw.window_should_close(window):
        process_input(window)

        ctx.viewport = (0, 0, width, height
                        )  # 这个就是glViewport(),设置opengl的窗口大小,不设置其实也无所谓
        ctx.clear(0.2, 0.3, 0.3, 1.0)

        angle += math.pi / 180

        trans = mat.rotate(angle, 0, 0, 1)
        program['transform'].write(trans.tobytes())

        vao.render()

        glfw.poll_events()
        glfw.swap_buffers(window)

    glfw.terminate()
Esempio n. 52
0
import glfw

if not glfw.init():
    sys.exit()

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

window = glfw.create_window(500, 500, "ModelViewProjection Demo 12", None,
                            None)
if not window:
    glfw.terminate()
    sys.exit()

# Make the window's context current
glfw.make_context_current(window)


# Install a key handler
def on_key(window, key, scancode, action, mods):
    if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
        glfw.set_window_should_close(window, 1)


glfw.set_key_callback(window, on_key)

glClearColor(0.0, 0.0, 0.0, 1.0)

glMatrixMode(GL_PROJECTION)
glLoadIdentity()
glMatrixMode(GL_MODELVIEW)
Esempio n. 53
0
def main():
    # initialize glfw
    if not glfw.init():
        return

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

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    triangle = [-0.5, -0.5, 0.0, 0.5, -0.5, 0.0, 0.0, 0.5, 0.0]

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

    vertex_shader = """
    #version 330
    uniform vec3 current_color;
    out vec3 out_color
    
    void main()
    {
        gl_Position = position;
        out_color = current_color;
    }
    """

    fragment_shader = """
    #version 330
    in out_color;
    out frag_color;
    
    void main()
    {
        frag_color = out_color;
    }
    """
    shader = OpenGL.GL.shaders.compileProgram(
        OpenGL.GL.shaders.compileShader(vertex_shader, GL_VERTEX_SHADER),
        OpenGL.GL.shaders.compileShader(fragment_shader, GL_FRAGMENT_SHADER))

    VBO = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, VBO)
    glBufferData(GL_ARRAY_BUFFER, 36, triangle, GL_DYNAMIC_DRAW)

    position = glGetAttribLocation(shader, "position")
    glVertexAttribPointer(position, 3, GL_FLOAT, GL_FALSE, 0, None)
    glEnableVertexAttribArray(position)

    glUseProgram(shader)

    glClearColor(0.2, 0.3, 0.2, 1.0)
    while not glfw.window_should_close(window):
        glfw.poll_events()
        glfw.swap_buffers(window)
        glClear(GL_COLOR_BUFFER_BIT)

        glDrawArrays(GL_TRIANGLES, 0, 3)

    glfw.terminate()
Esempio n. 54
0
def main():
    # initialize glfw
    if not glfw.init():
        return

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

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    vertices = [
        0.5, 0.5, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.5, -0.5, 0.0, 0.0, 1.0, 0.0,
        1.0, 0.0, -0.5, -0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, -0.5, 0.5, 0.0,
        1.0, 1.0, 0.0, 0.0, 1.0
    ]
    vertices = np.array(vertices, dtype=np.float32)

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

    im = open('../textures/container.jpg')
    width, height, image = im.size[0], im.size[1], im.tobytes(
        "raw", "RGB", 0, -1)
    im.close()
    texture = glGenTextures(1)
    glBindTexture(GL_TEXTURE_2D, texture)
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB,
                 GL_UNSIGNED_BYTE, image)
    glGenerateMipmap(GL_TEXTURE_2D)

    vertex_shader = """
    #version 330 core
    layout (location = 0) in vec3 aPos;   // the position variable has attribute position 0
    layout (location = 1) in vec3 aColor; // the color variable has attribute position 1
    layout (location = 2) in vec2 aTexCoord;
      
    out vec3 ourColor; // output a color to the fragment shader
    out vec2 TexCoord;
    
    void main()
    {
        gl_Position = vec4(aPos, 1.0);
        ourColor = aColor; // set ourColor to the input color we got from the vertex data
        TexCoord = aTexCoord;
    }  
    """

    fragment_shader = """
    #version 330 core
    out vec4 FragColor;  
    in vec3 ourColor;
    in vec2 TexCoord;
    
    uniform sampler2D ourTexture;
      
    void main()
    {
        // FragColor = texture(ourTexture, TexCoord);
        FragColor = texture(ourTexture, TexCoord) * vec4(ourColor, 1.0);
    }
    """

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

    VAO = glGenVertexArrays(1)
    VBO = glGenBuffers(
        1)  # vertex buffer object, which stores vertices in the GPU's memory.
    EBO = glGenBuffers(1)  # Element Buffer Object
    glBindVertexArray(VAO)

    glBindBuffer(GL_ARRAY_BUFFER, VBO)  # now, all calls will configure VBO
    glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices,
                 GL_STATIC_DRAW)  # copy user-defined data into VBO

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

    # position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT,
                          GL_FALSE, 8 * np.dtype(np.float32).itemsize,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    # color attribute
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,
                          8 * np.dtype(np.float32).itemsize,
                          ctypes.c_void_p(3 * np.dtype(np.float32).itemsize))
    glEnableVertexAttribArray(1)

    # texture attribute
    glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE,
                          8 * np.dtype(np.float32).itemsize,
                          ctypes.c_void_p(6 * np.dtype(np.float32).itemsize))
    glEnableVertexAttribArray(2)

    glBindBuffer(GL_ARRAY_BUFFER, 0)

    glBindVertexArray(0)

    glfw.set_framebuffer_size_callback(window, framebuffer_size_callback)

    # render loop
    while not glfw.window_should_close(window):
        # input
        process_input(window)

        # rendering commands here
        glClearColor(0.2, 0.3, 0.3, 1.0)  # state-setting function
        glClear(GL_COLOR_BUFFER_BIT)  # state-using function

        # render triangle
        timeValue = glfw.get_time()
        greenValue = (np.sin(timeValue) / 2.0) + 0.5
        vertexColorLocation = glGetUniformLocation(shader, "ourColor")
        glUseProgram(shader)
        glUniform4f(vertexColorLocation, 0.0, greenValue, 0.0, 1.0)
        glBindTexture(GL_TEXTURE_2D, texture)
        glBindVertexArray(VAO)
        glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_INT, None)

        # check and call events and swap the buffers
        glfw.swap_buffers(window)
        glfw.poll_events()
    glfw.terminate()
Esempio n. 55
0
def main():
    global delta_time, last_frame

    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(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/5.4.light_casters.vs", CURDIR / "shaders/5.4.light_casters.fs")

    vertices = [
        # positions        normals           texture coords
        -0.5, -0.5, -0.5,  0.0,  0.0, -1.0,  0.0,  0.0,
         0.5, -0.5, -0.5,  0.0,  0.0, -1.0,  1.0,  0.0,
         0.5,  0.5, -0.5,  0.0,  0.0, -1.0,  1.0,  1.0,
         0.5,  0.5, -0.5,  0.0,  0.0, -1.0,  1.0,  1.0,
        -0.5,  0.5, -0.5,  0.0,  0.0, -1.0,  0.0,  1.0,
        -0.5, -0.5, -0.5,  0.0,  0.0, -1.0,  0.0,  0.0,

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

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

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

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

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

    cube_positions = [
        ( 0.0,  0.0,  0.0),
        ( 2.0,  5.0, -15.0),
        (-1.5, -2.2, -2.5),
        (-3.8, -2.0, -12.3),
        ( 2.4, -0.4, -3.5),
        (-1.7,  3.0, -7.5),
        ( 1.3, -2.0, -2.5),
        ( 1.5,  2.0, -2.5),
        ( 1.5,  0.2, -1.5),
        (-1.3,  1.0, -1.5)
    ]

    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, 8 * sizeof(c_float), c_void_p(0))
    gl.glEnableVertexAttribArray(0)
    # -- normal attribute
    gl.glVertexAttribPointer(1, 3, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(3 * sizeof(c_float)))
    gl.glEnableVertexAttribArray(1)
    # -- texture coordinate
    gl.glVertexAttribPointer(2, 2, gl.GL_FLOAT, gl.GL_FALSE, 8 * sizeof(c_float), c_void_p(6 * sizeof(c_float)))
    gl.glEnableVertexAttribArray(2)

    # -- 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, 8 * sizeof(c_float), c_void_p(0))
    gl.glEnableVertexAttribArray(0)

    # -- load texture
    diffuse_map = load_texture("container2.png")
    specular_map = load_texture("container2_specular.png")

    # -- shader configuration
    lighting_shader.use()
    lighting_shader.set_int("material.diffuse", 0)
    lighting_shader.set_int("material.specular", 1)

    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", camera.position)
        lighting_shader.set_vec3("light.direction", camera.front)
        lighting_shader.set_float("light.cutOff", math.cos(math.radians(12.5)))
        lighting_shader.set_float("light.outerCutOff", math.cos(math.radians(17.5)))
        lighting_shader.set_vec3("viewPos", camera.position)

        # -- light properties
        lighting_shader.set_vec3("light.ambient", Vector3([0.1, 0.1, 0.1]))
        # we configure the diffuse intensity slightly higher; the right lighting conditions differ with each lighting method and environment.
        # each environment and lighting type requires some tweaking to get the best out of your environment.
        lighting_shader.set_vec3("light.diffuse", Vector3([0.8, 0.8, 0.8]))
        lighting_shader.set_vec3("light.specular", Vector3([1.0, 1.0, 1.0]))
        lighting_shader.set_float("light.constant", 1.0)
        lighting_shader.set_float("light.linear", 0.09)
        lighting_shader.set_float("light.quadratic", 0.032)

        # -- material properties
        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)

        # -- bind diffuse map
        gl.glActiveTexture(gl.GL_TEXTURE0)
        gl.glBindTexture(gl.GL_TEXTURE_2D, diffuse_map)

        # -- bind specular map
        gl.glActiveTexture(gl.GL_TEXTURE1)
        gl.glBindTexture(gl.GL_TEXTURE_2D, specular_map)

        # -- render continers
        gl.glBindVertexArray(cube_vao)
        for idx, position in enumerate(cube_positions):
            angle = 20.0 * idx
            rotation = matrix44.create_from_axis_rotation([1.0, 0.3, 0.5], math.radians(angle))
            translation = Matrix44.from_translation(position)
            model = translation * rotation
            lighting_shader.set_mat4('model', model)
            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()
Esempio n. 56
0
def main():
    # initialize glfw
    if not glfw.init():
        return

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

    trans = glm.mat4(1.0)
    trans = glm.rotate(trans, glm.radians(90.0), glm.vec3(0.0, 0.0, 1.0))
    trans = glm.scale(trans, glm.vec3(0.5, 0.5, 0.5))

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    vertices = [
        -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,
    ]
    vertices = np.array(vertices, dtype=np.float32)

    vertex_shader = """
    #version 330 core
    layout (location = 0) in vec3 aPos;   // the position variable has attribute position 0
    layout (location = 1) in vec3 aColor; // the color variable has attribute position 1
      
    out vec3 ourColor; // output a color to the fragment shader
    uniform mat4 transform;
    
    void main()
    {
        gl_Position = transform * vec4(aPos, 1.0);
        ourColor = aColor; // set ourColor to the input color we got from the vertex data
    }  
    """

    fragment_shader = """
    #version 330 core
    out vec4 FragColor;  
    in vec3 ourColor;
      
    void main()
    {
        FragColor = vec4(ourColor, 1.0);
    }
    """

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

    VAO = glGenVertexArrays(1)
    VBO = glGenBuffers(
        1)  # vertex buffer object, which stores vertices in the GPU's memory.
    glBindVertexArray(VAO)

    glBindBuffer(GL_ARRAY_BUFFER, VBO)  # now, all calls will configure VBO
    glBufferData(GL_ARRAY_BUFFER, vertices.nbytes, vertices,
                 GL_STATIC_DRAW)  # copy user-defined data into VBO

    # position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT,
                          GL_FALSE, 6 * np.dtype(np.float32).itemsize,
                          ctypes.c_void_p(0))
    glEnableVertexAttribArray(0)

    # color attribute
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,
                          6 * np.dtype(np.float32).itemsize,
                          ctypes.c_void_p(3 * np.dtype(np.float32).itemsize))
    glEnableVertexAttribArray(1)

    glBindBuffer(GL_ARRAY_BUFFER, 0)

    glBindVertexArray(0)

    glfw.set_framebuffer_size_callback(window, framebuffer_size_callback)

    # render loop
    while not glfw.window_should_close(window):
        # input
        process_input(window)

        # rendering commands here
        glClearColor(0.2, 0.3, 0.3, 1.0)  # state-setting function
        glClear(GL_COLOR_BUFFER_BIT)  # state-using function

        # render triangle
        timeValue = glfw.get_time()
        greenValue = (np.sin(timeValue) / 2.0) + 0.5
        vertexColorLocation = glGetUniformLocation(shader, "ourColor")
        glUseProgram(shader)
        glUniform4f(vertexColorLocation, 0.0, greenValue, 0.0,
                    1.0)  # uniforms must be performed after glUseProgram
        transformLoc = glGetUniformLocation(shader, "transform")
        glUniformMatrix4fv(transformLoc, 1, GL_FALSE, glm.value_ptr(trans))
        glBindVertexArray(VAO)
        glDrawArrays(GL_TRIANGLES, 0, 3)

        # check and call events and swap the buffers
        glfw.swap_buffers(window)
        glfw.poll_events()
    glfw.terminate()
Esempio n. 57
0
    def __init__(self):
        if not glfw.init():
            return

        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 2)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)

        window = glfw.create_window(self.WIDTH, self.HEIGHT, self.TITLE, None,
                                    None)
        glfw.set_window_size_limits(window, 320, 480, glfw.DONT_CARE,
                                    glfw.DONT_CARE)
        if not window:
            glfw.terminate()
            return

        glfw.make_context_current(window)
        glfw.set_key_callback(window, self.key_callback)
        glfw.set_window_size_callback(window, self.reshape)

        width, height = glfw.get_framebuffer_size(window)
        glViewport(0, 0, width, height)
        aspect_ratio = width / height

        glClearColor(0.2, 0.3, 0.2, 1.0)
        glEnable(GL_DEPTH_TEST)

        self.ball = Ball(TEXTILE_TEXTURE)
        ball_shader = Shader(BASE_VS, BASE_FS)
        self.ball.prep(ball_shader, aspect_ratio, 0.5, 85)

        self.platform = Platform(BUCKET_TEXTURE)
        shader = Shader(BASE_VS, BASE_FS)
        self.platform.prep(shader, aspect_ratio, 1.0, 85)

        self.Vidass = []
        for i in range(0, self.MAX_FAIL):
            Vidas = LiveVidas([-3.0 + i * 0.5, 5.5, 0.0])
            Vidas_shader = Shader(Vidas_VS, Vidas_FS)
            Vidas.prep(Vidas_shader, aspect_ratio, 0.3, 85)
            self.Vidass.append(Vidas)

        self.bg = Background(WOOD_TEXTURE)
        bg_shader = Shader(BASE_VS, BASE_FS)
        self.bg.prep(bg_shader, aspect_ratio, 11.0, 85)

        while not glfw.window_should_close(window):
            glClearColor(0.0, 0.3, 0.3, 1.0)
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

            glDisable(GL_DEPTH_TEST)
            self.bg.draw()
            glEnable(GL_DEPTH_TEST)

            self.platform.draw(self.game_status_play)
            self.ball.draw(self.game_status_play)

            if self.collision_detect():
                if self.fails == self.MAX_FAIL:
                    self.game_status_play = False

            for Vidas in self.Vidass:
                Vidas.draw()

            glfw.swap_buffers(window)
            glfw.poll_events()

        glfw.terminate()
Esempio n. 58
0
    def render(self):

        # Glfw settings
        glfw.window_hint(glfw.SAMPLES, 4)
        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)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)

        # Create a windowed mode window and its OpenGL context
        window = glfw.create_window(self.w, self.h, self.wname, None, None)
        if not window:
            glfw.terminate()
            return

        # Make the window's context current
        glfw.make_context_current(window)

        # Glfw callbacks
        glfw.set_scroll_callback(window, self.mouse_scroll_callback)
        glfw.set_mouse_button_callback(window, self.mouse_button_callback)
        glfw.set_window_size_callback(window, self.window_resize_callback)
        glfw.set_key_callback(window, self.key_callback)

        # OpenGL settings
        glEnable(GL_DEPTH_TEST)
        glEnable(GL_LINE_SMOOTH)
        glEnable(GL_POLYGON_OFFSET_FILL)
        glClearColor(1.0, 1.0, 1.0, 1.0)
        glClearDepth(1.0)
        glDepthFunc(GL_LESS)
        glPolygonOffset(1.0, 1.0)
        glPolygonMode(GL_FRONT_AND_BACK, GL_FILL)

        # Create shader program
        program = glCreateProgram(1)

        # Vertex shader
        with open(VIEWER_DIR + "shaders/mesh.vert.glsl", 'r') as VS_file:
            VS = VS_file.read()
        vshader = glCreateShader(GL_VERTEX_SHADER)
        glShaderSource(vshader, VS)
        glCompileShader(vshader)
        glAttachShader(program, vshader)

        # Fragment shader
        with open(VIEWER_DIR + "shaders/mesh.frag.glsl", 'r') as FS_file:
            FS = FS_file.read()
        fshader = glCreateShader(GL_FRAGMENT_SHADER)
        glShaderSource(fshader, FS)
        glCompileShader(fshader)
        glAttachShader(program, fshader)

        # Link shader program
        glLinkProgram(program)

        # Detach and delete shaders
        glDetachShader(program, vshader)
        glDetachShader(program, fshader)
        glDeleteShader(vshader)
        glDeleteShader(fshader)

        # Get program locations
        self.location = lambda: 0
        self.location.model = glGetUniformLocation(program, 'model')
        self.location.view = glGetUniformLocation(program, 'view')
        self.location.nmat = glGetUniformLocation(program, 'nmat')
        self.location.proj = glGetUniformLocation(program, 'proj')
        self.location.cmode = glGetUniformLocation(
            program, 'cmode')  # 0 uniform 1 fixed 2 normals

        # Scale to uniform length
        diag = self.verts.max(0) - self.verts.min(0)
        aabb = np.linalg.norm(diag)
        if aabb > 0:
            self.scale = 1. / aabb

        # Snap to centroid
        self.verts -= 0.5 * (self.verts.max(0) + self.verts.min(0))

        # Compute per-vertex normals
        self.nrmls = per_vertex_normals(self.verts, self.faces)

        # Recompute Model, View, Projection matrices
        self.recompute_matrices()

        # Generate vertex arrays
        self.vao = glGenVertexArrays(1)
        glBindVertexArray(self.vao)

        # Generate vertex buffers
        self.vbo = glGenBuffers(4)

        # 0 : position
        glBindBuffer(GL_ARRAY_BUFFER, self.vbo[0])
        glBufferData(GL_ARRAY_BUFFER, self.verts.size * self.verts.itemsize,
                     self.verts, GL_STATIC_DRAW)

        # 1 : normals
        glBindBuffer(GL_ARRAY_BUFFER, self.vbo[1])
        glBufferData(GL_ARRAY_BUFFER, self.nrmls.size * self.nrmls.itemsize,
                     self.nrmls, GL_STATIC_DRAW)

        # 2 : face indices
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.vbo[2])
        glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                     self.faces.size * self.faces.itemsize, self.faces,
                     GL_STATIC_DRAW)

        # 3 : edge indices
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.vbo[3])
        glBufferData(GL_ELEMENT_ARRAY_BUFFER,
                     self.edges.size * self.edges.itemsize, self.edges,
                     GL_STATIC_DRAW)

        # Loop until the user closes the window
        while not glfw.window_should_close(window) and glfw.get_key(
                window, glfw.KEY_ESCAPE) != glfw.PRESS:

            # Change rotation
            if self.rotate:
                xpos, ypos = glfw.get_cursor_pos(window)
                if self.xpos != xpos or self.ypos != ypos:

                    # azimuth
                    self.az -= 10 * (self.xpos - xpos) / self.w
                    # elevation
                    self.el -= 10 * (self.ypos - ypos) / self.h

                    # store new mouse coords
                    self.xpos = xpos
                    self.ypos = ypos

                    # recompute MVP matrices
                    self.recompute_matrices()

            # Clear the buffers
            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

            # Use our shader program
            glUseProgram(program)

            # Set uniforms
            glUniformMatrix4fv(self.location.model, 1, True, self.model)
            glUniformMatrix4fv(self.location.view, 1, True, self.view)
            glUniformMatrix4fv(self.location.nmat, 1, True, self.nmat)
            glUniformMatrix4fv(self.location.proj, 1, True, self.proj)

            # Enable vertex arrays
            glEnableVertexAttribArray(0)
            glEnableVertexAttribArray(1)

            # 0 : positions
            glBindBuffer(GL_ARRAY_BUFFER, self.vbo[0])
            glVertexAttribPointer(0, 3, GL_FLOAT, False, 0, None)

            # 1 : normals
            glBindBuffer(GL_ARRAY_BUFFER, self.vbo[1])
            glVertexAttribPointer(1, 3, GL_FLOAT, False, 0, None)

            # Draw wireframe
            if self.wire:
                # Bind element buffer
                glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.vbo[3])
                glUniform1i(self.location.cmode, 1)
                glDrawElements(GL_LINES, self.edges.size, GL_UNSIGNED_INT,
                               None)

            # Draw triangles
            if self.rendernormals:
                # Color by normals
                glUniform1i(self.location.cmode, 2)
            else:
                # Uniform color
                glUniform1i(self.location.cmode, 0)
            glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, self.vbo[2])
            glDrawElements(GL_TRIANGLES, self.faces.size, GL_UNSIGNED_INT,
                           None)

            # Disable vertex arrays
            glDisableVertexAttribArray(0)
            glDisableVertexAttribArray(1)

            # Swap front and back buffers
            glfw.swap_buffers(window)

            # Poll for and process events
            glfw.poll_events()

        # Delete stuff
        glDeleteBuffers(4, self.vbo)
        glDeleteVertexArrays(1, (self.vao, ))
        glDeleteProgram(program)
        glfw.terminate()
Esempio n. 59
0
def main():
    # inicia glfw
    if not glfw.init():
        return

    # crea la ventana,
    # independientemente del SO que usemos
    window = glfw.create_window(800, 800, "Mi ventana", None, None)

    # Configuramos OpenGL
    glfw.window_hint(glfw.SAMPLES, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

    # Validamos que se cree la ventana
    if not window:
        glfw.terminate()
        return
    # Establecemos el contexto
    glfw.make_context_current(window)

    # Activamos la validación de
    # funciones modernas de OpenGL
    glewExperimental = True

    # Inicializar GLEW
    if glewInit() != GLEW_OK:
        print("No se pudo inicializar GLEW")
        return

    # Obtenemos versiones de OpenGL y Shaders
    version = glGetString(GL_VERSION)
    print(version)

    version_shaders = glGetString(GL_SHADING_LANGUAGE_VERSION)
    print(version_shaders)

    glfw.set_key_callback(window, key_callback)

    while not glfw.window_should_close(window):
        # Establece regiond e dibujo
        glViewport(0, 0, 800, 800)
        # Establece color de borrado
        glClearColor(0.4, 0.8, 0.1, 1)
        # Borra el contenido de la ventana
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        # Dibujar
        actualizar(window)
        dibujar()

        # Preguntar si hubo entradas de perifericos
        # (Teclado, mouse, game pad, etc.)
        glfw.poll_events()
        # Intercambia los buffers
        glfw.swap_buffers(window)

    # Se destruye la ventana para liberar memoria
    glfw.destroy_window(window)
    # Termina los procesos que inició glfw.init
    glfw.terminate()
Esempio n. 60
0
def main():
    global clear_all, clear_buffers, x, y, clicked, mode, complete, window_height
    mode = 1
    clicked, complete = False, False
    clear_all, clear_buffers = True, True
    window_height = 640

    if not glfw.init():
        print("GLFW not initialized")
        return

    window = glfw.create_window(640, window_height, "Rasterization", None,
                                None)
    if not window:
        print("Window not created")
        glfw.terminate()
        return

    glfw.make_context_current(window)

    glEnable(GL_DEPTH_TEST)
    glDepthFunc(GL_LESS)

    glfw.set_key_callback(window, key_callback)
    glfw.set_framebuffer_size_callback(window, resize_callback)
    glfw.set_mouse_button_callback(window, mouse_button_callback)

    figure = []
    color = (1.0, 1.0, 1.0)

    while not glfw.window_should_close(window):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        width, height = glfw.get_window_size(window)
        prepare_projection(width, height)

        if clear_buffers:
            matrix = None
            clear_buffers = False

        if clear_all:
            figure = []
            matrix = None
            clear_all, complete = False, False

        if mode == 1:
            if clicked:
                figure.append((int(x), int(height - y)))
            draw_points(figure, color)
            draw_lines(figure, color, complete)
            clicked = False
        elif mode == 2:
            if matrix is None:
                matrix = create_figure_view(width, height, figure, color)
            glDrawPixels(width, height, GL_RGB, GL_FLOAT, matrix)
        elif mode == 3:
            # фильтрация работает только при задании вершин против часовой стрелки!
            # отрисовка сглаженных границ
            if matrix is None:
                matrix = create_figure_view(width, height, figure, color)
                matrix = add_lines_to_matrix(figure, color, matrix)
            glDrawPixels(width, height, GL_RGB, GL_FLOAT, matrix)

        glfw.swap_buffers(window)
        glfw.poll_events()

    print("Terminate...")
    glfw.terminate()