예제 #1
0
파일: test_app.py 프로젝트: vanossj/vispy
def test_event_order():
    """Test event order"""
    x = list()

    class MyCanvas(Canvas):
        def on_initialize(self, event):
            x.append('init')

        def on_draw(self, event):
            sz = True if self.size is not None else False
            x.append('draw size=%s show=%s' % (sz, show))

        def on_close(self, event):
            x.append('close')

    for show in (False, True):
        # clear our storage variable
        while x:
            x.pop()
        with MyCanvas(show=show) as c:
            c.update()
            c.app.process_events()

        print(x)
        assert_true(len(x) >= 3)
        assert_equal(x[0], 'init')
        assert_in('draw size=True', x[1])
        assert_in('draw size=True', x[-2])
        assert_equal(x[-1], 'close')
예제 #2
0
파일: test_app.py 프로젝트: Eric89GXL/vispy
def test_event_order():
    """Test event order"""
    x = list()

    class MyCanvas(Canvas):
        def on_initialize(self, event):
            x.append('init')

        def on_draw(self, event):
            sz = True if self.size is not None else False
            x.append('draw size=%s show=%s' % (sz, show))

        def on_close(self, event):
            x.append('close')

    for show in (False, True):
        # clear our storage variable
        while x:
            x.pop()
        with MyCanvas(show=show) as c:
            c.update()
            c.app.process_events()

        print(x)
        assert_true(len(x) >= 3)
        assert_equal(x[0], 'init')
        assert_in('draw size=True', x[1])
        assert_in('draw size=True', x[-2])
        assert_equal(x[-1], 'close')
예제 #3
0
def test_wrappers():
    """Test gloo wrappers"""
    with Canvas():
        gl.use_gl('gl2 debug')
        gloo.clear('#112233')  # make it so that there's something non-zero
        # check presets
        assert_raises(ValueError, gloo.set_state, preset='foo')
        for state in gloo.get_state_presets().keys():
            gloo.set_state(state)
        assert_raises(ValueError, gloo.set_blend_color, (0., 0.))  # bad color
        assert_raises(TypeError, gloo.set_hint, 1, 2)  # need strs
        # this doesn't exist in ES 2.0 namespace
        assert_cmd_raises(ValueError, gloo.set_hint, 'fog_hint', 'nicest')
        # test bad enum
        assert_raises(RuntimeError, gloo.set_line_width, -1)

        # check read_pixels
        x = gloo.read_pixels()
        assert_true(isinstance(x, np.ndarray))
        assert_true(isinstance(gloo.read_pixels((0, 0, 1, 1)), np.ndarray))
        assert_raises(ValueError, gloo.read_pixels, (0, 0, 1))  # bad port
        y = gloo.read_pixels(alpha=False, out_type=np.ubyte)
        assert_equal(y.shape, x.shape[:2] + (3, ))
        assert_array_equal(x[..., :3], y)
        y = gloo.read_pixels(out_type='float')
        assert_allclose(x / 255., y)

        # now let's (indirectly) check our set_* functions
        viewport = (0, 0, 1, 1)
        blend_color = (0., 0., 0.)
        _funs = dict(
            viewport=viewport,  # checked
            hint=('generate_mipmap_hint', 'nicest'),
            depth_range=(1., 2.),
            front_face='cw',  # checked
            cull_face='front',
            line_width=1.,
            polygon_offset=(1., 1.),
            blend_func=('zero', 'one'),
            blend_color=blend_color,
            blend_equation='func_add',
            scissor=(0, 0, 1, 1),
            stencil_func=('never', 1, 2, 'back'),
            stencil_mask=4,
            stencil_op=('zero', 'zero', 'zero', 'back'),
            depth_func='greater',
            depth_mask=True,
            color_mask=(True, True, True, True),
            sample_coverage=(0.5, True))
        gloo.set_state(**_funs)
        gloo.clear((1., 1., 1., 1.), 0.5, 1)
        gloo.flush()
        gloo.finish()
        # check some results
        assert_array_equal(gl.glGetParameter(gl.GL_VIEWPORT), viewport)
        assert_equal(gl.glGetParameter(gl.GL_FRONT_FACE), gl.GL_CW)
        assert_equal(gl.glGetParameter(gl.GL_BLEND_COLOR), blend_color + (1, ))
예제 #4
0
def test_wrappers():
    """Test gloo wrappers"""
    with Canvas():
        gl.use_gl('gl2 debug')
        gloo.clear('#112233')  # make it so that there's something non-zero
        # check presets
        assert_raises(ValueError, gloo.set_state, preset='foo')
        for state in gloo.get_state_presets().keys():
            gloo.set_state(state)
        assert_raises(ValueError, gloo.set_blend_color, (0., 0.))  # bad color
        assert_raises(TypeError, gloo.set_hint, 1, 2)  # need strs
        # this doesn't exist in ES 2.0 namespace
        assert_cmd_raises(ValueError, gloo.set_hint, 'fog_hint', 'nicest')
        # test bad enum
        assert_raises(RuntimeError, gloo.set_line_width, -1)

        # check read_pixels
        x = gloo.read_pixels()
        assert_true(isinstance(x, np.ndarray))
        assert_true(isinstance(gloo.read_pixels((0, 0, 1, 1)), np.ndarray))
        assert_raises(ValueError, gloo.read_pixels, (0, 0, 1))  # bad port
        y = gloo.read_pixels(alpha=False, out_type=np.ubyte)
        assert_equal(y.shape, x.shape[:2] + (3,))
        assert_array_equal(x[..., :3], y)
        y = gloo.read_pixels(out_type='float')
        assert_allclose(x/255., y)

        # now let's (indirectly) check our set_* functions
        viewport = (0, 0, 1, 1)
        blend_color = (0., 0., 0.)
        _funs = dict(viewport=viewport,  # checked
                     hint=('generate_mipmap_hint', 'nicest'),
                     depth_range=(1., 2.),
                     front_face='cw',  # checked
                     cull_face='front',
                     line_width=1.,
                     polygon_offset=(1., 1.),
                     blend_func=('zero', 'one'),
                     blend_color=blend_color,
                     blend_equation='func_add',
                     scissor=(0, 0, 1, 1),
                     stencil_func=('never', 1, 2, 'back'),
                     stencil_mask=4,
                     stencil_op=('zero', 'zero', 'zero', 'back'),
                     depth_func='greater',
                     depth_mask=True,
                     color_mask=(True, True, True, True),
                     sample_coverage=(0.5, True))
        gloo.set_state(**_funs)
        gloo.clear((1., 1., 1., 1.), 0.5, 1)
        gloo.flush()
        gloo.finish()
        # check some results
        assert_array_equal(gl.glGetParameter(gl.GL_VIEWPORT), viewport)
        assert_equal(gl.glGetParameter(gl.GL_FRONT_FACE), gl.GL_CW)
        assert_equal(gl.glGetParameter(gl.GL_BLEND_COLOR), blend_color + (1,))
예제 #5
0
def test_key():
    """Test basic key functionality"""
    def bad():
        return (ENTER == dict())
    assert_raises(ValueError, bad)
    assert_true(not (ENTER == None))  # noqa
    assert_equal('Return', ENTER)
    print(ENTER.name)
    print(ENTER)  # __repr__
    assert_equal(Key('1'), 49)  # ASCII code
예제 #6
0
def test_read_pixels():
    """Test read_pixels to ensure that the image is not flipped"""
    # Create vertices
    vPosition = np.array(
        [
            [-1, 1, 0.0],
            [0, 1, 0.5],  # For drawing a square to top left
            [-1, 0, 0.0],
            [0, 0, 0.5]
        ],
        np.float32)

    VERT_SHADER = """ // simple vertex shader
    attribute vec3 a_position;
    void main (void) {
        gl_Position = vec4(a_position, 1.0);
    }
    """

    FRAG_SHADER = """ // simple fragment shader
    void main()
    {
        gl_FragColor = vec4(1,1,1,1);
    }
    """

    with Canvas() as c:
        c.set_current()
        gloo.set_viewport(0, 0, *c.size)
        gloo.set_state(depth_test=True)
        c._program = gloo.Program(VERT_SHADER, FRAG_SHADER)
        c._program['a_position'] = gloo.VertexBuffer(vPosition)
        gloo.clear(color='black')
        c._program.draw('triangle_strip')

        # Check if the return of read_pixels is the same as our drawing
        img = read_pixels(alpha=False)
        assert_equal(img.shape[:2], c.size[::-1])
        top_left = sum(img[0, 0])
        assert_true(top_left > 0)  # Should be > 0 (255*4)
        # Sum of the pixels in top right + bottom left + bottom right corners
        corners = sum(img[0, -1] + img[-1, 0] + img[-1, -1])
        assert_true(corners == 0)  # Should be all 0
        gloo.flush()
        gloo.finish()

        # Check that we can read the depth buffer
        img = read_pixels(mode='depth')
        assert_equal(img.shape[:2], c.size[::-1])
        assert_equal(img.shape[2], 1)
        unique_img = np.unique(img)
        # we should have quite a few different depth values
        assert unique_img.shape[0] > 50
        assert unique_img.max() == 255
        assert unique_img.min() > 0
