Пример #1
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 = mg.create_context(require=410)

    # 主循环
    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)
        glfw.poll_events()

        glfw.swap_buffers(window)

    glfw.terminate()
Пример #2
0
    def __init__(self, WIDTH=1280, HEIGHT=720, framerate=25):
        self.width = WIDTH
        self.height = HEIGHT
        # initializing glfw library
        if not glfw.init():
            raise Exception("glfw can not be initialized!")
        self.window = glfw.create_window(self.width, self.height, "Display",
                                         None, None)
        # check if window was created
        if not self.window:
            glfw.terminate()
            raise Exception("glfw window can not be created!")

        # make the context current
        glfw.make_context_current(self.window)
        # set window's position
        glfw.set_window_pos(self.window, 400, 200)
        # set the callback function for window resize
        glfw.set_window_size_callback(self.window, self.window_resize)

        self.scenes = []
        self.viewports = []
        self.cameras = []
        self.update_calls = []
        self.components = []
        self.frame_rate = framerate
Пример #3
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()
Пример #4
0
    def head_cam_viewer_close(self):
        if self.get_head_cam_viewer() is not None:
            #glfw.window_should_close()
            glfw.set_window_size_callback(
                self.head_cam_viewer.opengl_context.window, None)

            glfw.destroy_window(self.head_cam_viewer.opengl_context.window)
Пример #5
0
    def __init__(self):
        super().__init__()

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

        self.check_glfw_version()

        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, self.gl_version.major)
        glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, self.gl_version.minor)
        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
            print("picked fullscreen mode:", mode)

        print("Window size:", self.width, self.height)
        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)

        # Get the actual buffer size of the window
        # This is important for some displays like Apple's Retina as reported window sizes are virtual
        self.buffer_width, self.buffer_height = glfw.get_framebuffer_size(
            self.window)
        print("Frame buffer size:", self.buffer_width, self.buffer_height)
        print("Actual window size:", glfw.get_window_size(self.window))

        glfw.make_context_current(self.window)

        # The number of screen updates to wait from the time glfwSwapBuffers
        # was called before swapping the buffers and returning
        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_window_size_callback(self.window, self.window_resize_callback)

        # Create mederngl context from existing context
        self.ctx = moderngl.create_context(require=self.gl_version.code)
        context.WINDOW = self
        self.fbo = self.ctx.screen
        self.set_default_viewport()
Пример #6
0
def main():
    if not glfw.init():
        raise Exception("glfw nt initialized")

    window=glfw.create_window(480,480, "Midpoint Circle Algorithm",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,200)

    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(1,1,1,1.0)
        setpixel((0), (0), [1,0,0])

        BresenhamCircle(0,0,150, [1,0,1])
        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()
Пример #7
0
    def __init__(self):

        cwd = os.getcwd()

        if not glfw.init():
            return

        os.chdir(cwd)

        glfw.window_hint(glfw.DEPTH_BITS, 32)
        self.frame_rate = 100

        self.width, self.height = 600, 600
        self.aspect = self.width / float(self.height)
        self.window = glfw.create_window(self.width, self.height, "bspline",
                                         None, None)
        if not self.window:
            glfw.terminate()
            return

        glfw.make_context_current(self.window)

        glClearColor(1.0, 1.0, 1.0, 1.0)

        glfw.set_mouse_button_callback(self.window, self.onMouseButton)
        glfw.set_key_callback(self.window, self.onKeyboard)
        glfw.set_window_size_callback(self.window, self.onSize)

        self.scene = Scene(self.width, self.height)

        self.exitNow = False

        self.shiftMode = False
Пример #8
0
    def __init__(self):
        # initialize glfw
        if not glfw.init():
            glfw.terminate()
            exit(0)

        glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
        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.RESIZABLE, GL_FALSE)
        self.windowID = glfw.create_window(self.w_width, self.w_height,
                                           "My OpenGL window", None, None)

        if not self.windowID:
            glfw.terminate()
            exit(0)

        glfw.make_context_current(self.windowID)

        print("Supported GLSL version is: ",
              glGetString(GL_SHADING_LANGUAGE_VERSION))

        glfw.set_window_size_callback(self.windowID, self.onWindowResize)
        glfw.set_cursor_pos_callback(self.windowID, self.onCursorMove)
        glfw.set_input_mode(self.windowID, glfw.CURSOR, glfw.CURSOR_DISABLED)

        self.lastFrame = glfw.get_time()
        self.deltaTime = 0
