예제 #1
0
def setup_glfw(title="poolvr.py 0.0.1",
               window_size=(800,600),
               double_buffered=False,
               multisample=4,
               fullscreen=False):
    if not glfw.Init():
        raise Exception('failed to initialize glfw')
    if not double_buffered:
        glfw.WindowHint(glfw.DOUBLEBUFFER, False)
        glfw.SwapInterval(0)
    if multisample:
        glfw.WindowHint(glfw.SAMPLES, multisample)
    width, height = window_size
    if fullscreen:
        window = glfw.CreateWindow(width, height, title, glfw.GetPrimaryMonitor())
    else:
        window = glfw.CreateWindow(width, height, title)
    if not window:
        glfw.Terminate()
        raise Exception('failed to create glfw window')
    glfw.MakeContextCurrent(window)
    _logger.info('GL_VERSION: %s', gl.glGetString(gl.GL_VERSION))
    renderer = OpenGLRenderer(window_size=(width, height), znear=0.1, zfar=1000)
    def on_resize(renderer, window, width, height):
        gl.glViewport(0, 0, width, height)
        renderer.window_size[:] = (width, height)
        renderer.update_projection_matrix()
    from functools import partial
    on_resize = partial(on_resize, renderer)
    glfw.SetWindowSizeCallback(window, on_resize)
    renderer.init_gl()
    on_resize(window, window_size[0], window_size[1])
    return window, renderer
예제 #2
0
    def __init__(self,
                 width,
                 height,
                 title='',
                 samples=1,
                 monitor=0,
                 fullscreen=False):
        self._width = width
        self._height = height
        self._title = title

        if not glfw.Init():
            log.error('Glfw Init failed!')
            raise RuntimeError('Glfw Init failed!')
        else:
            log.debug('Glfw Initialized.')

        glfw.WindowHint(glfw.SAMPLES, samples)

        self._window = glfw.CreateWindow(
            self._width, self._height, self._title,
            glfw.GetMonitors()[monitor] if fullscreen else None, None)

        glfw.MakeContextCurrent(self._window)
        if not glInitBindlessTextureNV():
            log.error('Bindless textures not supported!')
            raise RuntimeError('Bindless textures not supported!')
        else:
            log.debug('Bindless textures supported.')

        self.center_pos(monitor)

        self._previous_second = glfw.GetTime()
        self._frame_count = 0.0
예제 #3
0
def setup_glfw(width=800,
               height=600,
               double_buffered=False,
               title="poolvr.py 0.0.1",
               multisample=0):
    if not glfw.Init():
        raise Exception('failed to initialize glfw')
    if not double_buffered:
        glfw.WindowHint(glfw.DOUBLEBUFFER, False)
        glfw.SwapInterval(0)
    if multisample:
        glfw.WindowHint(glfw.SAMPLES, multisample)
    window = glfw.CreateWindow(width, height, title)
    if not window:
        glfw.Terminate()
        raise Exception('failed to create glfw window')
    glfw.MakeContextCurrent(window)
    _logger.info('GL_VERSION: %s', gl.glGetString(gl.GL_VERSION))
    renderer = OpenGLRenderer(window_size=(width, height),
                              znear=0.1,
                              zfar=1000)

    def on_resize(window, width, height):
        gl.glViewport(0, 0, width, height)
        renderer.window_size = (width, height)
        renderer.update_projection_matrix()

    glfw.SetWindowSizeCallback(window, on_resize)
    return window, renderer