예제 #7
0
def test_key():
    """Test basic key functionality"""
    def bad():
        return (ENTER == dict())

    assert_raises(ValueError, bad)
    assert_true(not (ENTER == None))  # noqa
    assert_equal('Return', ENTER)
    print(ENTER.name)
    print(ENTER)  # __repr__
    assert_equal(Key('1'), 49)  # ASCII code
예제 #8
0
def test_sys_info():
    """Test printing of system information"""
    fname = op.join(temp_dir, 'info.txt')
    sys_info(fname)
    assert_raises(IOError, sys_info, fname)  # no overwrite
    with open(fname, 'r') as fid:
        out = ''.join(fid.readlines())
    keys = ['GL version', 'Python', 'Backend', 'pyglet', 'Platform:']
    for key in keys:
        assert_in(key, out)
    print(out)
    assert_true('Info-gathering error' not in out)
예제 #9
0
파일: test_config.py 프로젝트: bdvd/vispy
def test_sys_info():
    """Test printing of system information"""
    fname = op.join(temp_dir, "info.txt")
    sys_info(fname)
    assert_raises(IOError, sys_info, fname)  # no overwrite
    with open(fname, "r") as fid:
        out = "".join(fid.readlines())
    keys = ["GL version", "Python", "Backend", "pyglet", "Platform:"]
    for key in keys:
        assert_in(key, out)
    print(out)
    assert_true("Info-gathering error" not in out)
예제 #10
0
 def test_group_ignore(self):
     """EmitterGroup.block_all"""
     grp = EmitterGroup(em1=Event)
     grp.em1.connect(self.error_event)
     with use_log_level('warning', record=True, print_msg=False) as l:
         grp.em1()
     assert_true(len(l) >= 1)
     grp.ignore_callback_errors = False
     assert_raises(RuntimeError, grp.em1)
     grp.ignore_callback_errors = True
     with use_log_level('warning', record=True, print_msg=False) as l:
         grp.em1()
     assert_true(len(l) >= 1)
예제 #11
0
 def test_group_ignore(self):
     """EmitterGroup.block_all"""
     grp = EmitterGroup(em1=Event)
     grp.em1.connect(self.error_event)
     with use_log_level('warning', record=True, print_msg=False) as l:
         grp.em1()
     assert_true(len(l) >= 1)
     grp.ignore_callback_errors = False
     assert_raises(RuntimeError, grp.em1)
     grp.ignore_callback_errors = True
     with use_log_level('warning', record=True, print_msg=False) as l:
         grp.em1()
     assert_true(len(l) >= 1)
예제 #12
0
def _test_setting_stuff():
    # Set stuff to touch functions
    
    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
    #
    gl.glBlendColor(1.0, 1.0, 1.0, 1.0)
    gl.glBlendEquation(gl.GL_FUNC_ADD)
    gl.glBlendEquationSeparate(gl.GL_FUNC_ADD, gl.GL_FUNC_ADD)
    gl.glBlendFunc(gl.GL_ONE, gl.GL_ZERO)
    gl.glBlendFuncSeparate(gl.GL_ONE, gl.GL_ZERO, gl.GL_ONE, gl.GL_ZERO)
    #
    gl.glClearColor(0.0, 0.0, 0.0, 1.0)
    gl.glClearDepth(1)
    gl.glClearStencil(0)
    #
    gl.glColorMask(True, True, True, True)
    gl.glDepthMask(False)
    gl.glStencilMask(255)
    gl.glStencilMaskSeparate(gl.GL_FRONT, 128)
    #
    gl.glStencilFunc(gl.GL_ALWAYS, 0, 255)
    gl.glStencilFuncSeparate(gl.GL_FRONT, gl.GL_ALWAYS, 0, 255)
    gl.glStencilOp(gl.GL_KEEP, gl.GL_KEEP, gl.GL_KEEP)
    gl.glStencilOpSeparate(gl.GL_FRONT, gl.GL_KEEP, gl.GL_KEEP, gl.GL_KEEP)
    #
    gl.glFrontFace(gl.GL_CW)
    gl.glHint(gl.GL_GENERATE_MIPMAP_HINT, gl.GL_FASTEST)
    gl.glLineWidth(2.0)
    gl.glPolygonOffset(0.0, 0.0)
    gl.glSampleCoverage(1.0, False)
    
    # And getting stuff
    try:
        with use_log_level('error', print_msg=False):
            r, p = gl.glGetShaderPrecisionFormat(gl.GL_FRAGMENT_SHADER,
                                                 gl.GL_HIGH_FLOAT)
            gl.check_error()  # Sometimes the func is there but OpenGL errs
    except Exception:
        pass  # accept if the function is not there ...
        # We should catch RuntimeError and GL.error.NullFunctionError,
        # but PyOpenGL may not be available.
        # On Travis this function was not there on one machine according
        # to PyOpenGL, but our desktop backend worked fine ...
        
    #
    v = gl.glGetParameter(gl.GL_VERSION)
    assert_true(isinstance(v, string_types))
    assert_true(len(v) > 0)
    
    gl.check_error()
예제 #13
0
def _test_setting_stuff():
    # Set stuff to touch functions

    gl.glClear(gl.GL_COLOR_BUFFER_BIT)
    #
    gl.glBlendColor(1.0, 1.0, 1.0, 1.0)
    gl.glBlendEquation(gl.GL_FUNC_ADD)
    gl.glBlendEquationSeparate(gl.GL_FUNC_ADD, gl.GL_FUNC_ADD)
    gl.glBlendFunc(gl.GL_ONE, gl.GL_ZERO)
    gl.glBlendFuncSeparate(gl.GL_ONE, gl.GL_ZERO, gl.GL_ONE, gl.GL_ZERO)
    #
    gl.glClearColor(0.0, 0.0, 0.0, 1.0)
    gl.glClearDepth(1)
    gl.glClearStencil(0)
    #
    gl.glColorMask(True, True, True, True)
    gl.glDepthMask(False)
    gl.glStencilMask(255)
    gl.glStencilMaskSeparate(gl.GL_FRONT, 128)
    #
    gl.glStencilFunc(gl.GL_ALWAYS, 0, 255)
    gl.glStencilFuncSeparate(gl.GL_FRONT, gl.GL_ALWAYS, 0, 255)
    gl.glStencilOp(gl.GL_KEEP, gl.GL_KEEP, gl.GL_KEEP)
    gl.glStencilOpSeparate(gl.GL_FRONT, gl.GL_KEEP, gl.GL_KEEP, gl.GL_KEEP)
    #
    gl.glFrontFace(gl.GL_CW)
    gl.glHint(gl.GL_GENERATE_MIPMAP_HINT, gl.GL_FASTEST)
    gl.glLineWidth(2.0)
    gl.glPolygonOffset(0.0, 0.0)
    gl.glSampleCoverage(1.0, False)

    # And getting stuff
    try:
        with use_log_level('error', print_msg=False):
            r, p = gl.glGetShaderPrecisionFormat(gl.GL_FRAGMENT_SHADER,
                                                 gl.GL_HIGH_FLOAT)
            gl.check_error()  # Sometimes the func is there but OpenGL errs
    except Exception:
        pass  # accept if the function is not there ...
        # We should catch RuntimeError and GL.error.NullFunctionError,
        # but PyOpenGL may not be available.
        # On Travis this function was not there on one machine according
        # to PyOpenGL, but our desktop backend worked fine ...

    #
    v = gl.glGetParameter(gl.GL_VERSION)
    assert_true(isinstance(v, string_types))
    assert_true(len(v) > 0)

    gl.check_error()