Пример #9
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()
Пример #10
0
    def __init__(self):
        cwd = os.getcwd()

        if not glfw.init():
            return

        os.chdir(cwd)

        glfw.window_hint(glfw.VERSION_MAJOR, 3)
        glfw.window_hint(glfw.VERSION_MINOR, 3)
        glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

        self.width, self.height = 640, 480
        self.window = glfw.create_window(self.width, self.height,
                                         "Simple Window", None, None)

        glfw.make_context_current(self.window)

        glViewport(0, 0, self.width, self.height)
        glEnable(GL_DEPTH_TEST)
        glClearColor(0.5, 0.5, 0.5, 1)

        glfw.set_key_callback(self.window, self._key_press_callback)
        glfw.set_mouse_button_callback(self.window, self._mouse_press_callback)
        glfw.set_window_size_callback(self.window,
                                      self._window_resize_callback)
def create_window():
    """
    It creates a new window.
    """
    # initializing glfw library
    if not glfw.init():
        raise Exception("glfw cannot be initialized!")

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

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

    # make the context current
    glfw.make_context_current(window)

    glfw.set_window_size_callback(window, window_resize)

    # Define the keycallback functions
    glfw.set_key_callback(window, key_callback)

    return window
Пример #12
0
    def __init__(self, window_name: str, window_width: int,
                 window_height: int):
        self.window_name: str = window_name
        self.window_width: int = window_width
        self.window_height: int = window_height

        self.fps_calc: fpsCalculator = fpsCalculator()
        self.models: List[Any] = []

        # Initialize GLFW
        if not glfw.init():
            print('Failed to create glfw')
            raise RuntimeError

        # Create window
        self.window = glfw.create_window(self.window_width, self.window_height,
                                         self.window_name, None, None)
        if not self.window:
            glfw.terminate()
            print('Failed to create window')
            raise RuntimeError

        glfw.make_context_current(self.window)

        # resize callback function
        glfw.set_window_size_callback(self.window, self.resize)
Пример #13
0
def inicializaOpenGL():
    global Window, WIDTH, HEIGHT

    #Inicializa GLFW - Biblioteca responsável por todas as questões relacionadas a JANELA da aplicação
    glfw.init()

    #Criação de uma janela. Parâmetros: largura, altura, título, monitor e janela de compartilhamento
    Window = glfw.create_window(WIDTH, HEIGHT,
                                "Exemplo 1 - renderização de um triângulo",
                                None, None)
    #Caso não seja possível criar a janela, a GLFW e a aplicação são terminadas
    if not Window:
        glfw.terminate()
        exit()

    #Registramos a função "redimensionaCallback" como sendo a função de redimensionamento

#Isso significa que a função "redimensionaCallback" será chamada sempre que a janela for redimensionada,
#seja pelo sistema ou pelo usuário
    glfw.set_window_size_callback(Window, redimensionaCallback)

    #Define o contexto atual do GLFW como sendo a janela criada acima. O contexto define
    #em qual janela o OpenGL irá funcionar, o que é essencial para que o programa funcione
    glfw.make_context_current(Window)

    #Buscamos informações a respeito do hardware (placa de vídeo) e a versão do OpenGL que a mesma da suporte
    print("Placa de vídeo: ", OpenGL.GL.glGetString(OpenGL.GL.GL_RENDERER))
    print("Versão do OpenGL: ", OpenGL.GL.glGetString(OpenGL.GL.GL_VERSION))