예제 #4
0
    def __init__(self, window_width, window_height, samples, window_title):
        self.window_title = window_title
        assert glfw.Init(), 'Glfw Init failed!'
        glfw.WindowHint(glfw.SAMPLES, samples)
        self.windowID = glfw.CreateWindow(window_width, window_height,
                                          self.window_title, None)
        assert self.windowID, 'Could not create Window!'
        glfw.MakeContextCurrent(self.windowID)
        assert glInitBindlessTextureNV(), 'Bindless Textures not supported!'
        self.framebuf_width, self.framebuf_height = glfw.GetFramebufferSize(
            self.windowID)

        def framebuffer_size_callback(window, w, h):
            self.framebuf_width, self.framebuf_height = w, h

        glfw.SetFramebufferSizeCallback(self.windowID,
                                        framebuffer_size_callback)

        def key_callback(window, key, scancode, action, mode):
            if action == glfw.PRESS:
                if key == glfw.KEY_ESCAPE:
                    glfw.SetWindowShouldClose(window, True)

        glfw.SetKeyCallback(self.windowID, key_callback)

        self.previous_second = glfw.GetTime()
        self.frame_count = 0.0

        glColorMask(GL_TRUE, GL_TRUE, GL_TRUE, GL_TRUE)
        glDisable(GL_STENCIL_TEST)
        glDisable(GL_BLEND)
        glDisable(GL_CULL_FACE)
        glClearColor(0.0, 0.0, 0.0, 1.0)
        glEnable(GL_LINE_SMOOTH)
        glEnable(GL_POLYGON_SMOOTH)
예제 #5
0
파일: tests.py 프로젝트: timweckx/cyglfw3
 def test_get_monitors_test_fullscreen(self):
     monitors = glfw.GetMonitors()
     for monitor in monitors:
         self.assertIsInstance(glfw.GetMonitorName(monitor), str)
         x, y = glfw.GetMonitorPos(monitor)
         width, height = glfw.GetMonitorPhysicalSize(monitor)
         window = glfw.CreateWindow(width, height, 'Monitors', monitor)
         glfw.DestroyWindow(window)
예제 #6
0
def _create_off_screen_window():
    glfw.WindowHint(glfw.VISIBLE, GL_FALSE)
    window = glfw.CreateWindow(239, 239,
                               'GLFW offscreen window for GL context')
    assert window is not None
    logger.debug('GLFW offscreen window for GL context created!')
    glfw.DefaultWindowHints()
    return window
    def __init__(self):
        assert glfw.Init(), 'Glfw Init failed!'
        glfw.WindowHint(glfw.VISIBLE, False);
        self._offscreen_context = glfw.CreateWindow(1, 1, "", None)
        assert self._offscreen_context, 'Could not create Offscreen Context!'
        glfw.MakeContextCurrent(self._offscreen_context)

        self.previous_second = glfw.GetTime()
        self.frame_count = 0.0
        self._fps = 0.0
예제 #8
0
def setup_glfw(width=800, height=600, double_buffered=False):
    if not glfw.Init():
        raise Exception('failed to initialize glfw')
    if not double_buffered:
        glfw.WindowHint(glfw.DOUBLEBUFFER, False)
        glfw.SwapInterval(0)
    window = glfw.CreateWindow(width, height, "gltfview")
    if not window:
        glfw.Terminate()
        raise Exception('failed to create glfw window')
    glfw.MakeContextCurrent(window)
    _logger.info('GL_VERSION: %s' % gl.glGetString(gl.GL_VERSION))
    return window
예제 #9
0
def test_vcgl(frame_block=None):
    # save current working directory
    cwd = os.getcwd()

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

    # restore cwd
    os.chdir(cwd)

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

    # make a window
    win = glfw.CreateWindow(WIDTH, HEIGHT, TITLE)

    # make context current
    glfw.MakeContextCurrent(win)

    glClearColor(0.5, 0.5, 0.5, 1.0)

    renderer = TextureRenderer()
    renderer.prepare()

    fps_checker = FPSChecker()

    webcam = Webcam()
    with webcam:
        while not glfw.WindowShouldClose(win):
            frame = webcam.frame
            if frame_block:
                frame = frame_block(frame)
            fps_checker.lab(frame)

            frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            frame = frame[::-1, ...]
            renderer.image = frame

            glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
            renderer.render()

            glfw.SwapBuffers(win)

            # Poll for and process events
            glfw.PollEvents()

    glfw.Terminate()