예제 #14
0
def test_read_pixels():
    """Test read_pixels to ensure that the image is not flipped"""
    # Create vertices
    vPosition = np.array(
        [
            [-1, 1],
            [0, 1],  # For drawing a square to top left
            [-1, 0],
            [0, 0]
        ],
        np.float32)

    VERT_SHADER = """ // simple vertex shader
    attribute vec2 a_position;
    void main (void) {
        gl_Position = vec4(a_position, 0., 1.0);
    }
    """

    FRAG_SHADER = """ // simple fragment shader
    void main()
    {
        gl_FragColor = vec4(1,1,1,1);
    }
    """

    with Canvas() as c:
        gloo.set_viewport(0, 0, *c.size)
        c._program = gloo.Program(VERT_SHADER, FRAG_SHADER)
        c._program['a_position'] = gloo.VertexBuffer(vPosition)
        gloo.clear(color='black')
        c._program.draw('triangle_strip')

        # Check if the return of read_pixels is the same as our drawing
        img = read_pixels(format='rgb')
        assert_equal(img.shape[:2], c.size[::-1])
        top_left = sum(img[0, 0])
        assert_true(top_left > 0)  # Should be > 0 (255*4)
        # Sum of the pixels in top right + bottom left + bottom right corners
        corners = sum(img[0, -1] + img[-1, 0] + img[-1, -1])
        assert_true(corners == 0)  # Should be all 0
        gloo.flush()
        gloo.finish()
예제 #15
0
def test_networkx_layout_with_graph():
    """
    Testing the various inputs to the networkx layout
    """

    settings = dict(name="networkx_layout")
    if nx:
        # empty input
        # testing.assert_raises(ValueError("Requires networkx input"), get_layout(**settings))

        # define graph
        graph = nx.complete_graph(5)
        # define positions
        layout = np.random.rand(5, 2)
        settings['graph'] = graph
        settings['layout'] = layout

        # test numpy array input
        testing.assert_true(
            isinstance(get_layout(**settings), NetworkxCoordinates))
        # testing string input
        settings['layout'] = 'circular'
        testing.assert_true(
            isinstance(get_layout(**settings), NetworkxCoordinates))
        # testing dict input
        settings['layout'] = nx.circular_layout(graph)
        testing.assert_true(
            isinstance(get_layout(**settings), NetworkxCoordinates))
예제 #16
0
def test_read_pixels():
    """Test read_pixels to ensure that the image is not flipped"""
    # Create vertices
    vPosition = np.array([[-1, 1], [0, 1],  # For drawing a square to top left
                          [-1, 0], [0, 0]], np.float32)

    VERT_SHADER = """ // simple vertex shader
    attribute vec2 a_position;
    void main (void) {
        gl_Position = vec4(a_position, 0., 1.0);
    }
    """

    FRAG_SHADER = """ // simple fragment shader
    void main()
    {
        gl_FragColor = vec4(1,1,1,1);
    }
    """

    with Canvas() as c:
        gloo.set_viewport(0, 0, *c.size)
        c._program = gloo.Program(VERT_SHADER, FRAG_SHADER)
        c._program['a_position'] = gloo.VertexBuffer(vPosition)
        gloo.clear(color='black')
        c._program.draw('triangle_strip')

        # Check if the return of read_pixels is the same as our drawing
        img = read_pixels(alpha=False)
        assert_equal(img.shape[:2], c.size[::-1])
        top_left = sum(img[0, 0])
        assert_true(top_left > 0)  # Should be > 0 (255*4)
        # Sum of the pixels in top right + bottom left + bottom right corners
        corners = sum(img[0, -1] + img[-1, 0] + img[-1, -1])
        assert_true(corners == 0)  # Should be all 0
        gloo.flush()
        gloo.finish()
예제 #17
0
파일: test_color.py 프로젝트: zangxc/vispy
def test_color_interpretation():
    """Test basic color interpretation API"""
    # test useful ways of single color init
    r = ColorArray('r')
    print(r)  # test repr
    r2 = ColorArray(r)
    assert_equal(r, r2)
    r2.rgb = 0, 0, 0
    assert_equal(r2, ColorArray('black'))
    assert_equal(r, ColorArray('r'))  # modifying new one preserves old
    assert_equal(r, r.copy())
    assert_equal(r, ColorArray('#ff0000'))
    assert_equal(r, ColorArray('#FF0000FF'))
    assert_equal(r, ColorArray('red'))
    assert_equal(r, ColorArray('red', alpha=1.0))
    assert_equal(ColorArray((1, 0, 0, 0.1)), ColorArray('red', alpha=0.1))
    assert_array_equal(r.rgb.ravel(), (1., 0., 0.))
    assert_array_equal(r.rgba.ravel(), (1., 0., 0., 1.))
    assert_array_equal(r.RGBA.ravel(), (255, 0, 0, 255))

    # handling multiple colors
    rgb = ColorArray(list('rgb'))
    print(rgb)  # multi repr
    assert_array_equal(rgb, ColorArray(np.eye(3)))
    # complex/annoying case
    rgb = ColorArray(['r', (0, 1, 0), '#0000ffff'])
    assert_array_equal(rgb, ColorArray(np.eye(3)))
    assert_raises(RuntimeError, ColorArray, ['r', np.eye(3)])  # can't nest

    # getting/setting properties
    r = ColorArray('#ffff')
    assert_equal(r, ColorArray('white'))
    r = ColorArray('#ff000000')
    assert_true('turquoise' in get_color_names())  # make sure our JSON loaded
    assert_equal(r.alpha, 0)
    r.alpha = 1.0
    assert_equal(r, ColorArray('r'))
    r.alpha = 0
    r.rgb = (1, 0, 0)
    assert_equal(r.alpha, 0)
    assert_equal(r.hex, ['#ff0000'])
    r.alpha = 1
    r.hex = '00ff00'
    assert_equal(r, ColorArray('g'))
    assert_array_equal(r.rgb.ravel(), (0., 1., 0.))
    r.RGB = 255, 0, 0
    assert_equal(r, ColorArray('r'))
    assert_array_equal(r.RGB.ravel(), (255, 0, 0))
    r.RGBA = 255, 0, 0, 0
    assert_equal(r, ColorArray('r', alpha=0))
    w = ColorArray()
    w.rgb = ColorArray('r').rgb + ColorArray('g').rgb + ColorArray('b').rgb
    assert_equal(w, ColorArray('white'))
    w = ColorArray('white')
    assert_equal(w, w.darker().lighter())
    assert_equal(w, w.darker(0.1).darker(-0.1))
    w2 = w.darker()
    assert_true(w != w2)
    w.darker(copy=False)
    assert_equal(w, w2)
    with use_log_level('warning', record=True, print_msg=False) as w:
        w = ColorArray('white')
        w.value = 2
        assert_equal(len(w), 1)
    assert_equal(w, ColorArray('white'))

    # warnings and errors
    assert_raises(ValueError, ColorArray, '#ffii00')  # non-hex
    assert_raises(ValueError, ColorArray, '#ff000')  # too short
    assert_raises(ValueError, ColorArray, [0, 0])  # not enough vals
    assert_raises(ValueError, ColorArray, [2, 0, 0])  # val > 1
    assert_raises(ValueError, ColorArray, [-1, 0, 0])  # val < 0
    c = ColorArray([2., 0., 0.], clip=True)  # val > 1
    assert_true(np.all(c.rgb <= 1))
    c = ColorArray([-1., 0., 0.], clip=True)  # val < 0
    assert_true(np.all(c.rgb >= 0))

    # make sure our color dict works
    for key in get_color_names():
        assert_true(ColorArray(key))
    assert_raises(ValueError, ColorArray, 'foo')  # unknown color error

    _color_dict = get_color_dict()
    assert isinstance(_color_dict, dict)
    assert set(_color_dict.keys()) == set(get_color_names())
