Пример #1
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))
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()
Пример #3
0
def main():
	glfw.setErrorCallback(error_callback)

	glfw.init()
	glfw.windowHint(glfw.CONTEXT_VERSION_MAJOR, 3)
	glfw.windowHint(glfw.CONTEXT_VERSION_MINOR, 3)
	glfw.windowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
	# glfw.windowHint(glfw.RESIZABLE, gl.FALSE)
	glfw.windowHint(glfw.OPENGL_FORWARD_COMPAT, 1)

	window = glfw.createWindow(800, 600, "LearnOpenGL")

	if window is None:
		print('could not open window.')
		glfw.terminate()
		sys.exit()

	window.makeContextCurrent()
	window.setKeyCallback(key_callback)

	gl.init()
	gl.clearColor(0.2, 0.3, 0.3, 1.0)
	
	while not window.shouldClose():
		framebuffer_width, framebuffer_height = window.getFramebufferSize()
		gl.viewport(0, 0, framebuffer_width, framebuffer_height)
		gl.clear(gl.COLOR_BUFFER_BIT)
		glfw.pollEvents()
		window.swapBuffers()
Пример #4
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()
Пример #5
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)
Пример #6
0
	def setUp(self):
		glfw.init()
		glfw.windowHint(glfw.CONTEXT_VERSION_MAJOR, 3)
		glfw.windowHint(glfw.CONTEXT_VERSION_MINOR, 3)
		glfw.windowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
		glfw.windowHint(glfw.RESIZABLE, gl.FALSE)
		glfw.windowHint(glfw.OPENGL_FORWARD_COMPAT, 1)
		self.window = glfw.createWindow(800, 600, "TestCase")
		if self.window is None:
			print('could not open window.')
			glfw.terminate()
			sys.exit()
		self.window.makeContextCurrent()
		print("opened window")
		gl.init()
Пример #7
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()
Пример #8
0
    def __init__(self, use_light_coord=False):
        Thread.__init__(self)
        if not glfw.init():
            raise RuntimeError("Cannot start up GLFW")
        self.flatten = lambda l: [u for t in l for u in t]
        self.c_array = lambda c_type: lambda l: (c_type * len(l))(*l)
#         self.look_at = lambda eye, at, up: mat4.lookAt(eye, 2 * eye - at, up).inverse()
#         self.init()
        self.ss_update = Lock() # ss is short for snapshot
#         self.ss_ready = Lock()
#         self.ss_ready.acquire()
        self.ss_ready = Semaphore(0)
        self.snapshot = None
        self.param_lock = Lock()
        self._init_finished_lock = Lock()
        self._init_finished_lock.acquire()
        self._finalized_lock = Lock()
        self._finalized_lock.acquire()
        self._items = []
        self._cont_flag = True
        self._energy_terms = {}
        self._extern_penalty_terms = {}
        self._intern_penalty_terms = {"shadow_distance": -23.3, 'x': -23.3, 'y': -23.3}
        self.bg_img = None
        self.atb_controls = True
        self.use_light_coord(use_light_coord)
        self.use_pillars()        
        self.viewport_size = w, h = (640, 480)
        self.window = Window(w*3/2, h*2, "scene")
Пример #9
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()
Пример #10
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()
Пример #11
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()
Пример #12
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()
Пример #13
0
    def setup(self):
        # get glfw started
        glfw.init()
        self.window = glfw.create_window(self.width, self.height, "Python NanoVG Demo", None, None)
        glfw.set_window_pos(self.window, 0, 0)

        # Register callbacks window
        glfw.set_window_size_callback(self.window, self.on_resize)
        glfw.set_window_close_callback(self.window, self.on_close)
        glfw.set_key_callback(self.window, self.on_key)
        glfw.set_mouse_button_callback(self.window, self.on_button)

        self.basic_gl_setup()

        # glfwSwapInterval(0)
        glfw.make_context_current(self.window)