예제 #10
0
def main():
    appName = 'First App'

    glfw.Init()
    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)

    window = glfw.CreateWindow(800, 800, appName)
    glfw.SetWindowSizeCallback(window, window_size_callback)
    glfw.SetKeyCallback(window, key_callback)
    glfw.MakeContextCurrent(window)
    glfw.SwapInterval(1)

    try:
        initOpenGL()
    except Exception as e:
        print(e)
        exit(1)

    prevTime = time()
    frameCount = 0
    frameTimeSum = 0
    lastUpdateTime = prevTime
    while not glfw.WindowShouldClose(window):
        glfw.PollEvents()
        display(window)
        glfw.SwapBuffers(window)
        curTime = time()
        frameTime = (curTime - prevTime)
        # if frameTime != 0: print(1 / frameTime)
        sleep(0.016)

        if curTime - lastUpdateTime > 1:
            glfw.SetWindowTitle(
                window, '%s, FPS: %s' %
                (appName, str(round(frameCount / frameTimeSum))))
            frameCount = 0
            frameTimeSum = 0
            lastUpdateTime = curTime

        frameTimeSum += frameTime
        frameCount += 1
        prevTime = curTime

    glfw.DestroyWindow(window)
    glfw.Terminate()
예제 #11
0
    def _initialize(self):
        # save current working directory
        cwd = os.getcwd()

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

        # restore cwd
        os.chdir(cwd)

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

        # make a window
        self._win = glfw.CreateWindow(self._width, self._height, self._title)
예제 #12
0
def main():
    # save current working directory
    cwd = os.getcwd()

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

    # restore cwd
    os.chdir(cwd)

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

    # make a window
    win = glfw.CreateWindow(512, 512, b'simpleglfw')

    # make context current
    glfw.MakeContextCurrent(win)

    glClearColor(0.5, 0.5, 0.5, 1.0)

    # renderer = TriangleRenderer()
    # renderer = RectangleRenderer()
    with Image.open('./image/psh.jpg') as img:
        data = np.asarray(img, dtype='uint8')
        data = data[::-1, ...]
        renderer = TextureRenderer(image=data)

    renderer.prepare()
    while not glfw.WindowShouldClose(win):
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)

        renderer.render()
        glfw.SwapBuffers(win)

        # Poll for and process events
        glfw.PollEvents()

    glfw.Terminate()
예제 #13
0
    def __init__(self, width=1024, height=1024, title="vol_render"):
        curdir = os.getcwd()
        glfw.Init()
        # glfw sometimes changes the current working directory, see
        # https://github.com/adamlwgriffiths/cyglfw3/issues/21
        os.chdir(curdir)
        glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 3)
        glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 3)
        glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, True)
        glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
        self.window = glfw.CreateWindow(width, height, title)
        if not self.window:
            glfw.Terminate()
            exit()

        glfw.MakeContextCurrent(self.window)
        GL.glClearColor(0.0, 0.0, 0.0, 0.0)
        GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)
        glfw.SwapBuffers(self.window)
        glfw.PollEvents()
예제 #14
0
 def init_gl(self):
     if self._is_initialized:
         return
     if not glfw.Init():
         raise RuntimeError("GLFW Initialization failed")
     glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 4)
     glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 1)
     glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
     glfw.WindowHint(glfw.DOUBLEBUFFER, False)
     glfw.SwapInterval(0)
     self.window = glfw.CreateWindow(self.renderer.window_size[0],
                                     self.renderer.window_size[1],
                                     self.title)
     if self.window is None:
         glfw.Terminate()
         raise RuntimeError("GLFW Window creation failed")
     glfw.SetKeyCallback(self.window, self.key_callback)
     glfw.MakeContextCurrent(self.window)
     if self.renderer is not None:
         self.renderer.init_gl()
     self._is_initialized = True
예제 #15
0
    def init(self):
        assert glfw.Init(), 'Glfw Init failed!'
        self.window = glfw.CreateWindow(self._window_size[0],
                                        self._window_size[1], self._title,
                                        None)
        glfw.WindowHint(glfw.SAMPLES, 4)
        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)

        glfw.MakeContextCurrent(self.window)
        glfw.SetInputMode(self.window, glfw.STICKY_KEYS, True)

        # Enable depth test
        glEnable(GL_DEPTH_TEST)
        glEnable(GL_TEXTURE_3D)
        # Accept fragment if it closer to the camera than the former one
        glDepthFunc(GL_LESS)
        # disable vsync
        glfw.SwapInterval(0)
        self._init_shaders()