Пример #14
0
def View(meshes):

    global viewer

    viewer = ViewerClass()
    viewer.W = 1024
    viewer.H = 768
    viewer.fov = 60.0
    viewer.button = 0
    viewer.meshes = meshes
    viewer.shader = None

    # calculate bounding box -> (-1,+1) ^3
    BOX = invalid_box()
    for mesh in viewer.meshes:
        box = get_bounding_box(mesh)
        add_point(BOX, box.p1)
        add_point(BOX, box.p2)
    S = BOX.p2 - BOX.p1
    maxsize = max([S.x, S.y, S.z])

    for mesh in viewer.meshes:
        mesh.T = matrix_prod(
            translate_matrix(Point3d(-1.0, -1.0, -1.0)),
            matrix_prod(
                scale_matrix(
                    Point3d(2.0 / maxsize, 2.0 / maxsize, 2.0 / maxsize)),
                translate_matrix(-BOX.p1)))

    viewer.pos = Point3d(3, 3, 3)
    viewer.dir = normalized(Point3d(0, 0, 0) - viewer.pos)
    viewer.vup = Point3d(0, 0, 1)

    maxsize = 2.0
    viewer.zNear = maxsize / 50.0
    viewer.zFar = maxsize * 10.0
    viewer.walk_speed = maxsize / 100.0
    redisplay(viewer)

    glfw.init()

    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)

    viewer.win = glfw.create_window(viewer.W, viewer.H, "Plasm", None, None)
    glfw.make_context_current(viewer.win)

    glfw.set_window_size_callback(viewer.win, on_resize_evt)
    glfw.set_key_callback(viewer.win, on_keypress_evt)
    glfw.set_cursor_pos_callback(viewer.win, on_mousemove_evt)
    glfw.set_mouse_button_callback(viewer.win, on_mousebutton_evt)
    glfw.set_scroll_callback(viewer.win, on_mousewheel_evt)

    while not glfw.window_should_close(viewer.win):
        glRender(viewer)
        glfw.swap_buffers(viewer.win)
        glfw.poll_events()
    glfw.terminate()
Пример #15
0
    def __init__(self, window):
        super(Client, self).__init__()

        self.window = window
        self.width, self.height = glfw.get_window_size(window)

        self.gl = mg.create_context()
        self.compile()

        self.camerapos = vec4(0.0, 0.0, 20.0, 1.0)

        def on_modified(e):
            # restart python if python code is changed
            if e.src_path.endswith(".py"):
                glfw.set_window_should_close(window, glfw.TRUE)
                os.system(f"python {e.src_path}")

            # compile shaders if the change is not python code
            else:
                self.should_compile = True

        handler = FileSystemEventHandler()
        handler.on_modified = on_modified
        observer = Observer()
        observer.schedule(handler, "./.", True)
        observer.start()

        self.is_drag_rot_cam = False
        self.prempos = vec2(0.0, 0.0)

        # wire glfw events
        glfw.set_mouse_button_callback(window, self.on_mouse_button)
        glfw.set_cursor_pos_callback(window, self.on_cursor_pos)
        glfw.set_scroll_callback(window, self.on_scroll)
        glfw.set_window_size_callback(window, self.on_window_size)
def main():
    if not glfw.init():
        raise Exception("glfw nt initialized")

    window = glfw.create_window(700, 700, "B117049- Quartic Function", 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, 45)
    glfw.make_context_current(window)
    glfw.set_key_callback(window, key_callback)
    glfw.set_window_size_callback(window, reshape_callback)
    gluOrtho2D(-80.0, 80, -400000.0, 40000000.0)

    while not glfw.window_should_close(window):

        glClear(GL_COLOR_BUFFER_BIT)
        #glClearColor(0.0,0.76,0.56,1.0)
        glClearColor(1, 1, 1, 1.0)
        drawAxes()

        for i in range(-79, 79, 1):
            y = quartic(i)
            setpixel(i, y, (1, 0, 0))

        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()
Пример #17
0
def main():
    global window, frame_rate
    cwd = os.getcwd()

    if not glfw.init():
        return

    os.chdir(cwd)

    glfw.window_hint(glfw.DEPTH_BITS, 32)
    frame_rate = 144
    window = glfw.create_window(WIDTH, HEIGHT, "2D Graphics", None, None)

    if not window:
        glfw.terminate()
        return

    glfw.make_context_current(window)

    glfw.set_mouse_button_callback(window, mouse_pressed)
    glfw.set_key_callback(window, key_pressed)
    glfw.set_window_size_callback(window, resize_viewport)
    glfw.set_cursor_pos_callback(window, mouse_moved)

    create_obj_from_file()

    init_opengl()

    run()
Пример #18
0
def main():
    if not glfw.init():
        raise ValueError("Failed to initialize glfw")

    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, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 2)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
    glfw.window_hint(glfw.RESIZABLE, True)
    glfw.window_hint(glfw.DOUBLEBUFFER, True)
    glfw.window_hint(glfw.DEPTH_BITS, 24)
    glfw.window_hint(glfw.SAMPLES, 4)

    window = glfw.create_window(1260, 720, "Python GL", None, None)
    if not window:
        glfw.terminate()
        raise ValueError("Failed to create window")

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

    while not glfw.window_should_close(window):

        on_input(window)
        on_draw()
        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()