예제 #18
0
파일: test_app.py 프로젝트: vanossj/vispy
def test_application():
    """Test application running"""
    app = use_app()
    print(app)  # __repr__ without app
    app.create()
    wrong = 'glfw' if app.backend_name.lower() != 'glfw' else 'pyqt4'
    assert_raises(RuntimeError, use_app, wrong)
    app.process_events()
    print(app)  # test __repr__

    assert_raises(ValueError, Canvas, keys='foo')
    assert_raises(TypeError, Canvas, keys=dict(escape=1))
    assert_raises(ValueError, Canvas, keys=dict(escape='foo'))  # not an attr

    pos = [0, 0] if app.backend_module.capability['position'] else None
    size = (100, 100)
    # Use "with" statement so failures don't leave open window
    # (and test context manager behavior)
    title = 'default'
    with Canvas(title=title, size=size, app=app, show=True,
                position=pos) as canvas:
        context = canvas.context
        assert_true(canvas.create_native() is None)  # should be done already
        assert_is(canvas.app, app)
        assert_true(canvas.native)
        assert_equal('swap_buffers', canvas.events.draw.callback_refs[-1])

        canvas.measure_fps(0.001)
        sleep(0.002)
        canvas.update()
        app.process_events()
        assert_true(canvas.fps > 0)

        # Other methods
        print(canvas)  # __repr__
        assert_equal(canvas.title, title)
        canvas.title = 'you'
        with use_log_level('warning', record=True, print_msg=False) as l:
            if app.backend_module.capability['position']:
                # todo: disable more tests based on capability
                canvas.position = pos
            canvas.size = size
        if 'ipynb_vnc' in canvas.app.backend_name.lower():
            assert_true(len(l) >= 1)
        else:
            assert_true(len(l) == 0)
        canvas.connect(on_mouse_move)
        assert_raises(ValueError, canvas.connect, _on_mouse_move)
        if sys.platform != 'darwin':  # XXX knownfail, prob. needs warmup
            canvas.show(False)
            canvas.show()
        app.process_events()
        assert_raises(ValueError, canvas.connect, on_nonexist)
        # deprecation of "paint"
        with use_log_level('info', record=True, print_msg=False) as log:
            olderr = sys.stderr
            try:
                fid = StringIO()
                sys.stderr = fid

                @canvas.events.paint.connect
                def fake(event):
                    pass
            finally:
                sys.stderr = olderr
        assert_equal(len(log), 1)
        assert_in('deprecated', log[0])

        # screenshots
        gl.glViewport(0, 0, *size)
        ss = _screenshot()
        assert_array_equal(ss.shape, size + (4,))
        assert_equal(len(canvas._backend._vispy_get_geometry()), 4)
        if sys.platform != 'win32':  # XXX knownfail for windows
            assert_array_equal(canvas.size, size)
        assert_equal(len(canvas.position), 2)  # XXX knawnfail, doesn't "take"

        # GLOO: should have an OpenGL context already, so these should work
        vert = "void main (void) {gl_Position = pos;}"
        frag = "void main (void) {gl_FragColor = pos;}"
        program = Program(vert, frag)
        assert_raises(RuntimeError, program.glir.flush, context.shared.parser)
        
        vert = "uniform vec4 pos;\nvoid main (void) {gl_Position = pos;}"
        frag = "uniform vec4 pos;\nvoid main (void) {gl_FragColor = pos;}"
        program = Program(vert, frag)
        #uniform = program.uniforms[0]
        program['pos'] = [1, 2, 3, 4]
        
        vert = "attribute vec4 pos;\nvoid main (void) {gl_Position = pos;}"
        frag = "void main (void) {}"
        program = Program(vert, frag)
        #attribute = program.attributes[0]
        program["pos"] = [1, 2, 3, 4]
        
        # use a real program
        program._glir.clear()
        vert = ("uniform mat4 u_model;"
                "attribute vec2 a_position; attribute vec4 a_color;"
                "varying vec4 v_color;"
                "void main (void) {v_color = a_color;"
                "gl_Position = u_model * vec4(a_position, 0.0, 1.0);"
                "v_color = a_color;}")
        frag = "void main() {gl_FragColor = vec4(0, 0, 0, 1);}"
        n, p = 250, 50
        T = np.random.uniform(0, 2 * np.pi, n)
        position = np.zeros((n, 2), dtype=np.float32)
        position[:, 0] = np.cos(T)
        position[:, 1] = np.sin(T)
        color = np.ones((n, 4), dtype=np.float32) * (1, 1, 1, 1)
        data = np.zeros(n * p, [('a_position', np.float32, 2),
                                ('a_color', np.float32, 4)])
        data['a_position'] = np.repeat(position, p, axis=0)
        data['a_color'] = np.repeat(color, p, axis=0)

        program = Program(vert, frag)
        program.bind(VertexBuffer(data))
        program['u_model'] = np.eye(4, dtype=np.float32)
        # different codepath if no call to activate()
        program.draw(gl.GL_POINTS)
        subset = IndexBuffer(np.arange(10, dtype=np.uint32))
        program.draw(gl.GL_POINTS, subset)

        # bad programs
        frag_bad = ("varying vec4 v_colors")  # no semicolon
        program = Program(vert, frag_bad)
        assert_raises(RuntimeError, program.glir.flush, context.shared.parser)
        frag_bad = None  # no fragment code. no main is not always enough
        assert_raises(ValueError, Program, vert, frag_bad)

        # Timer
        timer = Timer(interval=0.001, connect=on_mouse_move, iterations=2,
                      start=True, app=app)
        timer.start()
        timer.interval = 0.002
        assert_equal(timer.interval, 0.002)
        assert_true(timer.running)
        sleep(.003)
        assert_true(timer.elapsed >= 0.002)
        timer.stop()
        assert_true(not timer.running)
        assert_true(timer.native)
        timer.disconnect()

        # test that callbacks take reasonable inputs
        _test_callbacks(canvas)

        # cleanup
        canvas.swap_buffers()
        canvas.update()
        app.process_events()
        # put this in even though __exit__ will call it to make sure we don't
        # have problems calling it multiple times
        canvas.close()  # done by context
예제 #19
0
def test_color_interpretation():
    """Test basic color interpretation API"""
    # test useful ways of single color init
    r = ColorArray('r')
    print(r)  # test repr
    r2 = ColorArray(r)
    assert_equal(r, r2)
    r2.rgb = 0, 0, 0
    assert_equal(r2, ColorArray('black'))
    assert_equal(r, ColorArray('r'))  # modifying new one preserves old
    assert_equal(r, r.copy())
    assert_equal(r, ColorArray('#ff0000'))
    assert_equal(r, ColorArray('#FF0000FF'))
    assert_equal(r, ColorArray('red'))
    assert_equal(r, ColorArray('red', alpha=1.0))
    assert_equal(ColorArray((1, 0, 0, 0.1)), ColorArray('red', alpha=0.1))
    assert_array_equal(r.rgb.ravel(), (1., 0., 0.))
    assert_array_equal(r.rgba.ravel(), (1., 0., 0., 1.))
    assert_array_equal(r.RGBA.ravel(), (255, 0, 0, 255))

    # handling multiple colors
    rgb = ColorArray(list('rgb'))
    print(rgb)  # multi repr
    assert_array_equal(rgb, ColorArray(np.eye(3)))
    # complex/annoying case
    rgb = ColorArray(['r', (0, 1, 0), '#0000ffff'])
    assert_array_equal(rgb, ColorArray(np.eye(3)))
    assert_raises(RuntimeError, ColorArray, ['r', np.eye(3)])  # can't nest

    # getting/setting properties
    r = ColorArray('#ffff')
    assert_equal(r, ColorArray('white'))
    r = ColorArray('#ff000000')
    assert_true('turquoise' in get_color_names())  # make sure our JSON loaded
    assert_equal(r.alpha, 0)
    r.alpha = 1.0
    assert_equal(r, ColorArray('r'))
    r.alpha = 0
    r.rgb = (1, 0, 0)
    assert_equal(r.alpha, 0)
    assert_equal(r.hex, ['#ff0000'])
    r.alpha = 1
    r.hex = '00ff00'
    assert_equal(r, ColorArray('g'))
    assert_array_equal(r.rgb.ravel(), (0., 1., 0.))
    r.RGB = 255, 0, 0
    assert_equal(r, ColorArray('r'))
    assert_array_equal(r.RGB.ravel(), (255, 0, 0))
    r.RGBA = 255, 0, 0, 0
    assert_equal(r, ColorArray('r', alpha=0))
    w = ColorArray()
    w.rgb = ColorArray('r').rgb + ColorArray('g').rgb + ColorArray('b').rgb
    assert_equal(w, ColorArray('white'))
    w = ColorArray('white')
    assert_equal(w, w.darker().lighter())
    assert_equal(w, w.darker(0.1).darker(-0.1))
    w2 = w.darker()
    assert_true(w != w2)
    w.darker(copy=False)
    assert_equal(w, w2)
    with use_log_level('warning', record=True, print_msg=False) as w:
        w = ColorArray('white')
        w.value = 2
        assert_equal(len(w), 1)
    assert_equal(w, ColorArray('white'))

    # warnings and errors
    assert_raises(ValueError, ColorArray, '#ffii00')  # non-hex
    assert_raises(ValueError, ColorArray, '#ff000')  # too short
    assert_raises(ValueError, ColorArray, [0, 0])  # not enough vals
    assert_raises(ValueError, ColorArray, [2, 0, 0])  # val > 1
    assert_raises(ValueError, ColorArray, [-1, 0, 0])  # val < 0
    c = ColorArray([2., 0., 0.], clip=True)  # val > 1
    assert_true(np.all(c.rgb <= 1))
    c = ColorArray([-1., 0., 0.], clip=True)  # val < 0
    assert_true(np.all(c.rgb >= 0))

    # make sure our color dict works
    for key in get_color_names():
        assert_true(ColorArray(key))
    assert_raises(ValueError, ColorArray, 'foo')  # unknown color error

    _color_dict = get_color_dict()
    assert isinstance(_color_dict, dict)
    assert set(_color_dict.keys()) == set(get_color_names())