예제 #16
0
파일: tests.py 프로젝트: timweckx/cyglfw3
 def test_create_window(self):
     window = glfw.CreateWindow(640, 480, 'Create')
     glfw.DestroyWindow(window)
예제 #17
0
def create_window(width=640, height=480, title='Triangulum3D'):
    window = glfw.CreateWindow(width, height, title)
    assert window is not None
    logger.debug('GLFW window created! ({}x{} "{}")'.format(
        width, height, title))
    return window
예제 #18
0
import glm

import OpenGL.GL as gl
import OpenGL.GL.shaders as shaders

# initialize glfw

glfw.Init()

# this makes opengl work on mac (https://developer.apple.com/library/content/documentation/GraphicsImaging/Conceptual/OpenGL-MacProgGuide/UpdatinganApplicationtoSupportOpenGL3/UpdatinganApplicationtoSupportOpenGL3.html)
glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 3)
glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 3)
glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)
glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

window = glfw.CreateWindow(800, 600, 'mac')
glfw.MakeContextCurrent(window)

# initialize shaders

vertex_shader = """
#version 330
layout (location = 0) in vec4 position;
layout (location = 1) in vec4 color;

out vec4 vertexColor;

void main()
{
   gl_Position = position;
   vertexColor = color;
예제 #19
0
    def __init__(self,
                 window_width,
                 window_height,
                 samples=1,
                 window_title="",
                 monitor=1,
                 show_at_center=True,
                 offscreen=False):
        self.window_title = window_title
        assert glfw.Init(), "Glfw Init failed!"
        glfw.WindowHint(glfw.SAMPLES, samples)
        if offscreen:
            glfw.WindowHint(glfw.VISIBLE, False)
        mon = glfw.GetMonitors()[monitor] if monitor != None else None
        self.windowID = glfw.CreateWindow(window_width, window_height,
                                          self.window_title, mon)
        assert self.windowID, "Could not create Window!"
        glfw.MakeContextCurrent(self.windowID)

        if not glInitBindlessTextureNV():
            raise RuntimeError("Bindless Textures not supported")

        self.framebuf_width, self.framebuf_height = glfw.GetFramebufferSize(
            self.windowID)
        self.framebuffer_size_callback = []

        def framebuffer_size_callback(window, w, h):
            self.framebuf_width, self.framebuf_height = w, h
            for callback in self.framebuffer_size_callback:
                callback(w, h)

        glfw.SetFramebufferSizeCallback(self.windowID,
                                        framebuffer_size_callback)

        self.key_callback = []

        def key_callback(window, key, scancode, action, mode):
            if action == glfw.PRESS:
                if key == glfw.KEY_ESCAPE:
                    glfw.SetWindowShouldClose(window, True)
            for callback in self.key_callback:
                callback(key, scancode, action, mode)

        glfw.SetKeyCallback(self.windowID, key_callback)

        self.mouse_callback = []

        def mouse_callback(window, xpos, ypos):
            for callback in self.mouse_callback:
                callback(xpos, ypos)

        glfw.SetCursorPosCallback(self.windowID, mouse_callback)

        self.mouse_button_callback = []

        def mouse_button_callback(window, button, action, mods):
            for callback in self.mouse_button_callback:
                callback(button, action, mods)

        glfw.SetMouseButtonCallback(self.windowID, mouse_button_callback)

        self.scroll_callback = []

        def scroll_callback(window, xoffset, yoffset):
            for callback in self.scroll_callback:
                callback(xoffset, yoffset)

        glfw.SetScrollCallback(self.windowID, scroll_callback)

        self.previous_second = glfw.GetTime()
        self.frame_count = 0.0

        if show_at_center:
            monitors = glfw.GetMonitors()
            assert monitor >= 0 and monitor < len(
                monitors), "Invalid monitor selected."
            vidMode = glfw.GetVideoMode(monitors[monitor])
            glfw.SetWindowPos(
                self.windowID,
                vidMode.width / 2 - self.framebuf_width / 2,
                vidMode.height / 2 - self.framebuf_height / 2,
            )
W = 1024
H = int(W / (16./9.))
window_title = "OpenGL Test"
monitor = 0

def glfw_error_callback(code, description):
    print 'GLFW Error', code, description
    exit(-1)

glfw.SetErrorCallback(glfw_error_callback)

assert glfw.Init()

glfw.WindowHint(glfw.SAMPLES, 16)

window = glfw.CreateWindow(W, H, window_title, None, None)
glfw.MakeContextCurrent(window)

def center_pos(monitor_id, W, H):
    # W, H: window dimensions
    mon = glfw.GetMonitors()
    xpos = glfw.GetMonitorPos(mon[monitor_id])[0]+glfw.GetVideoMode(mon[monitor_id]).width/2-W/2
    ypos = glfw.GetMonitorPos(mon[monitor_id])[1]+glfw.GetVideoMode(mon[monitor_id]).height/2-H/2
    glfw.SetWindowPos(window, xpos, ypos)

center_pos(monitor, W, H)

previous_second = glfw.GetTime()
frame_count = 0.0

def update_fps_counter():
def generate_binary_mask(faces, vertices_2d, width, height):
    if not glfw.Init():
        print('glfw not initialized')
        sys.exit()

    version = 3, 3
    glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, version[0])
    glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, version[1])
    glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, 1)
    glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)
    glfw.WindowHint(glfw.VISIBLE, 1)

    window = glfw.CreateWindow(width, height, 'Quad')
    if not window:
        print('glfw window not created')
        glfw.Terminate()
        sys.exit()

    glfw.MakeContextCurrent(window)

    strVS = """
        #version 330
        layout(location = 0) in vec2 aPosition;

        void main() {
            gl_Position = vec4(vec3(aPosition, 0), 1.0);
        }
        """
    strFS = """
        #version 330
        out vec3 fragColor;

        void main() {
            fragColor = vec3(0, 1, 0);
        }
        """

    program = glutils.loadShaders(strVS, strFS)
    glUseProgram(program)

    element_array = np.reshape(faces, -1)
    elementData = np.array(element_array, np.uint32)

    vertex_array = np.reshape(vertices_2d, -1)
    vertexData = np.array(vertex_array, np.float32)

    vao = glGenVertexArrays(1)
    glBindVertexArray(vao)

    ebo = glGenBuffers(1)
    glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, ebo)
    glBufferData(GL_ELEMENT_ARRAY_BUFFER, 4 * len(elementData), elementData, GL_STATIC_DRAW)

    vbo = glGenBuffers(1)
    glBindBuffer(GL_ARRAY_BUFFER, vbo)
    glBufferData(GL_ARRAY_BUFFER, 4 * len(vertexData), vertexData, GL_STATIC_DRAW)

    glEnableVertexAttribArray(0)
    glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, None)

    glBindVertexArray(0)

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

    glUseProgram(program)
    glBindVertexArray(vao)
    glDrawElements(GL_TRIANGLES, len(element_array), GL_UNSIGNED_INT, None)
    glBindVertexArray(0)

    glPixelStorei(GL_PACK_ALIGNMENT, 1)
    pixel_data = glReadPixels(0, 0, width, height, GL_RGB, GL_UNSIGNED_BYTE, outputType=None)

    im = np.array(pixel_data)
    mask = Image.frombuffer('RGB', (width, height), im, 'raw', 'RGB')
    mask = np.array(mask)
    glfw.Terminate()
    return mask
예제 #22
0
파일: tests.py 프로젝트: timweckx/cyglfw3
 def test_should_close(self):
     window = glfw.CreateWindow(640, 480, 'Should close')
     glfw.SetWindowShouldClose(window, True)
     self.assertTrue(glfw.WindowShouldClose(window))
     glfw.DestroyWindow(window)
예제 #23
0
파일: tests.py 프로젝트: timweckx/cyglfw3
 def test_window_share(self):
     # test the window parameter of the createWindow function
     window = glfw.CreateWindow(640, 480, 'Share2', window=self.window)
     glfw.DestroyWindow(window)
예제 #24
0
파일: tests.py 프로젝트: timweckx/cyglfw3
 def setUpClass(cls):
     glfw.Init()
     # we need to avoid creating many window
     # because GLFW / NSApp begins to freak out and will segfault
     # good times, good times
     cls.window = glfw.CreateWindow(640, 480, 'Primary')
예제 #25
0
from assimp import *


# SERGIO MARCHENA
# 16387
# PROYECTO 2
# GRAFICAS POR COMPUTADORA

# config de glfw
glfw.Init()
glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, 3)
glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 3)
glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, gl.GL_TRUE)
glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

window=glfw.CreateWindow(800, 600, 'Sergio Marchena - Proyecto 2 - Graficas por Computadora')
glfw.MakeContextCurrent(window)
clock = pygame.time.Clock()
gl.glEnable(gl.GL_DEPTH_TEST)

# VERTEX SHADER (v330)
vertex_shader="""
#version 330
layout (location = 0) in vec4 vert_pos;
layout (location = 1) in vec4 vert_normal;
layout (location = 2) in vec2 vert_texture_coords;
uniform mat4 model_mat;
uniform mat4 view_mat;
uniform mat4 projection_mat;
uniform vec4 color;
uniform vec4 light;
예제 #26
0
                uniforms.append(m['uniform_name'])
            cls._UNIFORMS = uniforms