Пример #19
0
def create_main_window():
    global sm
    if not glfw.init():
        sys.exit(1)

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

    title = 'MyPy Engine'
    width, height = sm.get_dimensions()

    window = glfw.create_window(width, height, title, None, None)
    if not window:
        sys.exit(2)
    glfw.make_context_current(window)

    glfw.set_input_mode(window, glfw.STICKY_KEYS, True)
    glfw.set_key_callback(window, key_handler)
    glfw.set_cursor_pos_callback(window, sm.mouse_pos_handler)
    glfw.set_mouse_button_callback(window, sm.mouse_button_handler)
    glfw.set_scroll_callback(window, sm.mouse_scroll_handler)
    glfw.set_window_size_callback(window, window_resize_listener)

    return window
Пример #20
0
    def __init__(self, objFilePath):

        # save current working directory
        cwd = os.getcwd()

        # Initialize the library
        if not glfw.init():
            return

        # restore cwd
        os.chdir(cwd)

        # version hints
        #glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 3)
        #glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 3)
        #glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, GL_TRUE)
        #glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

        # buffer hints
        glfw.window_hint(glfw.DEPTH_BITS, 32)

        # define desired frame rate
        self.frame_rate = 100

        # make a window
        self.width, self.height = 640, 480
        self.aspect = self.width/float(self.height)
        self.window = glfw.create_window(self.width, self.height, "2D Graphics", None, None)
        if not self.window:
            glfw.terminate()
            return

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

        # initialize GL
        glViewport(0, 0, self.width, self.height)
        glEnable(GL_DEPTH_TEST)
        glClearColor(1.0, 1.0, 1.0, 1.0)
        glMatrixMode(GL_PROJECTION)
        glLoadIdentity()
        #glOrtho(-self.width/2,self.width/2,-self.height/2,self.height/2,0.1,100)
        #glOrtho(-2,2,-2,2,0.1,100)
        gluPerspective(45.0,self.aspect,0.1,100.0) #TODO: ERLAUBT?
        glMatrixMode(GL_MODELVIEW)

        # set window callbacks
        glfw.set_mouse_button_callback(self.window, self.onMouseButton)
        glfw.set_key_callback(self.window, self.onKeyboard)
        glfw.set_window_size_callback(self.window, self.onSize)

        # create 3D
        self.scene = Scene(self.width, self.height, objFilePath)

        # exit flag
        self.exitNow = False

        # animation flag
        self.animation = True
Пример #21
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)

        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.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_window_size_callback(self._window,
                                      self.glfw_window_resize_callback)

        if self._create_mgl_context:
            self.init_mgl_context()

        self.set_default_viewport()
Пример #22
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)
        glfw.window_hint(glfw.SCALE_TO_MONITOR, glfw.TRUE)

        monitor = None
        if self.fullscreen:
            self._set_fullscreen(True)

        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)
        else:
            glfw.swap_interval(0)

        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)
        glfw.set_window_close_callback(self._window, self.glfw_window_close)

        self.init_mgl_context()
        self.set_default_viewport()
Пример #23
0
	def set_callbacks(self):
		glfw.set_window_close_callback(self.window, self.window_close_callback)
		glfw.set_window_size_callback(self.window, self.window_resize_callback)
		glfw.set_key_callback(self.window, self.keyboard_callback)
		glfw.set_char_callback(self.window, self.key_typed_callback)
		glfw.set_mouse_button_callback(self.window, self.mouse_callback)
		glfw.set_scroll_callback(self.window, self.scroll_callback)
		glfw.set_cursor_pos_callback(self.window, self.cursor_pos_callback)
Пример #24
0
def main():
    glfw.init()
    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 3)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

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

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

    shader = Shader(CURDIR / 'shaders/3.6.shader.vs',
                    CURDIR / 'shaders/3.6.shader.fs')

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

    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(data), data, gl.GL_STATIC_DRAW)

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

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

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

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

        glfw.poll_events()
        glfw.swap_buffers(window)

    gl.glDeleteVertexArrays(1, id(vao))
    gl.glDeleteBuffers(1, id(vbo))
    glfw.terminate()