Пример #14
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()
Пример #15
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)
Пример #16
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()
Пример #17
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
Пример #18
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()
Пример #19
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
Пример #20
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()
Пример #21
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);
Пример #22
0
def main():
    # init glfw
    glfw.init()

    # make a window
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.window_hint(glfw.OPENGL_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.OPENGL_VERSION_MINOR, 3)

    glfw.open_window(640, 480, 8, 8, 8, 8, 0, 0, glfw.WINDOW)

    initialize()

    while glfw.GetWindowParam(glfw.OPENED):
        render()

    glfw.Terminate()
Пример #23
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
Пример #24
0
   def init(self):
      # Initialize the renderer, set up the Window.
      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, gl.GL_TRUE)
      glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
      glfw.window_hint(glfw.DECORATED, gl.GL_TRUE)
      glfw.window_hint(glfw.DECORATED, gl.GL_TRUE)
      glfw.window_hint(glfw.RESIZABLE, gl.GL_FALSE)

      width = Config.windowWidth
      height = Config.windowHeight

      self.aspect = width/height

      # Initialize the window
      self.window = glfw.create_window(width, height, "Magic", None, None)
      glfw.make_context_current(self.window)
      self.renderer = Renderer()
      self.quad = []
      self.text = []

      # Set up camera
      self.viewMatrix = Matrix.identity()

      # Set up view transform. View is always 16 units high, and 16 * aspect units
      # wide. The extra space outside of a 4:3 ratio is unused, to make sure that
      # all the cards always fit in a 4:3 aspect monitor. 
      vHeight = 2
      vWidth = vHeight * self.aspect
      self.projectionMatrix = Matrix.ortho(-vWidth/2, vWidth/2, vHeight/2, -vHeight/2, -1, 1)
      self.viewProjectionMatrix = self.projectionMatrix * self.viewMatrix

      # Set up viewport
      fbWidth, fbHeight = glfw.get_framebuffer_size(self.window)
      gl.glViewport(0, 0, fbWidth, fbHeight)
      q = Quad(Texture('Images/Sen Triplets.jpg'))
      # Natural resolution of cards is 480x680
      cardAspect = 480/680
      q.x = 0
      q.y = 0
      q.height = .8
      q.width = q.height * cardAspect
      self.quad.append(q)
Пример #25
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)
Пример #26
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()
Пример #27
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()
Пример #28
0
def main():

    glfw.init()

    window = glfw.create_window( 640, 480, "glfw triangle", None, None )
    
    glfw.make_context_current( window )
    glfw.swap_interval( 1 )
    glfw.set_key_callback( window, on_key )

    while not glfw.window_should_close( window ):

        # set up model view
        width, height = glfw.get_framebuffer_size( window )
        ratio = width / float(height)
        gl.glViewport( 0, 0, width, height )
        gl.glClear( gl.GL_COLOR_BUFFER_BIT )
        gl.glMatrixMode( gl.GL_PROJECTION )
        gl.glLoadIdentity()
        gl.glOrtho( -ratio, ratio, -1.0, 1.0, 1.0, -1.0 )
        gl.glMatrixMode( gl.GL_MODELVIEW )
        gl.glLoadIdentity()
        gl.glRotatef( float(glfw.get_time()) * 50.0, 0.0, 0.0, 1.0 )

        # draw triangle
        gl.glBegin(gl.GL_TRIANGLES);
        gl.glColor3f( 1.0, 0.0, 0.0 )
        gl.glVertex3f( -0.6, -0.4, 0.0 )
        gl.glColor3f( 0.0, 1.0, 0.0 )
        gl.glVertex3f( 0.6, -0.4, 0.0 )
        gl.glColor3f( 0.0, 0.0, 1.0 )
        gl.glVertex3f( 0.0, 0.6, 0.0 )
        gl.glEnd()

        # swap buffers
        glfw.swap_buffers(window)

        # poll for events
        glfw.poll_events()
    
    glfw.destroy_window(window)
    glfw.terminate()