if __name__ == "__main__":
    import cyglfw3 as glfw
    _DEBUG_LOGGING_FORMAT = '%(asctime).19s [%(levelname)s]%(name)s.%(funcName)s:%(lineno)d: %(message)s'
    logging.basicConfig(format=_DEBUG_LOGGING_FORMAT, level=logging.DEBUG)
    opengl_logger = logging.getLogger('OpenGL')
    opengl_logger.setLevel(logging.INFO)
    pil_logger = logging.getLogger('PIL')
    pil_logger.setLevel(logging.WARNING)
    text_drawer = TextRenderer()
    glfw.Init()
    w, h = 800, 600
    window = glfw.CreateWindow(w, h, os.path.basename(__file__))
    glfw.MakeContextCurrent(window)
    gl.glClearColor(0.1, 0.1, 0.2, 0.0)
    text_drawer.init_gl()

    def on_keydown(window, key, scancode, action, mods):
        if key == glfw.KEY_ESCAPE and action == glfw.PRESS:
            glfw.SetWindowShouldClose(window, gl.GL_TRUE)

    glfw.SetKeyCallback(window, on_keydown)

    def on_resize(window, width, height):
        gl.glViewport(0, 0, width, height)
        gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
        text_drawer.set_screen_size((width, height))
예제 #27
0
    def __init__(self):
        glfw.Init()  #Init glfw
        glfw.WindowHint(
            glfw.CONTEXT_VERSION_MAJOR,
            3)  #set openGL context version to 3.3 (the latest we can support)
        glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, 3)
        glfw.WindowHint(
            glfw.OPENGL_FORWARD_COMPAT, GL_TRUE
        )  #tell OSX we don't give a shit about compatibility and want the newer GLSL versions
        glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

        self.width, self.height = 1440, 900
        self.aspect = self.width / float(self.height)
        self.win = glfw.CreateWindow(self.width, self.height, "test")
        #self.win = glfw.CreateWindow(self.width, self.height, "test", glfw.GetPrimaryMonitor(), None)
        self.exitNow = False
        glfw.MakeContextCurrent(self.win)

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

        #glfw.SetMouseButtonCallback(self.win, self.onMouseButton)
        glfw.SetKeyCallback(self.win, self.keyPressed)
        #glfw.SetWindowSizeCallback(self.win, self.onSize)

        self.objs = []
        self.callbacks = {'keyPressed': [], 'keyReleased': [], 'logic': []}
        self.objs.append(Box(0, 0))
        player = Player()
        self.objs.append(player)
        self.callbacks['keyPressed'].append(player.getCallback('keyPressed'))
        self.callbacks['keyReleased'].append(player.getCallback('keyReleased'))
        self.callbacks['logic'].append(player.getCallback('logic'))
        #self.callbacks['keyReleased'].append(player.getCallbacks(['keyReleased']))
        for obj in self.objs:
            obj.geomArray = numpy.array(obj.geom, numpy.float32)
            obj.vao = vertex_array_object.glGenVertexArrays(1)
            glBindVertexArray(obj.vao)
            obj.vBuff = glGenBuffers(1)
            glBindBuffer(GL_ARRAY_BUFFER, obj.vBuff)
            glBufferData(GL_ARRAY_BUFFER, 4 * len(obj.geom), obj.geomArray,
                         GL_DYNAMIC_DRAW)
            glEnableVertexAttribArray(0)
            glVertexAttribPointer(
                0, 3, GL_FLOAT, GL_FALSE, 0,
                None)  #set the size & type of the argument to the shader

            #compile shaders
            obj.vertShader = shaders.compileShader(obj.vertShaderString,
                                                   GL_VERTEX_SHADER)
            obj.fragShader = shaders.compileShader(obj.fragShaderString,
                                                   GL_FRAGMENT_SHADER)
            try:
                obj.shader = shaders.compileProgram(obj.vertShader,
                                                    obj.fragShader)
            except (GLError, RuntimeError) as err:
                print err

            glBindVertexArray(0)  #unbind our VAO

        self.colorOffset = 255 * 3
        self.OnInit()