Пример #25
0
def main():
    if not glfw.init():
        raise ValueError("Failed to initialize glfw")

    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, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 2)
    glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.window_hint(glfw.OPENGL_FORWARD_COMPAT, True)
    glfw.window_hint(glfw.RESIZABLE, True)
    glfw.window_hint(glfw.DOUBLEBUFFER, True)
    glfw.window_hint(glfw.DEPTH_BITS, 24)
    glfw.window_hint(glfw.SAMPLES, 4)

    window = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "Python Compute Shader Demo", None, None)
    if not window:
        glfw.terminate()
        raise ValueError("Failed to create window")

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

    CSG = shader.ComputeShader(RES("splat.glsl"))
    SplatProgram = shader.Shader(RES("splat.vert"), RES("splat.frag"))

    some_UAV = gl.glGenTextures(1)
    gl.glActiveTexture(gl.GL_TEXTURE0)
    gl.glBindTexture(gl.GL_TEXTURE_2D, some_UAV)
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_S, gl.GL_CLAMP_TO_EDGE)
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_WRAP_T, gl.GL_CLAMP_TO_EDGE)
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_NEAREST)
    gl.glTexParameteri(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_NEAREST)
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGBA32F, SCR_WIDTH, SCR_HEIGHT, 0, gl.GL_RGBA, gl.GL_FLOAT, None)
    gl.glBindImageTexture(0, some_UAV, 0, gl.GL_FALSE, 0, gl.GL_READ_WRITE, gl.GL_RGBA32F)

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

    gl.glDisable(gl.GL_CULL_FACE)
    gl.glDisable(gl.GL_DEPTH_TEST)

    while not glfw.window_should_close(window):
        CSG.use()
        gl.glDispatchCompute(SCR_WIDTH // 8, SCR_HEIGHT // 8, 1)
        gl.glMemoryBarrier(gl.GL_SHADER_IMAGE_ACCESS_BARRIER_BIT)

        SplatProgram.use()
        SplatProgram.set_int("Whatever", 0)
        gl.glDrawArrays(gl.GL_TRIANGLES, 0, 3)

        glfw.swap_buffers(window)
        glfw.poll_events()

    glfw.terminate()
Пример #26
0
 def _register_callbacks(self, window):
     glfw.set_window_size_callback(window, self._on_set_window_size)
     glfw.set_window_pos_callback(window, self._on_set_window_pos)
     glfw.set_framebuffer_size_callback(window,
                                        self._on_set_frame_buffer_size)
     glfw.set_mouse_button_callback(window, self._on_set_mouse_button)
     glfw.set_cursor_pos_callback(window, self._on_set_cursor_pos)
     glfw.set_scroll_callback(window, self._on_set_scroll)
     glfw.set_window_close_callback(window, self._on_set_window_close)
    def __create_window(self):
        window = glfw.create_window(self.width, self.height, self.window_title,
                                    None, None)

        glfw.set_window_pos(window, 400, 200)
        glfw.set_window_size_callback(window, self.__resize_window)
        glfw.make_context_current(window)

        return window
Пример #28
0
    def __init__(self,
                 width: int = 100,
                 height: int = 100,
                 title: str = "PyGameEngine Window",
                 fps_limit: int = 60,
                 resizable: bool = True,
                 max_width: int = GLFW_DONT_CARE,
                 min_width: int = GLFW_DONT_CARE,
                 max_height: int = GLFW_DONT_CARE,
                 min_height: int = GLFW_DONT_CARE):
        """
			The window class that all applications should derive from.

			Arguments:
				width      : int  : The width of the window being created.
				height     : int  : The height of the window being created.
				title      : str  : The title of the window being created.
				fps_limit  : int  : The fps limit of the window being created.
				resizable  : bool : Should the glfw window be allowed to resize.
				max_width  : int  : The max width the window can be resized to.
				min_width  : int  : The min width the window can be resized to.
				max_height : int  : The max height the window can be resized to.
				min_height : int  : The min height the window can be resized to.

		"""

        self.width = width
        self.height = height
        self.title = title
        self.fps_limit = fps_limit

        self.__background = (0.0, 0.0, 0.0, 1.0)

        # Try to initialize glfw.
        if not glfw.init():
            raise RuntimeError(
                "RunTimeError: At Window.__init__(): Failed to initialize glfw"
            )

        # Before creating the window tell glfw if the window should be allowed to resize.
        glfw.window_hint(GLFW_RESIZABLE, resizable)

        # Try to create the window.
        self.window = glfw.create_window(self.width, self.height, self.title,
                                         None, None)
        if not self.window:
            glfw.terminate()
            raise RuntimeError(
                "RunTimeError: At Window.__init__(): Failed to create a glfw window"
            )

        # Set a callback function for when the user tries to resize the window.
        glfw.set_window_size_callback(self.window, self.resize)

        # Set the size limits of the window.
        glfwSetWindowSizeLimits(self.window, min_width, min_height, max_width,
                                max_height)
Пример #29
0
    def __init__(self, Name, SizeX, SizeY, MainColor, EdgeColor):
        if not glfw.init():
            return
        self._mainColor = MainColor
        self._edgeColor = EdgeColor
        self.width, self.height = SizeX, SizeY
        '''
        monitors = glfw.get_monitors()
        if len(monitors) > 1:
            monitor = monitors[1]
        else:
            monitor = glfw.get_primary_monitor()
        mode = glfw.get_video_mode(monitor)

        print(mode)
        glfw.window_hint(glfw.RED_BITS, mode[1][0])
        glfw.window_hint(glfw.GREEN_BITS, mode[1][1])
        glfw.window_hint(glfw.BLUE_BITS, mode[1][2])
        glfw.window_hint(glfw.REFRESH_RATE, mode[2])
        glfw.window_hint(glfw.AUTO_ICONIFY, False)
        #glfw.window_hint(glfw.DECORATED, False)
        #GLFW_DECORATED


        self.Window = glfw.create_window(mode[0][0], mode[0][1], Name, monitor, None)
        glfw.set_window_monitor(self.Window, monitor, 0, 0, mode[0][0], mode[0][1], mode[2])
        #print(mode[0][0], mode[0][1], mode[2])
        '''
        glfw.window_hint(glfw.RESIZABLE, GL_FALSE)
        self.Window = glfw.create_window(self.width, self.height, Name, None,
                                         None)
        glfw.make_context_current(self.Window)

        #print(monitors, len(monitors))
        if not self.Window:
            glfw.terminate()
            return

        self.Keys = [False] * 1024
        self.KeyPressed = False
        self.MousePos = np.zeros([2])
        self.MouseButtons = np.zeros([5])
        self.MouseScroll = 0
        self.LeftArrow = False
        self.RightArrow = False
        self.MouseEventFlag = False
        self._lastColor = None
        self.NewDragNDrop = False
        self.CurrentDragNDropPath = "Drag here"

        glfw.set_drop_callback(self.Window, self.drop_callback)
        glfw.set_window_size_callback(self.Window, self.window_resize)
        glfw.set_key_callback(self.Window, self.key_callback)
        glfw.set_mouse_button_callback(self.Window, self.mouse_button_callback)
        glfw.set_cursor_pos_callback(self.Window, self.cursor_pos_callback)
        glfw.set_scroll_callback(self.Window, self.mouse_scroll_callback)
        glClearColor(0.3, 0.1, 0.1, 1.0)
Пример #30
0
    def __init__(self, bodybg_path, texture_path, ans_path="ans_render.png"):
        self.mixValue = 0.3
        if not glfw.init():
            raise Exception("glfw can not be initialized!")

        # creating the window
        self.window = glfw.create_window(1024, 1024, "OpenGL Window", None,
                                         None)
        if not self.window:
            glfw.terminate()
            raise Exception("glfw window can not be created!")
        # set window's position
        glfw.set_window_pos(self.window, 100, 100)

        # set the callback function for window resize
        glfw.set_window_size_callback(self.window, self.window_resize)
        # Install a key handler
        glfw.set_key_callback(self.window, self.on_key)

        # make the context current
        glfw.make_context_current(self.window)

        self.shader = compileProgram(
            compileShader(vertex_src, GL_VERTEX_SHADER),
            compileShader(fragment_src, GL_FRAGMENT_SHADER))
        glUseProgram(self.shader)
        self.vertices = np.array(vertices, dtype=np.float32)
        self.indices = np.array(indices, dtype=np.uint32)
        # Step2: 创建并绑定VBO 对象 传送数据
        VBO = glGenBuffers(1)
        glBindBuffer(GL_ARRAY_BUFFER, VBO)
        glBufferData(GL_ARRAY_BUFFER, self.vertices.nbytes, self.vertices,
                     GL_STATIC_DRAW)
        # Step3: 创建并绑定EBO 对象 传送数据
        EBO = glGenBuffers(1)
        glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, EBO)
        glBufferData(GL_ELEMENT_ARRAY_BUFFER, self.indices.nbytes,
                     self.indices, GL_STATIC_DRAW)
        # Step4: 指定解析方式  并启用顶点属性
        # 顶点位置属性
        glEnableVertexAttribArray(0)
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
                              self.vertices.itemsize * 8, ctypes.c_void_p(0))
        # 顶点颜色属性
        glEnableVertexAttribArray(1)
        glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,
                              self.vertices.itemsize * 8, ctypes.c_void_p(12))
        # 顶点纹理属性
        glEnableVertexAttribArray(2)
        glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE,
                              self.vertices.itemsize * 8, ctypes.c_void_p(24))

        texture = glGenTextures(1)
        glBindTexture(GL_TEXTURE_2D, texture)
        self.texid1 = loadTexture(bodybg_path)
        self.texid2 = loadTexture(texture_path)
        self.path = ans_path