Пример #29
0
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()
Пример #30
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 = []
Пример #31
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(width, height, "LearnOpenGL", None, None)
    if not window:
        print("Window Creation failed!")
        glfw.terminate()

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

    gl.glEnable(gl.GL_DEPTH_TEST)
    shader = Shader(CURDIR / 'shaders/6.1.coordinate_systems.vs',
                    CURDIR / 'shaders/6.1.coordinate_systems.fs')

    vertices = [
        # positions      tex_coords
        -0.5,
        -0.5,
        -0.5,
        0.0,
        0.0,
        0.5,
        -0.5,
        -0.5,
        1.0,
        0.0,
        0.5,
        0.5,
        -0.5,
        1.0,
        1.0,
        0.5,
        0.5,
        -0.5,
        1.0,
        1.0,
        -0.5,
        0.5,
        -0.5,
        0.0,
        1.0,
        -0.5,
        -0.5,
        -0.5,
        0.0,
        0.0,
        -0.5,
        -0.5,
        0.5,
        0.0,
        0.0,
        0.5,
        -0.5,
        0.5,
        1.0,
        0.0,
        0.5,
        0.5,
        0.5,
        1.0,
        1.0,
        0.5,
        0.5,
        0.5,
        1.0,
        1.0,
        -0.5,
        0.5,
        0.5,
        0.0,
        1.0,
        -0.5,
        -0.5,
        0.5,
        0.0,
        0.0,
        -0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        -0.5,
        0.5,
        -0.5,
        1.0,
        1.0,
        -0.5,
        -0.5,
        -0.5,
        0.0,
        1.0,
        -0.5,
        -0.5,
        -0.5,
        0.0,
        1.0,
        -0.5,
        -0.5,
        0.5,
        0.0,
        0.0,
        -0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        0.5,
        0.5,
        -0.5,
        1.0,
        1.0,
        0.5,
        -0.5,
        -0.5,
        0.0,
        1.0,
        0.5,
        -0.5,
        -0.5,
        0.0,
        1.0,
        0.5,
        -0.5,
        0.5,
        0.0,
        0.0,
        0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        -0.5,
        -0.5,
        -0.5,
        0.0,
        1.0,
        0.5,
        -0.5,
        -0.5,
        1.0,
        1.0,
        0.5,
        -0.5,
        0.5,
        1.0,
        0.0,
        0.5,
        -0.5,
        0.5,
        1.0,
        0.0,
        -0.5,
        -0.5,
        0.5,
        0.0,
        0.0,
        -0.5,
        -0.5,
        -0.5,
        0.0,
        1.0,
        -0.5,
        0.5,
        -0.5,
        0.0,
        1.0,
        0.5,
        0.5,
        -0.5,
        1.0,
        1.0,
        0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        0.5,
        0.5,
        0.5,
        1.0,
        0.0,
        -0.5,
        0.5,
        0.5,
        0.0,
        0.0,
        -0.5,
        0.5,
        -0.5,
        0.0,
        1.0
    ]
    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)]

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

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

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

    gl.glVertexAttribPointer(1, 2, gl.GL_FLOAT,
                             gl.GL_FALSE, 5 * sizeof(c_float),
                             c_void_p(3 * sizeof(c_float)))
    gl.glEnableVertexAttribArray(1)

    # -- load texture 1
    texture1 = gl.glGenTextures(1)
    gl.glBindTexture(gl.GL_TEXTURE_2D, texture1)
    # -- texture wrapping
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT)
    # -- texture filterting
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)

    img = Image.open(Tex('container.jpg')).transpose(Image.FLIP_TOP_BOTTOM)
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0,
                    gl.GL_RGB, gl.GL_UNSIGNED_BYTE, img.tobytes())
    gl.glGenerateMipmap(gl.GL_TEXTURE_2D)

    # -- load texture 2
    texture2 = gl.glGenTextures(1)
    gl.glBindTexture(gl.GL_TEXTURE_2D, texture2)
    # -- texture wrapping
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_REPEAT)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_REPEAT)
    # -- texture filterting
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
    gl.glTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)

    img = Image.open(Tex('awesomeface.png'))
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, img.width, img.height, 0,
                    gl.GL_RGBA, gl.GL_UNSIGNED_BYTE, img.tobytes())
    gl.glGenerateMipmap(gl.GL_TEXTURE_2D)

    shader.use()
    shader.set_int("texture1", 0)
    shader.set_int("texture2", 1)

    projection = Matrix44.perspective_projection(45, width / height, 0.1,
                                                 100.0)
    shader.set_mat4('projection', projection)

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

        process_input(window)

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

        gl.glActiveTexture(gl.GL_TEXTURE0)
        gl.glBindTexture(gl.GL_TEXTURE_2D, texture1)
        gl.glActiveTexture(gl.GL_TEXTURE1)
        gl.glBindTexture(gl.GL_TEXTURE_2D, texture2)

        shader.use()
        view = Matrix44.look_at(camera_pos, camera_pos + camera_front,
                                camera_up)
        shader.set_mat4('view', view)

        gl.glBindVertexArray(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
            shader.set_mat4('model', model)
            gl.glDrawArrays(gl.GL_TRIANGLES, 0, 36)

        glfw.poll_events()
        glfw.swap_buffers(window)

    gl.glDeleteVertexArrays(1, id(vao))
    gl.glDeleteBuffers(1, id(vbo))
    glfw.terminate()
Пример #32
0
    characters = Node(
        transform=translate(characters_offset_x, characters_offset_y,
                            characters_offset_z) @ scale(characters_scale)
        @ rotate(axis=(0, 1, 0), angle=characters_rotate_deg))
    characters.add(*load_skinned("dino/Dinosaurus_roar.dae"))

    forest = Node(
        transform=translate(0, forest_offset, 0) @ scale(forest_scale))
    forest.add(*load_textured("trees9/forest.obj"))

    ground = Node(transform=translate(-ground_size >> 1, ground_offset,
                                      -ground_size >> 1))
    ground.add(sol(ground_size))

    Skysphere = Node(transform=scale(Skysphere_scale))
    Skysphere.add(*load_textured("Skysphere/skysphere.obj"))

    scene = Node(transform=identity(),
                 children=[characters, forest, ground, Skysphere])

    viewer.add(scene)

    viewer.run()


if __name__ == '__main__':
    glfw.init()  # initialize window system glfw
    main()  # main function keeps variables locally scoped
    glfw.terminate()  # destroy all glfw windows and GL contexts
Пример #33
0
def main():
    # initialize glfw
    if not glfw.init():
        return

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

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    vertices = [-0.5, -0.5, -0.5, 0.0, 0.0, 1.0,
                0.5, -0.5, -0.5, 1.0, 0.0, 1.0,
                0.5, 0.5, -0.5, 1.0, 1.0, 1.0,
                0.5, 0.5, -0.5, 1.0, 1.0, 1.0,
                -0.5, 0.5, -0.5, 0.0, 1.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, 1.0,
                0.5, 0.5, 0.5, 1.0, 1.0, 1.0,
                0.5, 0.5, 0.5, 1.0, 1.0, 1.0,
                -0.5, 0.5, 0.5, 0.0, 1.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, 1.0,
                -0.5, 0.5, -0.5, 1.0, 1.0, 1.0,
                -0.5, -0.5, -0.5, 0.0, 1.0, 1.0,
                -0.5, -0.5, -0.5, 0.0, 1.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, 1.0,

                0.5, 0.5, 0.5, 1.0, 0.0, 1.0,
                0.5, 0.5, -0.5, 1.0, 1.0, 1.0,
                0.5, -0.5, -0.5, 0.0, 1.0, 1.0,
                0.5, -0.5, -0.5, 0.0, 1.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, 1.0,

                -0.5, -0.5, -0.5, 0.0, 1.0, 1.0,
                0.5, -0.5, -0.5, 1.0, 1.0, 1.0,
                0.5, -0.5, 0.5, 1.0, 0.0, 1.0,
                0.5, -0.5, 0.5, 1.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, 1.0, 1.0,

                -0.5, 0.5, -0.5, 0.0, 1.0, 1.0,
                0.5, 0.5, -0.5, 1.0, 1.0, 1.0,
                0.5, 0.5, 0.5, 1.0, 0.0, 1.0,
                0.5, 0.5, 0.5, 1.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, 1.0, 1.0
                ]
    vertices = np.array(vertices, dtype=np.float32)

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

    view = glm.mat4(1.0)
    view = glm.translate(view, glm.vec3(0.0, 0.0, -3.0))

    projection = glm.perspective(glm.radians(45.0), screen_width / screen_height, 0.1, 100.0)

    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 model;
    uniform mat4 view;
    uniform mat4 projection;
    
    void main()
    {
        gl_Position = projection * view * model * 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)
    glEnable(GL_DEPTH_TEST)

    # 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 | GL_DEPTH_BUFFER_BIT) # state-using function

        # render triangle
        glUseProgram(shader)

        for i in range(10):
            glDrawArrays(GL_TRIANGLES, 0, 36)

            model = glm.mat4(1.0)
            model = glm.translate(model, cube_positions[i])
            angle = 20.0 * i
            model = glm.rotate(model, glm.radians(angle), glm.vec3(1.0, 0.3, 0.5))
            modelLoc = glGetUniformLocation(shader, "model")
            glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm.value_ptr(model))


        viewLoc = glGetUniformLocation(shader, "view")
        glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm.value_ptr(view))

        projectionLoc = glGetUniformLocation(shader, "projection")
        glUniformMatrix4fv(projectionLoc, 1, GL_FALSE, glm.value_ptr(projection))

        glBindVertexArray(VAO)



        # check and call events and swap the buffers
        glfw.swap_buffers(window)
        glfw.poll_events()
    glfw.terminate()