예제 #28
0
if not glfw.Init():
    exit()

version = (4, 0)
glfw.WindowHint(glfw.CLIENT_API, glfw.OPENGL_API)
major, minor = version
glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, major)
glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, minor)
glfw.WindowHint(glfw.CONTEXT_ROBUSTNESS, glfw.NO_ROBUSTNESS)
glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, 1)
glfw.WindowHint(glfw.OPENGL_DEBUG_CONTEXT, 1)
glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

window_size = (640, 480)
window = glfw.CreateWindow(window_size[0], window_size[1], 'Bast')
if not window:
    glfw.Terminate()
    exit()

glfw.MakeContextCurrent(window)

from OpenGL import GL


def redirector(fn):
    def func(*args, **kwargs):
        print('{}({}, {})'.format(fn.__name__, args, kwargs))
        return fn(*args, **kwargs)

    return func
예제 #29
0
print("""
Some platforms may not support backward compatibility mode, notably OS-X.
If this crashes, your system does not support this mode.

Unfortunately PyOpenGL doesn't always handle error cases well.
""")

version = 3,2

glfw.WindowHint(glfw.CONTEXT_VERSION_MAJOR, version[0])
glfw.WindowHint(glfw.CONTEXT_VERSION_MINOR, version[1])
glfw.WindowHint(glfw.OPENGL_FORWARD_COMPAT, 0)
glfw.WindowHint(glfw.OPENGL_PROFILE, glfw.OPENGL_CORE_PROFILE)