Пример #31
0
def main():
    
    # Initialize the OpenGL pipeline
    #glutInit(sys.argv)

    # Set OpenGL display mode
    #glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH)

    # Set the Window size and position
    #glutInitWindowSize(w_width, w_height)
    #glutInitWindowPosition(50, 100)

    # Create the window with given width, height and title
    if not glfw.init():
        return

    window = glfw.create_window(w_width, w_height, TITLE, 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_window_aspect_ratio(window, 16, 9)
    # Instantiate the sphere object
    s = Sphere(1.0, 0, 0, 0)

    s.init()

    # Set the callback function for display
    #glutDisplayFunc(s.display)

    # Set the callback function for the visibility
    #glutVisibilityFunc(s.visible)

    # Set the callback for special function
    #glutSpecialFunc(s.special)

    # Run the OpenGL main loop
    #glutMainLoop()

    #Main loop
    while not glfw.window_should_close(window):
        #Update
        glfw.poll_events()
        s.update()

        #Render
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        glColor3f(1.0, 1.0, 1.0)
        s.display()
        #Swaps the front and back buffer
        glfw.swap_buffers(window)

    glfw.terminate()
Пример #32
0
def render(vertices_index, borders, underlay, overlays):
    """
    # ---- The main entry of the OpenGL rendering ----
    Input:
        vertices_index: the flatmap vertices drawing order (faces)
        borders: the border buffers objects (flatten) shape list(N, )
        underlay: the underlay buffers object
        overlays: the overlays buffer object (flatten), shape list(N, )
    Returns:
        Draw the scene
    """
    # initialize glfw
    if not glfw.init():
        return

    w_width, w_height = 600, 600
    # glfw.window_hint(glfw.RESIZABLE, GL_FALSE)
    window = glfw.create_window(w_width, w_height, "Cortex Flatmap", None,
                                None)

    if not window:
        glfw.terminate()
        return

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

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

    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    glClearColor(0.0, 0.0, 0.0, 1.0)  # Background color, default black

    glUseProgram(shader)
    glEnable(GL_BLEND)
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
    glDepthMask(GL_FALSE)

    # rendering objects
    render_underlay(underlay, vertices_index,
                    shader)  # -- the underlay rendering
    render_overlays(overlays, vertices_index,
                    shader)  # -- the overlays rendering
    render_borders(borders, shader)  # -- border buffer object

    glDisable(GL_BLEND)  # Disable gl blending from this point
    glDepthMask(GL_TRUE)

    glfw.swap_buffers(window)

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

    glfw.terminate()
Пример #33
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()
Пример #34
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)
Пример #35
0
    def __init__(self):

        # save current working directory
        cwd = os.getcwd()

        # initialize glfw - this changes cwd
        glfw.init()

        # restore cwd
        os.chdir(cwd)

        # version 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_TRUE)
        glfw.window_hint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

        # make a window
        self.width, self.height = 640, 480
        self.aspect = self.width/float(self.height)
        self.win = glfw.create_window(self.width, self.height, "test")
        # make context current
        glfw.make_context_current(self.win)

        # initialize GL
        glViewport(0, 0, self.width, self.height)
        glEnable(GL_DEPTH_TEST)
        glClearColor(0.5, 0.5, 0.5,1.0)

        # set window callbacks
        glfw.set_mouse_button_callback(self.win, self.onMouseButton)
        glfw.set_key_callback(self.win, self.onKeyboard)
        glfw.set_window_size_callback(self.win, self.onSize)        

        # create 3D
        self.scene = Scene()

        # exit flag
        self.exitNow = False