예제 #20
0
def _prepare_vis():
    
    objects = []
    
    # --- program and shaders
    
    # Create program and shaders
    hprog = gl.glCreateProgram()
    hvert = gl.glCreateShader(gl.GL_VERTEX_SHADER)
    hfrag = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
    objects.append((gl.glDeleteProgram, hprog))
    objects.append((gl.glDeleteShader, hvert))
    objects.append((gl.glDeleteShader, hfrag))
    
    # Compile source code
    gl.glShaderSource(hvert, VERT)
    gl.glShaderSource(hfrag, FRAG)
    gl.glCompileShader(hvert)
    gl.glCompileShader(hfrag)
    
    # Check
    assert_equal(gl.glGetShaderInfoLog(hvert), '')
    assert_equal(gl.glGetShaderInfoLog(hfrag), '')
    assert_equal(gl.glGetShaderParameter(hvert, gl.GL_COMPILE_STATUS), 1)
    assert_equal(gl.glGetShaderParameter(hfrag, gl.GL_COMPILE_STATUS), 1)
    
    # Attach and link
    gl.glAttachShader(hprog, hvert)
    gl.glAttachShader(hprog, hfrag)
    # touch glDetachShader
    gl.glDetachShader(hprog, hvert)
    gl.glAttachShader(hprog, hvert)
    gl.glLinkProgram(hprog)
    
    # Test that indeed these shaders are attached
    attached_shaders = gl.glGetAttachedShaders(hprog)
    assert_equal(set(attached_shaders), set([hvert, hfrag]))
    
    # Check
    assert_equal(gl.glGetProgramInfoLog(hprog), '')
    assert_equal(gl.glGetProgramParameter(hprog, gl.GL_LINK_STATUS), 1)
    gl.glValidateProgram(hprog)
    assert_equal(gl.glGetProgramParameter(hprog, gl.GL_VALIDATE_STATUS), 1)
    
    # Use it!
    gl.glUseProgram(hprog)
    
    # Bind one attribute
    gl.glBindAttribLocation(hprog, 1, 'a_2')
    
    # Check if all is ok
    assert_equal(gl.glGetError(), 0)
    
    # Check source
    vert_source = gl.glGetShaderSource(hvert)
    assert_true('attribute vec2 a_2;' in vert_source)
    
    # --- get information on attributes and uniforms
    
    # Count attribbutes and uniforms
    natt = gl.glGetProgramParameter(hprog, gl.GL_ACTIVE_ATTRIBUTES)
    nuni = gl.glGetProgramParameter(hprog, gl.GL_ACTIVE_UNIFORMS)
    assert_equal(natt, 4)
    assert_equal(nuni, 4+4+3+1)
    
    # Get names
    names = {}
    for i in range(natt):
        name, count, type = gl.glGetActiveAttrib(hprog, i)
        names[name] = type
        assert_equal(count, 1)
    for i in range(nuni):
        name, count, type = gl.glGetActiveUniform(hprog, i)
        names[name] = type
        assert_equal(count, 1)
    
    # Check
    assert_equal(names['a_1'], gl.GL_FLOAT)
    assert_equal(names['a_2'], gl.GL_FLOAT_VEC2)
    assert_equal(names['a_3'], gl.GL_FLOAT_VEC3)
    assert_equal(names['a_4'], gl.GL_FLOAT_VEC4)
    assert_equal(names['s_1'], gl.GL_SAMPLER_2D)
    #
    for i, type in enumerate([gl.GL_FLOAT, gl.GL_FLOAT_VEC2, 
                              gl.GL_FLOAT_VEC3, gl.GL_FLOAT_VEC4]):
        assert_equal(names['u_f%i' % (i+1)], type)
    for i, type in enumerate([gl.GL_INT, gl.GL_INT_VEC2, 
                              gl.GL_INT_VEC3, gl.GL_INT_VEC4]):
        assert_equal(names['u_i%i' % (i+1)], type)
    for i, type in enumerate([gl.GL_FLOAT_MAT2, gl.GL_FLOAT_MAT3, 
                              gl.GL_FLOAT_MAT4]):
        assert_equal(names['u_m%i' % (i+2)], type)
    
    # Check if all is ok
    assert_equal(gl.glGetError(), 0)
    
    # --- texture
    
    # Create, bind, activate
    htex = gl.glCreateTexture()
    objects.append((gl.glDeleteTexture, htex))
    gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)
    gl.glBindTexture(gl.GL_TEXTURE_2D, htex)
    
    # Allocate data and upload
    # This data is luminance and not C-contiguous
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_LUMINANCE, gl.GL_LUMINANCE, 
                    gl.GL_UNSIGNED_BYTE, im2)  # touch
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_LUMINANCE, gl.GL_LUMINANCE, 
                    gl.GL_UNSIGNED_BYTE, im2.shape[:2])
    gl.glTexSubImage2D(gl.GL_TEXTURE_2D, 0, 0, 0, gl.GL_LUMINANCE,
                       gl.GL_UNSIGNED_BYTE, im2)
    
    # Set texture parameters (use f and i to touch both)
    T = gl.GL_TEXTURE_2D
    gl.glTexParameterf(T, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
    gl.glTexParameteri(T, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)
    
    # Re-allocate data and upload 
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, gl.GL_RGB, 
                    gl.GL_UNSIGNED_BYTE, im1.shape[:2])
    gl.glTexSubImage2D(gl.GL_TEXTURE_2D, 0, 0, 0, gl.GL_RGB,
                       gl.GL_UNSIGNED_BYTE, im1)
    
    # Attach!
    loc = gl.glGetUniformLocation(hprog, 's_1')
    unit = 0
    gl.glActiveTexture(gl.GL_TEXTURE0+unit)
    gl.glUniform1i(loc, unit) 
    
    # Mipmaps (just to touch this function)
    gl.glGenerateMipmap(gl.GL_TEXTURE_2D)
    
    # Check min filter (touch getTextParameter)
    minfilt = gl.glGetTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER)
    assert_equal(minfilt, gl.GL_LINEAR)
    
    # Check if all is ok
    assert_equal(gl.glGetError(), 0)
    
    # --- buffer vec2 (contiguous VBO)
    
    # Create buffer
    hbuf2 = gl.glCreateBuffer()
    objects.append((gl.glDeleteBuffer, hbuf2))
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, hbuf2)

    # Allocate and set data
    gl.glBufferData(gl.GL_ARRAY_BUFFER, buf2.nbytes, gl.GL_DYNAMIC_DRAW)
    gl.glBufferSubData(gl.GL_ARRAY_BUFFER, 0, buf2)
    
    # Attach!
    loc = gl.glGetAttribLocation(hprog, 'a_2')
    gl.glDisableVertexAttribArray(loc)  # touch
    gl.glEnableVertexAttribArray(loc)
    gl.glVertexAttribPointer(loc, 2, gl.GL_FLOAT, False, 2*4, 0)
    
    # Check (touch glGetBufferParameter, glGetVertexAttrib and
    # glGetVertexAttribOffset)
    size = gl.glGetBufferParameter(gl.GL_ARRAY_BUFFER, gl.GL_BUFFER_SIZE)
    assert_equal(size, buf2.nbytes)
    stride = gl.glGetVertexAttrib(loc, gl.GL_VERTEX_ATTRIB_ARRAY_STRIDE)
    assert_equal(stride, 2*4)
    offset = gl.glGetVertexAttribOffset(loc, gl.GL_VERTEX_ATTRIB_ARRAY_POINTER)
    assert_equal(offset, 0)
    
    # Check if all is ok
    assert_equal(gl.glGetError(), 0)
    
    # --- buffer vec3 (non-contiguous VBO)
    
    # Create buffer
    hbuf3 = gl.glCreateBuffer()
    objects.append((gl.glDeleteBuffer, hbuf3))
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, hbuf3)

    # Allocate and set data
    gl.glBufferData(gl.GL_ARRAY_BUFFER, buf3.nbytes, gl.GL_DYNAMIC_DRAW)
    gl.glBufferSubData(gl.GL_ARRAY_BUFFER, 0, buf3)
    
    # Attach!
    loc = gl.glGetAttribLocation(hprog, 'a_3')
    gl.glEnableVertexAttribArray(loc)
    gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, 3*4, 0)
    
    # Check if all is ok
    assert_equal(gl.glGetError(), 0)
    
    # --- buffer vec4 (client vertex data)
    
    # Select no FBO
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)
    
    # Attach!
    loc = gl.glGetAttribLocation(hprog, 'a_4')
    gl.glEnableVertexAttribArray(loc)
    gl.glVertexAttribPointer(loc, 4, gl.GL_FLOAT, False, 4*4, buf4)
    
    # Check if all is ok
    assert_equal(gl.glGetError(), 0)
    
    # --- element buffer
    
    # Create buffer
    global helements
    helements = gl.glCreateBuffer()
    objects.append((gl.glDeleteBuffer, helements))
    gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, helements)

    # Allocate and set data
    gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, elements, gl.GL_DYNAMIC_DRAW)
    gl.glBufferSubData(gl.GL_ELEMENT_ARRAY_BUFFER, 0, elements)
    
    # Turn off
    gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, 0)
    
    # Check if all is ok
    assert_equal(gl.glGetError(), 0)
    
    # --- uniforms
    
    # Set integer uniforms to 0
    # We set them twice just to touch both i and iv functions
    for i, fun1, fun2 in [(1, gl.glUniform1i, gl.glUniform1iv),
                          (2, gl.glUniform2i, gl.glUniform2iv),
                          (3, gl.glUniform3i, gl.glUniform3iv),
                          (4, gl.glUniform4i, gl.glUniform4iv)]:
        name = 'u_i%i' % i
        value = [0] * i
        loc = gl.glGetUniformLocation(hprog, name)
        fun1(loc, *value)  # e.g. glUniform4i
        fun2(loc, 1, value)  # e.g. glUniform4iv

    # Set float uniforms to 1.0
    # We set them twice just to touch both i and iv functions
    for i, fun1, fun2 in [(1, gl.glUniform1f, gl.glUniform1fv),
                          (2, gl.glUniform2f, gl.glUniform2fv),
                          (3, gl.glUniform3f, gl.glUniform3fv),
                          (4, gl.glUniform4f, gl.glUniform4fv)]:
        name = 'u_f%i' % i
        value = [1.0] * i
        loc = gl.glGetUniformLocation(hprog, name)
        fun1(loc, *value)  # e.g. glUniform4f
        fun2(loc, 1, value)  # e.g. glUniform4fv
    
    # Set matrix uniforms
    m = np.eye(5, dtype='float32')
    loc = gl.glGetUniformLocation(hprog, 'u_m2')
    gl.glUniformMatrix2fv(loc, 1, False, m[:2, :2])
    #
    loc = gl.glGetUniformLocation(hprog, 'u_m3')
    m = np.eye(3, dtype='float32')
    gl.glUniformMatrix3fv(loc, 1, False, m[:3, :3])
    #
    loc = gl.glGetUniformLocation(hprog, 'u_m4')
    m = np.eye(4, dtype='float32')
    gl.glUniformMatrix4fv(loc, 1, False, m[:4, :4])
    
    # Check some uniforms
    loc = gl.glGetUniformLocation(hprog, 'u_i1')
    assert_equal(gl.glGetUniform(hprog, loc), 0)
    loc = gl.glGetUniformLocation(hprog, 'u_i2')
    assert_equal(gl.glGetUniform(hprog, loc), (0, 0))
    loc = gl.glGetUniformLocation(hprog, 'u_f2')
    assert_equal(gl.glGetUniform(hprog, loc), (1.0, 1.0))
    
    # Check if all is ok
    assert_equal(gl.glGetError(), 0)
    
    # --- attributes 
    
    # Constant values for attributes. We do not even use this ...
    loc = gl.glGetAttribLocation(hprog, 'a_1')
    gl.glVertexAttrib1f(loc, 1.0)
    loc = gl.glGetAttribLocation(hprog, 'a_2')
    gl.glVertexAttrib2f(loc, 1.0, 1.0)
    loc = gl.glGetAttribLocation(hprog, 'a_3')
    gl.glVertexAttrib3f(loc, 1.0, 1.0, 1.0)
    loc = gl.glGetAttribLocation(hprog, 'a_4')
    gl.glVertexAttrib4f(loc, 1.0, 1.0, 1.0, 1.0)
    
    # --- flush and finish
    
    # Not really necessary, but we want to touch the functions
    gl.glFlush()
    gl.glFinish()
    
    #print([i[1] for i in objects])
    return objects