def main():
    if not glfw.init():
        raise Exception("glfw cannot be initialised.......")

    window=glfw.create_window(700,700, "rotation 2D",None,None)

    if not window:
        glfw.terminate()
        raise Exception("glfw window not created")

    w,h = glfw.get_framebuffer_size(window)
    print("width: {}, height:{}".format(w,h))

    glfw.set_window_pos(window, 400,40)
    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)

    glfw.set_window_size_callback(window, reshape_callback)

    gluOrtho2D(-200.0, 200.0,-200.0,200.0)
    setpixel(0,0,[1,0,1])

    while not glfw.window_should_close(window):

        glClear(GL_COLOR_BUFFER_BIT)
        #glClearColor(0.0,0.76,0.56,1.0)
        glClearColor(0,0,0,1.0)

        drawAxes()

        a =(50,50) #yellow
        b = (50, 80) #green
        c=(80,80) #red
        d=(80,50) #blue

        glBegin(GL_QUADS)
        glColor3f(1,1,0) #yellow vertex
        glVertex2fv(a)
        glColor3f(0,1,0)
        glVertex2fv(b)
        glColor3f(1,0,0)
        glVertex2fv(c)
        glColor3f(0,0,1)#blue vertex
        glVertex2fv(d)
        glEnd()

        #print("rotate square vertices by 45 degrees anti clockwise x-dir")


        #rotate square vertices by 45 degrees anti clockwise x-dir
        size = (2,2)
        A_new = scale2D(a, size)
        B_new = scale2D(b, size)
        C_new = scale2D(c,size)
        D_new = scale2D(d,size)
        #print(A_new,"||", B_new,"||", C_new,"||", D_new)

        glBegin(GL_QUADS)
        glColor3f(1,1,0)
        glVertex2fv(A_new)
        glColor3f(0,1,0)
        glVertex2fv(B_new)
        glColor3f(1,0,0)
        glVertex2fv(C_new)
        glColor3f(0,0,1)
        glVertex2fv(D_new)
        glEnd()

        #rotate square vertices by 90 degrees anti clockwise x-dir

        size = (0.3,0.3)
        A_new = scale2D(a, size)
        B_new = scale2D(b, size)
        C_new = scale2D(c,size)
        D_new = scale2D(d,size)

        glBegin(GL_QUADS)
        glColor3f(1,1,0)
        glVertex2fv(A_new)
        glColor3f(0,1,0)
        glVertex2fv(B_new)
        glColor3f(1,0,0)
        glVertex2fv(C_new)
        glColor3f(0,0,1)
        glVertex2fv(D_new)
        glEnd()

        glfw.swap_buffers(window)

        glfw.poll_events()

    glfw.terminate()