Пример #36
0
def setGLFWOptions(win):
    glfw.make_context_current(win)
    glfw.window_hint(glfw.SAMPLES,4)
    glfw.set_key_callback(win, key_callback);
    glfw.set_cursor_pos_callback(win, cursor_callback);
    glfw.set_window_size_callback(win, WindowSizeCallback);
Пример #37
0
w = glfw.create_window(800, 600, 'test', None, None)

#print("OpenGL version: %d.%d.%d\n" % glfw.get_gl_version())

#glfw.ext.set_icons([(icon_data, icon_width, icon_height)])
glfw.set_window_title(w, "pyglfw test")
#glfw.disable(w, glfw.AUTO_POLL_EVENTS)
#glfw.enable(w, glfw.KEY_REPEAT)

center_x = int(vm[0][0] / 2 - glfw.get_window_size(w)[0] / 2)
center_y = int(vm[0][1] / 2 - glfw.get_window_size(w)[1] / 2)
print( "new window position: {!s}, {!s}".format(center_x, center_y) )
glfw.set_window_pos(w, center_x, center_y)

glfw.set_window_size_callback(w, on_resize)
glfw.set_window_close_callback(w, on_close)
glfw.set_window_refresh_callback(w, on_refresh)
glfw.set_key_callback(w, on_key)
glfw.set_char_callback(w, on_char)
glfw.set_mouse_button_callback(w, on_button)
glfw.set_cursor_pos_callback(w, on_pos)
glfw.set_scroll_callback(w, on_scroll)