예제 #21
0
파일: test_app.py 프로젝트: Eric89GXL/vispy
def test_application():
    """Test application running"""
    app = use_app()
    print(app)  # __repr__ without app
    app.create()
    wrong = 'glfw' if app.backend_name.lower() != 'glfw' else 'pyqt4'
    assert_raises(RuntimeError, use_app, wrong)
    app.process_events()
    print(app)  # test __repr__

    assert_raises(ValueError, Canvas, keys='foo')
    assert_raises(TypeError, Canvas, keys=dict(escape=1))
    assert_raises(ValueError, Canvas, keys=dict(escape='foo'))  # not an attr

    pos = [0, 0] if app.backend_module.capability['position'] else None
    size = (100, 100)
    # Use "with" statement so failures don't leave open window
    # (and test context manager behavior)
    title = 'default'
    with Canvas(title=title, size=size, app=app, show=True,
                position=pos) as canvas:
        context = canvas.context
        assert_true(canvas.create_native() is None)  # should be done already
        assert_is(canvas.app, app)
        assert_true(canvas.native)
        assert_equal('swap_buffers', canvas.events.draw.callback_refs[-1])

        canvas.measure_fps(0.001)
        sleep(0.002)
        canvas.update()
        app.process_events()
        assert_true(canvas.fps > 0)

        # Other methods
        print(canvas)  # __repr__
        assert_equal(canvas.title, title)
        canvas.title = 'you'
        with use_log_level('warning', record=True, print_msg=False):
            if app.backend_module.capability['position']:
                # todo: disable more tests based on capability
                canvas.position = pos
            canvas.size = size
        canvas.connect(on_mouse_move)
        assert_raises(ValueError, canvas.connect, _on_mouse_move)
        if sys.platform != 'darwin':  # XXX knownfail, prob. needs warmup
            canvas.show(False)
            canvas.show()
        app.process_events()
        assert_raises(ValueError, canvas.connect, on_nonexist)
        # deprecation of "paint"
        with use_log_level('info', record=True, print_msg=False) as log:
            olderr = sys.stderr
            try:
                fid = StringIO()
                sys.stderr = fid

                @canvas.events.paint.connect
                def fake(event):
                    pass
            finally:
                sys.stderr = olderr
        assert_equal(len(log), 1)
        assert_in('deprecated', log[0])

        # screenshots
        gl.glViewport(0, 0, *size)
        ss = _screenshot()
        assert_array_equal(ss.shape, size + (4,))
        assert_equal(len(canvas._backend._vispy_get_geometry()), 4)
        if sys.platform != 'win32':  # XXX knownfail for windows
            assert_array_equal(canvas.size, size)
        assert_equal(len(canvas.position), 2)  # XXX knawnfail, doesn't "take"

        # GLOO: should have an OpenGL context already, so these should work
        vert = "void main (void) {gl_Position = pos;}"
        frag = "void main (void) {gl_FragColor = pos;}"
        program = Program(vert, frag)
        assert_raises(RuntimeError, program.glir.flush, context.shared.parser)

        vert = "uniform vec4 pos;\nvoid main (void) {gl_Position = pos;}"
        frag = "uniform vec4 pos;\nvoid main (void) {gl_FragColor = pos;}"
        program = Program(vert, frag)
        # uniform = program.uniforms[0]
        program['pos'] = [1, 2, 3, 4]

        vert = "attribute vec4 pos;\nvoid main (void) {gl_Position = pos;}"
        frag = "void main (void) {}"
        program = Program(vert, frag)
        # attribute = program.attributes[0]
        program["pos"] = [1, 2, 3, 4]

        # use a real program
        program._glir.clear()
        vert = ("uniform mat4 u_model;"
                "attribute vec2 a_position; attribute vec4 a_color;"
                "varying vec4 v_color;"
                "void main (void) {v_color = a_color;"
                "gl_Position = u_model * vec4(a_position, 0.0, 1.0);"
                "v_color = a_color;}")
        frag = "void main() {gl_FragColor = vec4(0, 0, 0, 1);}"
        n, p = 250, 50
        T = np.random.uniform(0, 2 * np.pi, n)
        position = np.zeros((n, 2), dtype=np.float32)
        position[:, 0] = np.cos(T)
        position[:, 1] = np.sin(T)
        color = np.ones((n, 4), dtype=np.float32) * (1, 1, 1, 1)
        data = np.zeros(n * p, [('a_position', np.float32, 2),
                                ('a_color', np.float32, 4)])
        data['a_position'] = np.repeat(position, p, axis=0)
        data['a_color'] = np.repeat(color, p, axis=0)

        program = Program(vert, frag)
        program.bind(VertexBuffer(data))
        program['u_model'] = np.eye(4, dtype=np.float32)
        # different codepath if no call to activate()
        program.draw(gl.GL_POINTS)
        subset = IndexBuffer(np.arange(10, dtype=np.uint32))
        program.draw(gl.GL_POINTS, subset)

        # bad programs
        frag_bad = ("varying vec4 v_colors")  # no semicolon
        program = Program(vert, frag_bad)
        assert_raises(RuntimeError, program.glir.flush, context.shared.parser)
        frag_bad = None  # no fragment code. no main is not always enough
        assert_raises(ValueError, Program, vert, frag_bad)

        # Timer
        timer = Timer(interval=0.001, connect=on_mouse_move, iterations=2,
                      start=True, app=app)
        timer.start()
        timer.interval = 0.002
        assert_equal(timer.interval, 0.002)
        assert_true(timer.running)
        sleep(.003)
        assert_true(timer.elapsed >= 0.002)
        timer.stop()
        assert_true(not timer.running)
        assert_true(timer.native)
        timer.disconnect()

        # test that callbacks take reasonable inputs
        _test_callbacks(canvas)

        # cleanup
        canvas.swap_buffers()
        canvas.update()
        app.process_events()
        # put this in even though __exit__ will call it to make sure we don't
        # have problems calling it multiple times
        canvas.close()  # done by context