Пример #35
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()
Пример #36
0
Файл: app.py Проект: 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
Пример #37
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()
Пример #38
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()
Пример #39
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
Пример #40
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()
Пример #41
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()
Пример #42
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
Пример #43
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,
    skip_driver_installation,
):
    """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() -> int:
        return int(g_pool.pupil_detection_enabled)

    def detection_enabled_setter(value: int):
        is_on = bool(value)
        g_pool.pupil_detection_enabled = is_on
        n = {"subject": "pupil_detector.set_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.31.0"), "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.debug("Application Version: {}".format(version))
        logger.debug("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
        g_pool.skip_driver_installation = skip_driver_installation

        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
            with gl_utils.current_context(main_window):
                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.debug(
                "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 = bool(
            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 == "pupil_detector.set_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": "pupil_detector.set_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
        g_pool.trigger_main_window_redraw = lambda: on_resize(
            main_window, *glfw.get_framebuffer_size(main_window))
        g_pool.trigger_main_window_redraw()

        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.debug("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.debug("Process shutting down.")
        ipc_pub.notify({"subject": "world_process.stopped"})
        sleep(1.0)
Пример #44
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()
Пример #45
0
def main():
    vertex_src = """
    # version 330

    layout(location = 0) in vec3 a_position;
    layout(location = 1) in vec3 a_color;

    out vec3 v_color;

    void main()
    {
        gl_Position = vec4(a_position, 1.0);
        v_color = a_color;
    }
    """

    fragment_src = """
    # version 330

    in vec3 v_color;
    out vec4 out_color;

    void main()
    {
        out_color = vec4(v_color, 1.0);
    }
    """

    def window_resize(window, width, height):
        glViewport(0, 0, width, height)

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

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

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

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

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

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

    # make the context current
    glfw.make_context_current(window)

    vertices = [
        -0.5, -0.5, 0.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, 1.0, 1.0, 0.0, 0.75, 0.0,
        1.0, 1.0, 0.0
    ]

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

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

    VAO = glGenVertexArrays(1)
    glBindVertexArray(VAO)

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

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

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

    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(0))

    glEnableVertexAttribArray(1)
    glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE, 24, ctypes.c_void_p(12))

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

    glClearColor(0, 0.1, 0.1, 1)

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

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

        glfw.swap_buffers(window)

    # terminate glfw, free up allocated resources
    glfw.terminate()
    v_color = a_color;
}
"""