while not glfw.window_should_close(w):
    glfw.poll_events()
    
    if glfw.get_key(w, glfw.KEY_E) == glfw.PRESS:
        break
    
    glClear(GL_COLOR_BUFFER_BIT)
Пример #38
0
def main():
    import os
    import sys
    os.chdir(os.path.dirname(__file__))

    import glfw
    import time
    from engine import Engine

    # Initialize the library
    if not glfw.init():
        sys.exit()

    glfw.window_hint(glfw.CONTEXT_VERSION_MAJOR, 4)
    glfw.window_hint(glfw.CONTEXT_VERSION_MINOR, 3)
    glfw.window_hint(glfw.SAMPLES, 16)

    # Create a windowed mode window and its OpenGL context
    window = glfw.create_window(640, 480, "Window Name", None, None)
    if not window:
        print "Couldn't initialize OpenGL. Check that your OpenGL version >4.3."
        glfw.terminate()
        sys.exit()

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

    # Get window size
    width, height = glfw.get_framebuffer_size(window)

    # Create engine
    engine = Engine(window)
    engine.setWindowHeight(height)
    engine.setWindowWidth(width)

    def on_resize(window, width, height):
        engine.setWindowWidth(width)
        engine.setWindowHeight(height)

    # Install a window size handler
    glfw.set_window_size_callback(window, on_resize)

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

    # Install a key handler
    glfw.set_key_callback(window, on_key)

    def on_mouse(window, button, action, mods):
        if button == glfw.MOUSE_BUTTON_1 and action == glfw.PRESS:
            engine.shoot_on()
        if button == glfw.MOUSE_BUTTON_1 and action == glfw.RELEASE:
            engine.shoot_off()
        if button == glfw.MOUSE_BUTTON_2 and action == glfw.PRESS:
            engine.camera_switch()

    glfw.set_mouse_button_callback(window, on_mouse)

    def on_scroll(window, x, y):
        engine.camera_scroll(y)

    glfw.set_scroll_callback(window, on_scroll)

    old_time = time.time()
    elapsed_time = 0.0

    # Loop until the user closes the window
    while not glfw.window_should_close(window):
        # Calculate elapsed time
        elapsed_time = time.time() - old_time
        old_time = time.time()

        # Process
        engine.step(elapsed_time)

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

        # Poll for and process events
        glfw.poll_events()

        # Don't be egoist :)
        time.sleep(0.01)

    glfw.terminate()