예제 #22
0
def _prepare_vis():

    objects = []

    # --- program and shaders

    # Create program and shaders
    hprog = gl.glCreateProgram()
    hvert = gl.glCreateShader(gl.GL_VERTEX_SHADER)
    hfrag = gl.glCreateShader(gl.GL_FRAGMENT_SHADER)
    objects.append((gl.glDeleteProgram, hprog))
    objects.append((gl.glDeleteShader, hvert))
    objects.append((gl.glDeleteShader, hfrag))

    # Compile source code
    gl.glShaderSource(hvert, VERT)
    gl.glShaderSource(hfrag, FRAG)
    gl.glCompileShader(hvert)
    gl.glCompileShader(hfrag)

    # Check
    assert gl.glGetShaderInfoLog(hvert) == ''
    assert gl.glGetShaderInfoLog(hfrag) == ''
    assert gl.glGetShaderParameter(hvert, gl.GL_COMPILE_STATUS) == 1
    assert gl.glGetShaderParameter(hfrag, gl.GL_COMPILE_STATUS) == 1

    # Attach and link
    gl.glAttachShader(hprog, hvert)
    gl.glAttachShader(hprog, hfrag)
    # touch glDetachShader
    gl.glDetachShader(hprog, hvert)
    gl.glAttachShader(hprog, hvert)

    # Bind all attributes - we could let this occur automatically, but some
    # implementations bind an attribute to index 0, which has the unfortunate
    # property of being unable to be modified.
    gl.glBindAttribLocation(hprog, 1, 'a_1')
    gl.glBindAttribLocation(hprog, 2, 'a_2')
    gl.glBindAttribLocation(hprog, 3, 'a_3')
    gl.glBindAttribLocation(hprog, 4, 'a_4')

    gl.glLinkProgram(hprog)

    # Test that indeed these shaders are attached
    attached_shaders = gl.glGetAttachedShaders(hprog)
    assert_equal(set(attached_shaders), set([hvert, hfrag]))

    # Check
    assert_equal(gl.glGetProgramInfoLog(hprog), '')
    assert_equal(gl.glGetProgramParameter(hprog, gl.GL_LINK_STATUS), 1)
    gl.glValidateProgram(hprog)
    assert_equal(gl.glGetProgramParameter(hprog, gl.GL_VALIDATE_STATUS), 1)

    # Use it!
    gl.glUseProgram(hprog)

    # Check if all is ok
    assert_equal(gl.glGetError(), 0)

    # Check source
    vert_source = gl.glGetShaderSource(hvert)
    assert_true('attribute vec2 a_2;' in vert_source)

    # --- get information on attributes and uniforms

    # Count attributes and uniforms
    natt = gl.glGetProgramParameter(hprog, gl.GL_ACTIVE_ATTRIBUTES)
    nuni = gl.glGetProgramParameter(hprog, gl.GL_ACTIVE_UNIFORMS)
    assert_equal(natt, 4)
    assert_equal(nuni, 4+4+3+1)

    # Get names
    names = {}
    for i in range(natt):
        name, count, type = gl.glGetActiveAttrib(hprog, i)
        names[name] = type
        assert_equal(count, 1)
    for i in range(nuni):
        name, count, type = gl.glGetActiveUniform(hprog, i)
        names[name] = type
        assert_equal(count, 1)

    # Check
    assert_equal(names['a_1'], gl.GL_FLOAT)
    assert_equal(names['a_2'], gl.GL_FLOAT_VEC2)
    assert_equal(names['a_3'], gl.GL_FLOAT_VEC3)
    assert_equal(names['a_4'], gl.GL_FLOAT_VEC4)
    assert_equal(names['s_1'], gl.GL_SAMPLER_2D)
    #
    for i, type in enumerate([gl.GL_FLOAT, gl.GL_FLOAT_VEC2,
                              gl.GL_FLOAT_VEC3, gl.GL_FLOAT_VEC4]):
        assert_equal(names['u_f%i' % (i+1)], type)
    for i, type in enumerate([gl.GL_INT, gl.GL_INT_VEC2,
                              gl.GL_INT_VEC3, gl.GL_INT_VEC4]):
        assert_equal(names['u_i%i' % (i+1)], type)
    for i, type in enumerate([gl.GL_FLOAT_MAT2, gl.GL_FLOAT_MAT3,
                              gl.GL_FLOAT_MAT4]):
        assert_equal(names['u_m%i' % (i+2)], type)

    # Check if all is ok
    assert_equal(gl.glGetError(), 0)

    # --- texture

    # Create, bind, activate
    htex = gl.glCreateTexture()
    objects.append((gl.glDeleteTexture, htex))
    gl.glPixelStorei(gl.GL_UNPACK_ALIGNMENT, 1)
    gl.glBindTexture(gl.GL_TEXTURE_2D, htex)

    # Allocate data and upload
    # This data is luminance and not C-contiguous
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_LUMINANCE, gl.GL_LUMINANCE,
                    gl.GL_UNSIGNED_BYTE, im2)  # touch
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_LUMINANCE, gl.GL_LUMINANCE,
                    gl.GL_UNSIGNED_BYTE, im2.shape[:2])
    gl.glTexSubImage2D(gl.GL_TEXTURE_2D, 0, 0, 0, gl.GL_LUMINANCE,
                       gl.GL_UNSIGNED_BYTE, im2)

    # Set texture parameters (use f and i to touch both)
    T = gl.GL_TEXTURE_2D
    gl.glTexParameterf(T, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)
    gl.glTexParameteri(T, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)

    # Re-allocate data and upload
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, gl.GL_RGB,
                    gl.GL_UNSIGNED_BYTE, im1.shape[:2])
    gl.glTexSubImage2D(gl.GL_TEXTURE_2D, 0, 0, 0, gl.GL_RGB,
                       gl.GL_UNSIGNED_BYTE, im1)

    # Attach!
    loc = gl.glGetUniformLocation(hprog, 's_1')
    unit = 0
    gl.glActiveTexture(gl.GL_TEXTURE0+unit)
    gl.glUniform1i(loc, unit)

    # Mipmaps (just to touch this function)
    gl.glGenerateMipmap(gl.GL_TEXTURE_2D)

    # Check min filter (touch getTextParameter)
    minfilt = gl.glGetTexParameter(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER)
    assert_equal(minfilt, gl.GL_LINEAR)

    # Check if all is ok
    assert_equal(gl.glGetError(), 0)

    # --- buffer vec2 (contiguous VBO)

    # Create buffer
    hbuf2 = gl.glCreateBuffer()
    objects.append((gl.glDeleteBuffer, hbuf2))
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, hbuf2)

    # Allocate and set data
    gl.glBufferData(gl.GL_ARRAY_BUFFER, buf2.nbytes, gl.GL_DYNAMIC_DRAW)
    gl.glBufferSubData(gl.GL_ARRAY_BUFFER, 0, buf2)

    # Attach!
    loc = gl.glGetAttribLocation(hprog, 'a_2')
    gl.glDisableVertexAttribArray(loc)  # touch
    gl.glEnableVertexAttribArray(loc)
    gl.glVertexAttribPointer(loc, 2, gl.GL_FLOAT, False, 2*4, 0)

    # Check (touch glGetBufferParameter, glGetVertexAttrib and
    # glGetVertexAttribOffset)
    size = gl.glGetBufferParameter(gl.GL_ARRAY_BUFFER, gl.GL_BUFFER_SIZE)
    assert_equal(size, buf2.nbytes)
    stride = gl.glGetVertexAttrib(loc, gl.GL_VERTEX_ATTRIB_ARRAY_STRIDE)
    assert_equal(stride, 2*4)
    offset = gl.glGetVertexAttribOffset(loc, gl.GL_VERTEX_ATTRIB_ARRAY_POINTER)
    assert_equal(offset, 0)

    # Check if all is ok
    assert_equal(gl.glGetError(), 0)

    # --- buffer vec3 (non-contiguous VBO)

    # Create buffer
    hbuf3 = gl.glCreateBuffer()
    objects.append((gl.glDeleteBuffer, hbuf3))
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, hbuf3)

    # Allocate and set data
    gl.glBufferData(gl.GL_ARRAY_BUFFER, buf3.nbytes, gl.GL_DYNAMIC_DRAW)
    gl.glBufferSubData(gl.GL_ARRAY_BUFFER, 0, buf3)

    # Attach!
    loc = gl.glGetAttribLocation(hprog, 'a_3')
    gl.glEnableVertexAttribArray(loc)
    gl.glVertexAttribPointer(loc, 3, gl.GL_FLOAT, False, 3*4, 0)

    # Check if all is ok
    assert_equal(gl.glGetError(), 0)

    # --- buffer vec4 (client vertex data)

    # Select no FBO
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, 0)

    # Attach!
    loc = gl.glGetAttribLocation(hprog, 'a_4')
    gl.glEnableVertexAttribArray(loc)
    gl.glVertexAttribPointer(loc, 4, gl.GL_FLOAT, False, 4*4, buf4)

    # Check if all is ok
    assert_equal(gl.glGetError(), 0)

    # --- element buffer

    # Create buffer
    global helements
    helements = gl.glCreateBuffer()
    objects.append((gl.glDeleteBuffer, helements))
    gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, helements)

    # Allocate and set data
    gl.glBufferData(gl.GL_ELEMENT_ARRAY_BUFFER, elements, gl.GL_DYNAMIC_DRAW)
    gl.glBufferSubData(gl.GL_ELEMENT_ARRAY_BUFFER, 0, elements)

    # Turn off
    gl.glBindBuffer(gl.GL_ELEMENT_ARRAY_BUFFER, 0)

    # Check if all is ok
    assert_equal(gl.glGetError(), 0)

    # --- uniforms

    # Set integer uniforms to 0
    # We set them twice just to touch both i and iv functions
    for i, fun1, fun2 in [(1, gl.glUniform1i, gl.glUniform1iv),
                          (2, gl.glUniform2i, gl.glUniform2iv),
                          (3, gl.glUniform3i, gl.glUniform3iv),
                          (4, gl.glUniform4i, gl.glUniform4iv)]:
        name = 'u_i%i' % i
        value = [0] * i
        loc = gl.glGetUniformLocation(hprog, name)
        fun1(loc, *value)  # e.g. glUniform4i
        fun2(loc, 1, value)  # e.g. glUniform4iv

    # Set float uniforms to 1.0
    # We set them twice just to touch both i and iv functions
    for i, fun1, fun2 in [(1, gl.glUniform1f, gl.glUniform1fv),
                          (2, gl.glUniform2f, gl.glUniform2fv),
                          (3, gl.glUniform3f, gl.glUniform3fv),
                          (4, gl.glUniform4f, gl.glUniform4fv)]:
        name = 'u_f%i' % i
        value = [1.0] * i
        loc = gl.glGetUniformLocation(hprog, name)
        fun1(loc, *value)  # e.g. glUniform4f
        fun2(loc, 1, value)  # e.g. glUniform4fv

    # Set matrix uniforms
    m = np.eye(5, dtype='float32')
    loc = gl.glGetUniformLocation(hprog, 'u_m2')
    gl.glUniformMatrix2fv(loc, 1, False, m[:2, :2])
    #
    loc = gl.glGetUniformLocation(hprog, 'u_m3')
    m = np.eye(3, dtype='float32')
    gl.glUniformMatrix3fv(loc, 1, False, m[:3, :3])
    #
    loc = gl.glGetUniformLocation(hprog, 'u_m4')
    m = np.eye(4, dtype='float32')
    gl.glUniformMatrix4fv(loc, 1, False, m[:4, :4])

    # Check some uniforms
    loc = gl.glGetUniformLocation(hprog, 'u_i1')
    assert_equal(gl.glGetUniform(hprog, loc), 0)
    loc = gl.glGetUniformLocation(hprog, 'u_i2')
    assert_equal(gl.glGetUniform(hprog, loc), (0, 0))
    loc = gl.glGetUniformLocation(hprog, 'u_f2')
    assert_equal(gl.glGetUniform(hprog, loc), (1.0, 1.0))

    # Check if all is ok
    assert_equal(gl.glGetError(), 0)

    # --- attributes

    # Constant values for attributes. We do not even use this ...
    loc = gl.glGetAttribLocation(hprog, 'a_1')
    gl.glVertexAttrib1f(loc, 1.0)
    loc = gl.glGetAttribLocation(hprog, 'a_2')
    gl.glVertexAttrib2f(loc, 1.0, 1.0)
    loc = gl.glGetAttribLocation(hprog, 'a_3')
    gl.glVertexAttrib3f(loc, 1.0, 1.0, 1.0)
    loc = gl.glGetAttribLocation(hprog, 'a_4')
    gl.glVertexAttrib4f(loc, 1.0, 1.0, 1.0, 1.0)

    # --- flush and finish

    # Not really necessary, but we want to touch the functions
    gl.glFlush()
    gl.glFinish()

    # print([i[1] for i in objects])
    return objects