fragment_src = """
# version 330
in vec3 v_color;
out vec4 out_color;
void main()
{
    out_color = vec4(v_color, 1.0);
}
"""


if not glfw.init():
    raise Exception('glfw con not be initialized')

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

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

glfw.set_window_pos(window, 3400, 200)
glfw.make_context_current(window)

buffer = [
    -0.5, -0.5, 0.0,
    0.5, -0.5, 0.0,
    0.0, 0.5, 0.0,
Пример #47
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()
Пример #48
0
import glfw
from OpenGL.GL import *
import OpenGL.GL.shaders
import numpy as np
import math

glfw.init()
glfw.window_hint(glfw.VISIBLE, glfw.FALSE)
window = glfw.create_window(700, 700, "Esfera", None, None)
glfw.make_context_current(window)

vertex_code = """
        attribute vec3 position;
        uniform mat4 mat_transformation;
        void main(){
            gl_Position = mat_transformation * vec4(position,1.0);
        }
        """
fragment_code = """
        uniform vec4 color;
        void main(){
            gl_FragColor = color;
        }
        """

# Request a program and shader slots from GPU
program = glCreateProgram()
vertex = glCreateShader(GL_VERTEX_SHADER)
fragment = glCreateShader(GL_FRAGMENT_SHADER)

# Set shaders source
Пример #49
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()
Пример #50
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()
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()
Пример #52
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()
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
Пример #54
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()
Пример #55
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()
Пример #56
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()
Пример #57
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()
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()
Пример #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)

    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()
Пример #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()