window = glfw.CreateWindow(640, 480, 'Hello World')
if not window:
    glfw.Terminate()
    print('Failed to create window')
    exit()

glfw.MakeContextCurrent(window)
print('GL:',GL.glGetString(GL.GL_VERSION))
print('GLFW3:',glfw.GetVersionString())
for iteration in range(100):
    if glfw.WindowShouldClose(window):
        break
    GL.glClearColor(0.2, 0.2, 0.2, 1.0)
    GL.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT)

    glfw.SwapBuffers(window)
예제 #30
0
from Texture import Texture
from Camera import Camera
from Light import DirLight
import thread
import rospy
from sensor_msgs.msg import Image
from cv_bridge import CvBridge, CvBridgeError
import cv2
bridge = CvBridge()

window_width, window_height = 640, 480
samples = 16
window_title = 'OpenCV+OpenGL'
assert glfw.Init(), 'Glfw Init failed!'
glfw.WindowHint(glfw.SAMPLES, samples)
window = glfw.CreateWindow(window_width, window_height, window_title, None)
assert window, 'Could not create Window!'
glfw.MakeContextCurrent(window)
assert glInitBindlessTextureNV(), 'Bindless Textures not supported!'
framebuf_width, framebuf_height = glfw.GetFramebufferSize(window)
def framebuffer_size_callback(window, w, h):
    global framebuf_width, framebuf_height
    framebuf_width, framebuf_height = w, h
glfw.SetFramebufferSizeCallback(window, framebuffer_size_callback)
def key_callback(window, key, scancode, action, mode):
    if action == glfw.PRESS:
        if key == glfw.KEY_ESCAPE:
            glfw.SetWindowShouldClose(window, True)
glfw.SetKeyCallback(window, key_callback)

previous_second = glfw.GetTime(); frame_count = 0.0