Esempio n. 1
0
def test_context_taking():
    """Test GLContext ownership and taking"""
    def get_canvas(c):
        return c.shared.ref

    cb = DummyCanvasBackend()
    c = GLContext()

    # Context is not taken and cannot get backend_canvas
    assert c.shared.name is None
    assert_raises(RuntimeError, get_canvas, c)
    assert_in('None backend', repr(c.shared))

    # Take it
    c.shared.add_ref('test-foo', cb)
    assert c.shared.ref is cb
    assert_in('test-foo backend', repr(c.shared))

    # Now we can take it again
    c.shared.add_ref('test-foo', cb)
    assert len(c.shared._refs) == 2
    # assert_raises(RuntimeError, c.take, 'test', cb)

    # Canvas backend can delete (we use a weak ref)
    cb = DummyCanvasBackend()  # overwrite old object
    gc.collect()

    # No more refs
    assert_raises(RuntimeError, get_canvas, c)
Esempio n. 2
0
def test_context_config():
    """Test GLContext handling of config dict"""
    default_config = get_default_config()

    # Pass default config unchanged
    c = GLContext(default_config)
    assert_equal(c.config, default_config)
    # Must be deep copy
    c.config['double_buffer'] = False
    assert_not_equal(c.config, default_config)

    # Passing nothing should yield default config
    c = GLContext()
    assert_equal(c.config, default_config)
    # Must be deep copy
    c.config['double_buffer'] = False
    assert_not_equal(c.config, default_config)

    # This should work
    c = GLContext({'red_size': 4, 'double_buffer': False})
    assert_equal(c.config.keys(), default_config.keys())

    # Passing crap should raise
    assert_raises(KeyError, GLContext, {'foo': 3})
    assert_raises(TypeError, GLContext, {'double_buffer': 'not_bool'})

    # Capabilites are passed on
    assert 'gl_version' in c.capabilities
Esempio n. 3
0
def test_context_taking():
    """ Test GLContext ownership and taking
    """
    def get_canvas(c):
        return c.shared.ref
    
    cb = DummyCanvasBackend()
    c = GLContext()
    
    # Context is not taken and cannot get backend_canvas
    assert c.shared.name is None
    assert_raises(RuntimeError, get_canvas, c)
    assert_in('None backend', repr(c.shared))
    
    # Take it
    c.shared.add_ref('test-foo', cb)
    assert c.shared.ref is cb
    assert_in('test-foo backend', repr(c.shared))
    
    # Now we can take it again
    c.shared.add_ref('test-foo', cb)
    assert len(c.shared._refs) == 2
    #assert_raises(RuntimeError, c.take, 'test', cb)
    
    # Canvas backend can delete (we use a weak ref)
    cb = DummyCanvasBackend()  # overwrite old object
    gc.collect()
    
    # No more refs
    assert_raises(RuntimeError, get_canvas, c)
Esempio n. 4
0
def test_config():
    """Test vispy config methods and file downloading"""
    assert_raises(TypeError, config.update, data_path=dict())
    assert_raises(KeyError, config.update, foo="bar")  # bad key
    data_dir = op.join(temp_dir, "data")
    assert_raises(IOError, set_data_dir, data_dir)  # didn't say to create
    orig_val = os.environ.get("_VISPY_CONFIG_TESTING", None)
    os.environ["_VISPY_CONFIG_TESTING"] = "true"
    try:
        assert_raises(IOError, set_data_dir, data_dir)  # doesn't exist yet
        set_data_dir(data_dir, create=True, save=True)
        assert_equal(config["data_path"], data_dir)
        config["data_path"] = data_dir
        print(config)  # __repr__
        load_data_file("CONTRIBUTING.txt")
        fid = open(op.join(data_dir, "test-faked.txt"), "w")
        fid.close()
        load_data_file("test-faked.txt")  # this one shouldn't download
        assert_raises(RuntimeError, load_data_file, "foo-nonexist.txt")
        save_config()
    finally:
        if orig_val is not None:
            os.environ["_VISPY_CONFIG_TESTING"] = orig_val
        else:
            del os.environ["_VISPY_CONFIG_TESTING"]
Esempio n. 5
0
def test_use():
    
    # Set default app to None, so we can test the use function
    vispy.app.use_app()
    default_app = vispy.app._default_app.default_app
    vispy.app._default_app.default_app = None
    
    app_name = default_app.backend_name.split(' ')[0]
    
    try:
        # With no arguments, should do nothing
        assert_raises(TypeError, vispy.use)
        assert_equal(vispy.app._default_app.default_app, None)
        
        # With only gl args, should do nothing to app
        vispy.use(gl='gl2')
        assert_equal(vispy.app._default_app.default_app, None)
        
        # Specify app (one we know works)
        vispy.use(app_name)
        assert_not_equal(vispy.app._default_app.default_app, None)
        
        # Again, but now wrong app
        wrong_name = 'glfw' if app_name.lower() != 'glfw' else 'pyqt4'
        assert_raises(RuntimeError, vispy.use, wrong_name)
        
        # And both
        vispy.use(app_name, 'gl2')
    
    finally:
        # Restore
        vispy.app._default_app.default_app = default_app
Esempio n. 6
0
def test_context_sharing():
    """Test context sharing"""
    with Canvas() as c1:
        vert = "attribute vec4 pos;\nvoid main (void) {gl_Position = pos;}"
        frag = "void main (void) {gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);}"
        program = Program(vert, frag)
        program['pos'] = [(1, 2, 3, 1), (4, 5, 6, 1)]
        program.draw('points')

        def check():
            # Do something to program and see if it worked
            program['pos'] = [(1, 2, 3, 1), (4, 5, 6, 1)]  # Do command
            program.draw('points')
            check_error()

        # Check while c1 is active
        check()

        # Check while c2 is active (with different context)
        with Canvas() as c2:
            # pyglet always shares
            if 'pyglet' not in c2.app.backend_name.lower():
                assert_raises(Exception, check)

        # Check while c2 is active (with *same* context)
        with Canvas(shared=c1.context) as c2:
            assert c1.context.shared is c2.context.shared  # same object
            check()
Esempio n. 7
0
def test_context_sharing():
    """Test context sharing"""
    with Canvas() as c1:
        vert = "attribute vec4 pos;\nvoid main (void) {gl_Position = pos;}"
        frag = "void main (void) {gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);}"
        program = Program(vert, frag)
        program['pos'] = [(1, 2, 3, 1), (4, 5, 6, 1)]
        program.draw('points')

        def check():
            # Do something to program and see if it worked
            program['pos'] = [(1, 2, 3, 1), (4, 5, 6, 1)]  # Do command
            program.draw('points')
            check_error()

        # Check while c1 is active
        check()

        # Check while c2 is active (with different context)
        with Canvas() as c2:
            # pyglet always shares
            if 'pyglet' not in c2.app.backend_name.lower():
                assert_raises(Exception, check)

        # Check while c2 is active (with *same* context)
        with Canvas(shared=c1.context) as c2:
            assert c1.context.shared is c2.context.shared  # same object
            check()
Esempio n. 8
0
def test_context_config():
    """ Test GLContext handling of config dict
    """
    default_config = get_default_config()
    
    # Pass default config unchanged
    c = GLContext(default_config)
    assert_equal(c.config, default_config)
    # Must be deep copy
    c.config['double_buffer'] = False
    assert_not_equal(c.config, default_config)
    
    # Passing nothing should yield default config
    c = GLContext()
    assert_equal(c.config, default_config)
    # Must be deep copy
    c.config['double_buffer'] = False
    assert_not_equal(c.config, default_config)
    
    # This should work
    c = GLContext({'red_size': 4, 'double_buffer': False})
    assert_equal(c.config.keys(), default_config.keys())
    
    # Passing crap should raise
    assert_raises(KeyError, GLContext, {'foo': 3})
    assert_raises(TypeError, GLContext, {'double_buffer': 'not_bool'})
Esempio n. 9
0
def test_Variable():
    
    # Test init fail
    assert_raises(TypeError, Variable)  # no args
    assert_raises(TypeError, Variable, 3)  # wrong type
    assert_raises(TypeError, Variable, "name", "str")  # wrong type
    assert_raises(ValueError, Variable, 'bla bla')  # need correct vtype
    assert_raises(ValueError, Variable, 'uniform b l a')  # too many
    
    # Test init success
    var = Variable('uniform float bla')  # Finally
    assert_equal(var.name, 'bla')
    assert_equal(var.dtype, 'float')
    assert_equal(var.vtype, 'uniform')
    assert var.value is None
    
    # test assign new value
    var.value = 10.
    assert_equal(var.dtype, 'float')  # type is locked; won't change
    
    # test name-only init
    var = Variable('bla')  # Finally
    assert_equal(var.name, 'bla')
    assert_equal(var.dtype, None)
    assert_equal(var.vtype, None)
    assert var.value is None
    
    # test assign new value
    var.value = 10
    assert_equal(var.dtype, 'int')
    assert_equal(var.vtype, 'uniform')
    assert_equal(var.value, 10)
    
    # test init with value
    var = Variable('bla', (1, 2, 3))  # Also valid
    assert_equal(var.name, 'bla')
    assert_equal(var.dtype, 'vec3')
    assert_equal(var.vtype, 'uniform')
    assert_equal(var.value, (1, 2, 3))
    
    # Test value
    #var = Variable('uniform float bla', data)  # Also valid
    #assert_equal(var.value, data)
    #var.value = 3
    #assert_equal(var.value, 3)
    
    # Test repr
    var = Variable('uniform float bla')
    assert_in('uniform float bla', var.compile())
    
    # Test injection, definition, dependencies
    assert_equal(var.expression({var: 'xxx'}), 'xxx')
    assert_equal(var.definition({var: 'xxx'}), 'uniform float xxx;')
    assert_in(var, var.dependencies())
    
    # Renaming
    var = Variable('uniform float bla')
    assert_equal(var.name, 'bla')
    var.name = 'foo'
    assert_equal(var.name, 'foo')
Esempio n. 10
0
def test_config():
    """Test vispy config methods and file downloading"""
    assert_raises(TypeError, config.update, data_path=dict())
    assert_raises(KeyError, config.update, foo='bar')  # bad key
    data_dir = op.join(temp_dir, 'data')
    assert_raises(IOError, set_data_dir, data_dir)  # didn't say to create
    orig_val = os.environ.get('_VISPY_CONFIG_TESTING', None)
    os.environ['_VISPY_CONFIG_TESTING'] = 'true'
    try:
        assert_raises(IOError, set_data_dir, data_dir)  # doesn't exist yet
        set_data_dir(data_dir, create=True, save=True)
        assert_equal(config['data_path'], data_dir)
        config['data_path'] = data_dir
        print(config)  # __repr__
        load_data_file('CONTRIBUTING.txt')
        fid = open(op.join(data_dir, 'test-faked.txt'), 'w')
        fid.close()
        load_data_file('test-faked.txt')  # this one shouldn't download
        assert_raises(RuntimeError, load_data_file, 'foo-nonexist.txt')
        save_config()
    finally:
        if orig_val is not None:
            os.environ['_VISPY_CONFIG_TESTING'] = orig_val
        else:
            del os.environ['_VISPY_CONFIG_TESTING']
Esempio n. 11
0
def test_check_enum():
    from vispy.gloo import gl
    
    # Test enums
    assert util.check_enum(gl.GL_RGB) == 'rgb' 
    assert util.check_enum(gl.GL_TRIANGLE_STRIP) == 'triangle_strip' 
    
    # Test strings
    assert util.check_enum('RGB') == 'rgb' 
    assert util.check_enum('Triangle_STRIp') == 'triangle_strip' 
    
    # Test wrong input
    assert_raises(ValueError, util.check_enum, int(gl.GL_RGB))
    assert_raises(ValueError, util.check_enum, int(gl.GL_TRIANGLE_STRIP))
    assert_raises(ValueError, util.check_enum, [])
    
    # Test with test
    util.check_enum('RGB', 'test', ('rgb', 'alpha')) == 'rgb' 
    util.check_enum(gl.GL_ALPHA, 'test', ('rgb', 'alpha')) == 'alpha' 
    #
    assert_raises(ValueError, util.check_enum, 'RGB', 'test', ('a', 'b'))
    assert_raises(ValueError, util.check_enum, gl.GL_ALPHA, 'test', ('a', 'b'))
    
    # Test PyOpenGL enums
    try:
        from OpenGL import GL
    except ImportError:
        return  # we cannot test PyOpenGL
    #
    assert util.check_enum(GL.GL_RGB) == 'rgb' 
    assert util.check_enum(GL.GL_TRIANGLE_STRIP) == 'triangle_strip' 
Esempio n. 12
0
def test_FunctionCall():
    fun = Function(transformScale)
    fun['scale'] = '1.0'
    fun2 = Function(transformZOffset)
    
    # No args
    assert_raises(TypeError, fun)  # need 1 arg
    assert_raises(TypeError, fun, 1, 2)  # need 1 arg
    call = fun('x')
    # Test repr
    exp = call.expression({fun: 'y'})
    assert_equal(exp, 'y(x)')
    # Test sig
    assert len(call._args) == 1
    # Test dependencies
    assert_in(fun, call.dependencies())
    assert_in(call._args[0], call.dependencies())
    
    # More args
    call = fun(fun2('foo'))
    # Test repr
    exp = call.expression({fun: 'y', fun2: 'z'})
    assert_in('y(z(', exp)
    # Test sig
    assert len(call._args) == 1
    call2 = call._args[0]
    assert len(call2._args) == 1
    # Test dependencies
    assert_in(fun, call.dependencies())
    assert_in(call._args[0], call.dependencies())
    assert_in(fun2, call.dependencies())
    assert_in(call2._args[0], call.dependencies())
Esempio n. 13
0
def test_color_array():
    """Basic tests for ColorArray class"""
    x = ColorArray(['r', 'g', 'b'])
    assert_array_equal(x.rgb, np.eye(3))
    # Test ColorArray.__getitem__.
    assert isinstance(x[0], ColorArray)
    assert isinstance(x[:], ColorArray)
    assert_array_equal(x.rgba[:], x[:].rgba)
    assert_array_equal(x.rgba[0], x[0].rgba.squeeze())
    assert_array_equal(x.rgba[1:3], x[1:3].rgba)
    assert_raises(ValueError, x.__getitem__, (0, 1))
    # Test ColorArray.__setitem__.
    x[0] = 0
    assert_array_equal(x.rgba[0, :], np.zeros(4))
    assert_array_equal(x.rgba, x[:].rgba)
    x[1] = 1
    assert_array_equal(x[1].rgba, np.ones((1, 4)))
    x[:] = .5
    assert_array_equal(x.rgba, .5 * np.ones((3, 4)))
    assert_raises(ValueError, x.__setitem__, (0, 1), 0)

    # test hsv color space colors
    x = ColorArray(color_space="hsv",
                   color=[(0, 0, 1), (0, 0, 0.5), (0, 0, 0)])
    assert_array_equal(x.rgba[0], [1, 1, 1, 1])
    assert_array_equal(x.rgba[1], [0.5, 0.5, 0.5, 1])
    assert_array_equal(x.rgba[2], [0, 0, 0, 1])

    x = ColorArray(color_space="hsv")
    assert_array_equal(x.rgba[0], [0, 0, 0, 1])
Esempio n. 14
0
def test_use():

    # Set default app to None, so we can test the use function
    vispy.app.use_app()
    default_app = vispy.app._default_app.default_app
    vispy.app._default_app.default_app = None

    app_name = default_app.backend_name.split(' ')[0]

    try:
        # With no arguments, should do nothing
        assert_raises(TypeError, vispy.use)
        assert_equal(vispy.app._default_app.default_app, None)

        # With only gl args, should do nothing to app
        vispy.use(gl='gl2')
        assert_equal(vispy.app._default_app.default_app, None)

        # Specify app (one we know works)
        vispy.use(app_name)
        assert_not_equal(vispy.app._default_app.default_app, None)

        # Again, but now wrong app
        wrong_name = 'glfw' if app_name.lower() != 'glfw' else 'pyqt4'
        assert_raises(RuntimeError, vispy.use, wrong_name)

        # And both
        vispy.use(app_name, 'gl2')

    finally:
        # Restore
        vispy.app._default_app.default_app = default_app
Esempio n. 15
0
def test_capability():
    """Test application capability enumeration"""
    non_default_vals = dict(title='foo',
                            size=[100, 100],
                            position=[0, 0],
                            show=True,
                            decorate=False,
                            resizable=False,
                            vsync=True)  # context is tested elsewhere
    good_kwargs = dict()
    bad_kwargs = dict()
    with Canvas() as c:
        for key, val in c.app.backend_module.capability.items():
            if key in non_default_vals:
                if val:
                    good_kwargs[key] = non_default_vals[key]
                else:
                    bad_kwargs[key] = non_default_vals[key]
    # ensure all settable values can be set
    with Canvas(**good_kwargs):
        # some of these are hard to test, and the ones that are easy are
        # tested elsewhere, so let's just make sure it runs here
        pass
    # ensure that *any* bad argument gets caught
    for key, val in bad_kwargs.items():
        assert_raises(RuntimeError, Canvas, **{key: val})
Esempio n. 16
0
def test_check_enum():
    from vispy.gloo import gl

    # Test enums
    assert util.check_enum(gl.GL_RGB) == 'rgb'
    assert util.check_enum(gl.GL_TRIANGLE_STRIP) == 'triangle_strip'

    # Test strings
    assert util.check_enum('RGB') == 'rgb'
    assert util.check_enum('Triangle_STRIp') == 'triangle_strip'

    # Test wrong input
    assert_raises(ValueError, util.check_enum, int(gl.GL_RGB))
    assert_raises(ValueError, util.check_enum, int(gl.GL_TRIANGLE_STRIP))
    assert_raises(ValueError, util.check_enum, [])

    # Test with test
    util.check_enum('RGB', 'test', ('rgb', 'alpha')) == 'rgb'
    util.check_enum(gl.GL_ALPHA, 'test', ('rgb', 'alpha')) == 'alpha'
    #
    assert_raises(ValueError, util.check_enum, 'RGB', 'test', ('a', 'b'))
    assert_raises(ValueError, util.check_enum, gl.GL_ALPHA, 'test', ('a', 'b'))

    # Test PyOpenGL enums
    try:
        from OpenGL import GL
    except ImportError:
        return  # we cannot test PyOpenGL
    #
    assert util.check_enum(GL.GL_RGB) == 'rgb'
    assert util.check_enum(GL.GL_TRIANGLE_STRIP) == 'triangle_strip'
Esempio n. 17
0
def test_FunctionCall():
    fun = Function(transformScale)
    fun['scale'] = '1.0'
    fun2 = Function(transformZOffset)

    # No args
    assert_raises(TypeError, fun)  # need 1 arg
    assert_raises(TypeError, fun, 1, 2)  # need 1 arg
    call = fun('x')
    # Test repr
    exp = call.expression({fun: 'y'})
    assert_equal(exp, 'y(x)')
    # Test sig
    assert len(call._args) == 1
    # Test dependencies
    assert_in(fun, call.dependencies())
    assert_in(call._args[0], call.dependencies())

    # More args
    call = fun(fun2('foo'))
    # Test repr
    exp = call.expression({fun: 'y', fun2: 'z'})
    assert_in('y(z(', exp)
    # Test sig
    assert len(call._args) == 1
    call2 = call._args[0]
    assert len(call2._args) == 1
    # Test dependencies
    assert_in(fun, call.dependencies())
    assert_in(call._args[0], call.dependencies())
    assert_in(fun2, call.dependencies())
    assert_in(call2._args[0], call.dependencies())
Esempio n. 18
0
def test_linear_region_vertical_horizontal():
    """Test vertical and horizontal LinearRegionVisual with a single color"""

    # Definition of the region
    pos = np.array([5, 15, 24, 36, 40, 42], dtype=np.float32)
    # Expected internal pos buffer for vertical region
    expected_pos_v = np.array([[5.0, -1.],
                               [5.0, 1.],
                               [15.0, -1.],
                               [15.0, 1.],
                               [24.0, -1.],
                               [24.0, 1.],
                               [36.0, -1.],
                               [36.0, 1.],
                               [40.0, -1.],
                               [40.0, 1.],
                               [42.0, -1.],
                               [42.0, 1.]], dtype=np.float32)
    # Expected internal pos buffer for horizontal region
    expected_pos_h = np.array([expected_pos_v[:, 1] * -1,
                               expected_pos_v[:, 0]], dtype=np.float32).T

    # Test both horizontal and vertical region
    for is_vertical, reference_image in [(True, 'linear_region1.png'),
                                         (False, 'linear_region1_h.png')]:

        expected_pos = expected_pos_v if is_vertical else expected_pos_h

        with TestingCanvas() as c:
            # Check set_data is working correctly within visual constructor
            region = visuals.LinearRegion(pos=pos,
                                          color=[0.0, 1.0, 0.0, 0.5],
                                          vertical=is_vertical,
                                          parent=c.scene)
            assert np.all(region._pos == expected_pos)
            assert np.all(region.pos == pos)
            assert region.is_vertical == is_vertical

            # Check set_data is working as expected when passing a list as
            # pos argument
            region.set_data(pos=list(pos))
            assert np.all(region._pos == expected_pos)
            assert np.all(region.pos == pos)

            # Check set_data is working as expected when passing a tuple as
            # pos argument
            region.set_data(pos=tuple(pos))
            assert np.all(region._pos == expected_pos)
            assert np.all(region.pos == pos)

            # Test with different dtypes that must be converted to float32
            for t in [np.int64, np.float64, np.int32]:
                region.set_data(pos=pos.astype(t))
                assert np.all(region._pos == expected_pos)
                assert np.all(region.pos == pos)

            assert_image_approved(c.render(), 'visuals/%s' % reference_image)

            # Check ValueError is raised when pos is not 1D
            assert_raises(ValueError, region.set_data, pos=[[1, 2], [3, 4]])
Esempio n. 19
0
def test_color_array():
    """Basic tests for ColorArray class"""
    x = ColorArray(['r', 'g', 'b'])
    assert_array_equal(x.rgb, np.eye(3))
    # Test ColorArray.__getitem__.
    assert isinstance(x[0], ColorArray)
    assert isinstance(x[:], ColorArray)
    assert_array_equal(x.rgba[:], x[:].rgba)
    assert_array_equal(x.rgba[0], x[0].rgba.squeeze())
    assert_array_equal(x.rgba[1:3], x[1:3].rgba)
    assert_raises(ValueError, x.__getitem__, (0, 1))
    # Test ColorArray.__setitem__.
    x[0] = 0
    assert_array_equal(x.rgba[0, :], np.zeros(4))
    assert_array_equal(x.rgba, x[:].rgba)
    x[1] = 1
    assert_array_equal(x[1].rgba, np.ones((1, 4)))
    x[:] = .5
    assert_array_equal(x.rgba, .5 * np.ones((3, 4)))
    assert_raises(ValueError, x.__setitem__, (0, 1), 0)

    # test hsv color space colors
    x = ColorArray(color_space="hsv", color=[(0, 0, 1),
                   (0, 0, 0.5), (0, 0, 0)])
    assert_array_equal(x.rgba[0], [1, 1, 1, 1])
    assert_array_equal(x.rgba[1], [0.5, 0.5, 0.5, 1])
    assert_array_equal(x.rgba[2], [0, 0, 0, 1])

    x = ColorArray(color_space="hsv")
    assert_array_equal(x.rgba[0], [0, 0, 0, 1])
Esempio n. 20
0
def _test_texture_internalformats(Texture, baseshape):
    # Test format for concrete Texture class and baseshape + (numchannels,)
    # Test internalformats valid with desktop OpenGL

    formats = [
        (1, 'red', ['red', 'r8', 'r16', 'r16f', 'r32f']),
        (2, 'rg', ['rg', 'rg8', 'rg16', 'rg16f', 'rg32f']),
        (3, 'rgb', ['rgb', 'rgb8', 'rgb16', 'rgb16f', 'rgb32f']),
        (4, 'rgba', ['rgba', 'rgba8', 'rgba16', 'rgba16f', 'rgba32f'])
    ]
        
    for channels in range(1, 5):
        for fmt, ifmts in [(f, iL) for n, f, iL in formats if n == channels]:
            shape = baseshape + (channels,)
            data = np.zeros(shape, dtype=np.uint8)
            for ifmt in ifmts:
                T = Texture(shape=shape, format=fmt, internalformat=ifmt)
                assert 'Texture' in repr(T)
                assert T._shape == shape
                T = Texture(data=data, format=fmt, internalformat=ifmt)
                assert 'Texture' in repr(T)
                assert T._shape == shape

    for channels in range(1, 5):
        for fmt, ifmts in [(f, iL) for n, f, iL in formats if n != channels]:
            shape = baseshape + (channels,)
            data = np.zeros(shape, dtype=np.uint8)
            for ifmt in ifmts:
                assert_raises(ValueError, Texture, shape=shape, format=fmt,
                              internalformat=ifmt)
                assert_raises(ValueError, Texture, data=data, format=fmt,
                              internalformat=ifmt)
Esempio n. 21
0
def test_Variable():

    # Test init fail
    assert_raises(TypeError, Variable)  # no args
    assert_raises(TypeError, Variable, 3)  # wrong type
    assert_raises(TypeError, Variable, "name", "str")  # wrong type
    assert_raises(ValueError, Variable, 'bla bla')  # need correct vtype
    assert_raises(ValueError, Variable, 'uniform b l a')  # too many

    # Test init success
    var = Variable('uniform float bla')  # Finally
    assert_equal(var.name, 'bla')
    assert_equal(var.dtype, 'float')
    assert_equal(var.vtype, 'uniform')
    assert var.value is None

    # test assign new value
    var.value = 10.
    assert_equal(var.dtype, 'float')  # type is locked; won't change

    # test name-only init
    var = Variable('bla')  # Finally
    assert_equal(var.name, 'bla')
    assert_equal(var.dtype, None)
    assert_equal(var.vtype, None)
    assert var.value is None

    # test assign new value
    var.value = 10
    assert_equal(var.dtype, 'int')
    assert_equal(var.vtype, 'uniform')
    assert_equal(var.value, 10)

    # test init with value
    var = Variable('bla', (1, 2, 3))  # Also valid
    assert_equal(var.name, 'bla')
    assert_equal(var.dtype, 'vec3')
    assert_equal(var.vtype, 'uniform')
    assert_equal(var.value, (1, 2, 3))

    # Test value
    #var = Variable('uniform float bla', data)  # Also valid
    #assert_equal(var.value, data)
    #var.value = 3
    #assert_equal(var.value, 3)

    # Test repr
    var = Variable('uniform float bla')
    assert_in('uniform float bla', var.compile())

    # Test injection, definition, dependencies
    assert_equal(var.expression({var: 'xxx'}), 'xxx')
    assert_equal(var.definition({var: 'xxx'}), 'uniform float xxx;')
    assert_in(var, var.dependencies())

    # Renaming
    var = Variable('uniform float bla')
    assert_equal(var.name, 'bla')
    var.name = 'foo'
    assert_equal(var.name, 'foo')
Esempio n. 22
0
def test_use_uniforms():
    """Test using uniform arrays"""
    VERT_SHADER = """
    attribute vec2 a_pos;
    varying vec2 v_pos;

    void main (void)
    {
        v_pos = a_pos;
        gl_Position = vec4(a_pos, 0., 1.);
    }
    """

    FRAG_SHADER = """
    varying vec2 v_pos;
    uniform vec3 u_color[2];

    void main()
    {
        gl_FragColor = vec4((u_color[0] + u_color[1]) / 2., 1.);
    }
    """
    shape = (500, 500)
    with Canvas(size=shape) as c:
        c.set_current()
        c.context.glir.set_verbose(True)
        assert_equal(c.size, shape[::-1])
        shape = (3, 3)
        set_viewport((0, 0) + shape)
        program = Program(VERT_SHADER, FRAG_SHADER)
        program['a_pos'] = [[-1., -1.], [1., -1.], [-1., 1.], [1., 1.]]
        program['u_color'] = np.ones((2, 3))
        c.context.clear('k')
        c.set_current()
        program.draw('triangle_strip')
        out = _screenshot()
        assert_allclose(out[:, :, 0] / 255., np.ones(shape), atol=1. / 255.)

        # now set one element
        program['u_color[1]'] = np.zeros(3, np.float32)
        c.context.clear('k')
        program.draw('triangle_strip')
        out = _screenshot()
        assert_allclose(out[:, :, 0] / 255.,
                        127.5 / 255. * np.ones(shape),
                        atol=1. / 255.)

        # and the other
        assert_raises(ValueError, program.__setitem__, 'u_color',
                      np.zeros(3, np.float32))
        program['u_color'] = np.zeros((2, 3), np.float32)
        program['u_color[0]'] = np.ones(3, np.float32)
        c.context.clear((0.33, ) * 3)
        program.draw('triangle_strip')
        out = _screenshot()
        assert_allclose(out[:, :, 0] / 255.,
                        127.5 / 255. * np.ones(shape),
                        atol=1. / 255.)
Esempio n. 23
0
def test_figure_creation():
    """Test creating a figure"""
    with vp.Fig(show=False) as fig:
        fig[0, 0:2]
        fig[1:3, 0:2]
        ax_right = fig[1:3, 2]
        assert fig[1:3, 2] is ax_right
        # collision
        assert_raises(ValueError, fig.__getitem__, (slice(1, 3), 1))
Esempio n. 24
0
def test_figure_creation():
    """Test creating a figure"""
    with vp.Fig(show=False) as fig:
        fig[0, 0:2]
        fig[1:3, 0:2]
        ax_right = fig[1:3, 2]
        assert fig[1:3, 2] is ax_right
        # collision
        assert_raises(ValueError, fig.__getitem__, (slice(1, 3), 1))
Esempio n. 25
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, ))
Esempio n. 26
0
def test_use_uniforms():
    """Test using uniform arrays"""
    VERT_SHADER = """
    attribute vec2 a_pos;
    varying vec2 v_pos;

    void main (void)
    {
        v_pos = a_pos;
        gl_Position = vec4(a_pos, 0., 1.);
    }
    """

    FRAG_SHADER = """
    varying vec2 v_pos;
    uniform vec3 u_color[2];

    void main()
    {
        gl_FragColor = vec4((u_color[0] + u_color[1]) / 2., 1.);
    }
    """
    shape = (500, 500)
    with Canvas(size=shape) as c:
        c.set_current()
        c.context.glir.set_verbose(True)
        assert_equal(c.size, shape[::-1])
        shape = (3, 3)
        set_viewport((0, 0) + shape)
        program = Program(VERT_SHADER, FRAG_SHADER)
        program['a_pos'] = [[-1., -1.], [1., -1.], [-1., 1.], [1., 1.]]
        program['u_color'] = np.ones((2, 3))
        c.context.clear('k')
        c.set_current()
        program.draw('triangle_strip')
        out = _screenshot()
        assert_allclose(out[:, :, 0] / 255., np.ones(shape), atol=1. / 255.)

        # now set one element
        program['u_color[1]'] = np.zeros(3, np.float32)
        c.context.clear('k')
        program.draw('triangle_strip')
        out = _screenshot()
        assert_allclose(out[:, :, 0] / 255., 127.5 / 255. * np.ones(shape),
                        atol=1. / 255.)

        # and the other
        assert_raises(ValueError, program.__setitem__, 'u_color',
                      np.zeros(3, np.float32))
        program['u_color'] = np.zeros((2, 3), np.float32)
        program['u_color[0]'] = np.ones(3, np.float32)
        c.context.clear((0.33,) * 3)
        program.draw('triangle_strip')
        out = _screenshot()
        assert_allclose(out[:, :, 0] / 255., 127.5 / 255. * np.ones(shape),
                        atol=1. / 255.)
Esempio n. 27
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,))
Esempio n. 28
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
Esempio n. 29
0
def test_use_texture3D():
    """Test using a 3D texture"""
    vals = [0, 200, 100, 0, 255, 0, 100]
    d, h, w = len(vals), 3, 5
    data = np.zeros((d, h, w), np.float32)

    VERT_SHADER = """
    attribute vec2 a_pos;
    varying vec2 v_pos;

    void main (void)
    {
        v_pos = a_pos;
        gl_Position = vec4(a_pos, 0., 1.);
    }
    """

    FRAG_SHADER = """
    uniform sampler3D u_texture;
    varying vec2 v_pos;
    uniform float i;
    void main()
    {
        gl_FragColor = texture3D(u_texture,
                                 vec3((v_pos.y+1.)/2., (v_pos.x+1.)/2., i));
        gl_FragColor.a = 1.;
    }
    """
    # populate the depth "slices" with different gray colors in the bottom left
    for ii, val in enumerate(vals):
        data[ii, :2, :3] = val / 255.
    with Canvas(size=(100, 100)) as c:
        if not has_pyopengl():
            t = Texture3D(data)
            assert_raises(ImportError, t.glir.flush, c.context.shared.parser)
            return
        program = Program(VERT_SHADER, FRAG_SHADER)
        program['a_pos'] = [[-1., -1.], [1., -1.], [-1., 1.], [1., 1.]]
        tex = Texture3D(data, interpolation='nearest')
        assert_equal(tex.width, w)
        assert_equal(tex.height, h)
        assert_equal(tex.depth, d)
        program['u_texture'] = tex
        for ii, val in enumerate(vals):
            set_viewport(0, 0, w, h)
            clear(color='black')
            iii = (ii + 0.5) / float(d)
            print(ii, iii)
            program['i'] = iii
            program.draw('triangle_strip')
            out = _screenshot()[:, :, 0].astype(int)[::-1]
            expected = np.zeros_like(out)
            expected[:2, :3] = val
            assert_allclose(out, expected, atol=1./255.)
Esempio n. 30
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
Esempio n. 31
0
def test_use_texture3D():
    """Test using a 3D texture"""
    vals = [0, 200, 100, 0, 255, 0, 100]
    d, h, w = len(vals), 3, 5
    data = np.zeros((d, h, w), np.float32)

    VERT_SHADER = """
    attribute vec2 a_pos;
    varying vec2 v_pos;

    void main (void)
    {
        v_pos = a_pos;
        gl_Position = vec4(a_pos, 0., 1.);
    }
    """

    FRAG_SHADER = """
    uniform sampler3D u_texture;
    varying vec2 v_pos;
    uniform float i;
    void main()
    {
        gl_FragColor = texture3D(u_texture,
                                 vec3((v_pos.y+1.)/2., (v_pos.x+1.)/2., i));
        gl_FragColor.a = 1.;
    }
    """
    # populate the depth "slices" with different gray colors in the bottom left
    for ii, val in enumerate(vals):
        data[ii, :2, :3] = val / 255.
    with Canvas(size=(100, 100)) as c:
        if not has_pyopengl():
            t = Texture3D(data)
            assert_raises(ImportError, t.glir.flush, c.context.shared.parser)
            return
        program = Program(VERT_SHADER, FRAG_SHADER)
        program['a_pos'] = [[-1., -1.], [1., -1.], [-1., 1.], [1., 1.]]
        tex = Texture3D(data, interpolation='nearest')
        assert_equal(tex.width, w)
        assert_equal(tex.height, h)
        assert_equal(tex.depth, d)
        program['u_texture'] = tex
        for ii, val in enumerate(vals):
            set_viewport(0, 0, w, h)
            clear(color='black')
            iii = (ii + 0.5) / float(d)
            print(ii, iii)
            program['i'] = iii
            program.draw('triangle_strip')
            out = _screenshot()[:, :, 0].astype(int)[::-1]
            expected = np.zeros_like(out)
            expected[:2, :3] = val
            assert_allclose(out, expected, atol=1. / 255.)
Esempio n. 32
0
def test_get_layout():
    from vispy.visuals.graphs.layouts.random import random

    # Simple retrieval
    assert_equal(random, get_layout('random'))

    # Pass arguments
    fruchterman_reingold = get_layout('force_directed', iterations=100)
    assert_equal(fruchterman_reingold.iterations, 100)

    # Check if layout exists
    assert_raises(KeyError, get_layout, 'fdgdfgs_non_existent')
Esempio n. 33
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)
Esempio n. 34
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)
Esempio n. 35
0
def test_get_layout():
    from vispy.visuals.graphs.layouts.random import random

    # Simple retrieval
    assert_equal(random, get_layout('random'))

    # Pass arguments
    fruchterman_reingold = get_layout('force_directed', iterations=100)
    assert_equal(fruchterman_reingold.iterations, 100)

    # Check if layout exists
    assert_raises(KeyError, get_layout, 'fdgdfgs_non_existent')
Esempio n. 36
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)
Esempio n. 37
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)
Esempio n. 38
0
def test_context_properties():
    """Test setting context properties"""
    a = use_app()
    if a.backend_name.lower() == 'pyglet':
        return  # cannot set more than once on Pyglet
    # stereo, double buffer won't work on every sys
    configs = [dict(samples=4), dict(stencil_size=8),
               dict(samples=4, stencil_size=8)]
    if a.backend_name.lower() != 'glfw':  # glfw *always* double-buffers
        configs.append(dict(double_buffer=False, samples=4))
        configs.append(dict(double_buffer=False))
    else:
        assert_raises(RuntimeError, Canvas, app=a,
                      config=dict(double_buffer=False))
    if a.backend_name.lower() == 'sdl2' and os.getenv('TRAVIS') == 'true':
        raise SkipTest('Travis SDL cannot set context')
    for config in configs:
        n_items = len(config)
        with Canvas(config=config):
            if 'true' in (os.getenv('TRAVIS', ''),
                          os.getenv('APPVEYOR', '').lower()):
                # Travis and Appveyor cannot handle obtaining these values
                props = config
            else:
                props = get_gl_configuration()
            assert_equal(len(config), n_items)
            for key, val in config.items():
                # XXX knownfail for windows samples, and wx (all platforms)
                if key == 'samples':
                    iswx = a.backend_name.lower() == 'wx'
                    if not (sys.platform.startswith('win') or iswx):
                        assert_equal(val, props[key], key)
    assert_raises(TypeError, Canvas, config='foo')
    assert_raises(KeyError, Canvas, config=dict(foo=True))
    assert_raises(TypeError, Canvas, config=dict(double_buffer='foo'))
Esempio n. 39
0
def test_context_properties():
    """Test setting context properties"""
    a = use_app()
    if a.backend_name.lower() == 'pyglet':
        return  # cannot set more than once on Pyglet
    # stereo, double buffer won't work on every sys
    configs = [dict(samples=4), dict(stencil_size=8),
               dict(samples=4, stencil_size=8)]
    if a.backend_name.lower() != 'glfw':  # glfw *always* double-buffers
        configs.append(dict(double_buffer=False, samples=4))
        configs.append(dict(double_buffer=False))
    else:
        assert_raises(RuntimeError, Canvas, app=a,
                      config=dict(double_buffer=False))
    if a.backend_name.lower() == 'sdl2' and os.getenv('TRAVIS') == 'true':
        raise SkipTest('Travis SDL cannot set context')
    for config in configs:
        n_items = len(config)
        with Canvas(config=config):
            if 'true' in (os.getenv('TRAVIS', ''),
                          os.getenv('APPVEYOR', '').lower()):
                # Travis and Appveyor cannot handle obtaining these values
                props = config
            else:
                props = get_gl_configuration()
            assert_equal(len(config), n_items)
            for key, val in config.items():
                # XXX knownfail for windows samples, and wx (all platforms)
                if key == 'samples':
                    iswx = a.backend_name.lower() == 'wx'
                    if not (sys.platform.startswith('win') or iswx):
                        assert_equal(val, props[key], key)
    assert_raises(TypeError, Canvas, config='foo')
    assert_raises(KeyError, Canvas, config=dict(foo=True))
    assert_raises(TypeError, Canvas, config=dict(double_buffer='foo'))
Esempio n. 40
0
def test_colormap_interpolation():
    """Test interpolation routines for colormaps."""
    import vispy.color.colormap as c
    assert_raises(AssertionError, c._glsl_step, [0., 1.],)

    for fun in (c._glsl_step, c._glsl_mix):
        assert_raises(AssertionError, fun, controls=[0.1, 1.],)
        assert_raises(AssertionError, fun, controls=[0., .9],)
        assert_raises(AssertionError, fun, controls=[0.1, .9],)

    # Interpolation tests.
    color_0 = np.array([1., 0., 0.])
    color_1 = np.array([0., 1., 0.])
    color_2 = np.array([0., 0., 1.])

    colors_00 = np.vstack((color_0, color_0))
    colors_01 = np.vstack((color_0, color_1))
    colors_11 = np.vstack((color_1, color_1))
    # colors_012 = np.vstack((color_0, color_1, color_2))
    colors_021 = np.vstack((color_0, color_2, color_1))

    controls_2 = np.array([0., 1.])
    controls_3 = np.array([0., .25, 1.])
    x = np.array([-1., 0., 0.1, 0.4, 0.5, 0.6, 1., 2.])[:, None]

    mixed_2 = c.mix(colors_01, x, controls_2)
    mixed_3 = c.mix(colors_021, x, controls_3)

    for y in mixed_2, mixed_3:
        assert_allclose(y[:2, :], colors_00)
        assert_allclose(y[-2:, :], colors_11)

    assert_allclose(mixed_2[:, -1], np.zeros(len(y)))
Esempio n. 41
0
def test_colormap_interpolation():
    """Test interpolation routines for colormaps."""
    import vispy.color.colormap as c
    assert_raises(AssertionError, c._glsl_step, [0., 1.],)

    for fun in (c._glsl_step, c._glsl_mix):
        assert_raises(AssertionError, fun, controls=[0.1, 1.],)
        assert_raises(AssertionError, fun, controls=[0., .9],)
        assert_raises(AssertionError, fun, controls=[0.1, .9],)

    # Interpolation tests.
    color_0 = np.array([1., 0., 0.])
    color_1 = np.array([0., 1., 0.])
    color_2 = np.array([0., 0., 1.])

    colors_00 = np.vstack((color_0, color_0))
    colors_01 = np.vstack((color_0, color_1))
    colors_11 = np.vstack((color_1, color_1))
    # colors_012 = np.vstack((color_0, color_1, color_2))
    colors_021 = np.vstack((color_0, color_2, color_1))

    controls_2 = np.array([0., 1.])
    controls_3 = np.array([0., .25, 1.])
    x = np.array([-1., 0., 0.1, 0.4, 0.5, 0.6, 1., 2.])[:, None]

    mixed_2 = c.mix(colors_01, x, controls_2)
    mixed_3 = c.mix(colors_021, x, controls_3)

    for y in mixed_2, mixed_3:
        assert_allclose(y[:2, :], colors_00)
        assert_allclose(y[-2:, :], colors_11)

    assert_allclose(mixed_2[:, -1], np.zeros(len(y)))
Esempio n. 42
0
def test_show_vispy():
    """Some basic tests of show_vispy"""
    if has_matplotlib():
        n = 200
        t = np.arange(n)
        noise = np.random.RandomState(0).randn(n)
        # Need, image, markers, line, axes, figure
        plt.figure()
        ax = plt.subplot(211)
        ax.imshow(read_png(load_data_file('pyplot/logo.png')))
        ax = plt.subplot(212)
        ax.plot(t, noise, 'ko-')
        plt.draw()
        canvases = plt.show()
        canvases[0].close()
    else:
        assert_raises(ImportError, plt.show)
Esempio n. 43
0
def test_linear_region_color():
    """Test the color argument of LinearRegionVisual.set_data() method
    using a single color
    """
    # Definition of the region
    pos1 = [5, 42]
    # Definition of the color of the region
    color1 = np.array([0.0, 1.0, 0.0, 0.5], dtype=np.float32)
    # Expected internal color buffer
    color1_expected = np.array([color1, color1, color1, color1],
                               dtype=np.float32)

    with TestingCanvas() as c:
        # Check set_data is working correctly within visual constructor
        region = visuals.LinearRegion(pos=pos1, color=color1, parent=c.scene)
        assert np.all(region._color == color1_expected)
        assert np.all(region.color == color1)

        # Check set_data is working as expected when passing a list as
        # color argument
        region.set_data(color=list(color1))
        assert np.all(region._color == color1_expected)
        assert np.all(region.color == color1)

        # Check set_data is working as expected when passing a tuple as
        # color argument
        region.set_data(color=tuple(color1))
        assert np.all(region._color == color1_expected)
        assert np.all(region.color == color1)

        # Test with different dtypes that must be converted to float32
        region.set_data(color=color1.astype(np.float64))
        assert np.all(region._color == color1_expected)
        assert np.all(region.color == color1)

        assert_image_approved(c.render(), 'visuals/linear_region1.png')

        # Check a ValueError is raised when the length of color argument
        # is not 4.
        assert_raises(ValueError, region.set_data, color=[1.0, 0.5, 0.5])

        # Check a ValueError is raised when too many colors are provided
        assert_raises(ValueError,
                      region.set_data,
                      color=[color1, color1, color1])
Esempio n. 44
0
def test_linear_region_color():
    """Test the color argument of LinearRegionVisual.set_data() method
    using a single color"""

    # Definition of the region
    pos1 = [5, 42]
    # Definition of the color of the region
    color1 = np.array([0.0, 1.0, 0.0, 0.5], dtype=np.float32)
    # Expected internal color buffer
    color1_expected = np.array([color1, color1, color1, color1],
                               dtype=np.float32)

    with TestingCanvas() as c:
        # Check set_data is working correctly within visual constructor
        region = visuals.LinearRegion(pos=pos1, color=color1, parent=c.scene)
        assert np.all(region._color == color1_expected)
        assert np.all(region.color == color1)

        # Check set_data is working as expected when passing a list as
        # color argument
        region.set_data(color=list(color1))
        assert np.all(region._color == color1_expected)
        assert np.all(region.color == color1)

        # Check set_data is working as expected when passing a tuple as
        # color argument
        region.set_data(color=tuple(color1))
        assert np.all(region._color == color1_expected)
        assert np.all(region.color == color1)

        # Test with different dtypes that must be converted to float32
        region.set_data(color=color1.astype(np.float64))
        assert np.all(region._color == color1_expected)
        assert np.all(region.color == color1)

        assert_image_approved(c.render(), 'visuals/linear_region1.png')

        # Check a ValueError is raised when the length of color argument
        # is not 4.
        assert_raises(ValueError, region.set_data, color=[1.0, 0.5, 0.5])

        # Check a ValueError is raised when too many colors are provided
        assert_raises(ValueError, region.set_data,
                      color=[color1, color1, color1])
Esempio n. 45
0
def test_fs():
    """Test fullscreen support"""
    a = use_app()
    if not a.backend_module.capability['fullscreen']:
        return
    assert_raises(TypeError, Canvas, fullscreen='foo')
    if (a.backend_name.lower() == 'glfw' or
            (a.backend_name.lower() == 'sdl2' and sys.platform == 'darwin')):
        raise SkipTest('Backend takes over screen')
    with use_log_level('warning', record=True, print_msg=False) as l:
        with Canvas(fullscreen=False) as c:
            assert_equal(c.fullscreen, False)
            c.fullscreen = True
            assert_equal(c.fullscreen, True)
    assert_equal(len(l), 0)
    with use_log_level('warning', record=True, print_msg=False):
        # some backends print a warning b/c fullscreen can't be specified
        with Canvas(fullscreen=0) as c:
            assert_equal(c.fullscreen, True)
Esempio n. 46
0
def test_fs():
    """Test fullscreen support"""
    a = use_app()
    if not a.backend_module.capability['fullscreen']:
        return
    assert_raises(TypeError, Canvas, fullscreen='foo')
    if (a.backend_name.lower() == 'glfw' or
            (a.backend_name.lower() == 'sdl2' and sys.platform == 'darwin')):
        raise SkipTest('Backend takes over screen')
    with use_log_level('warning', record=True, print_msg=False) as emit_list:
        with Canvas(fullscreen=False) as c:
            assert_equal(c.fullscreen, False)
            c.fullscreen = True
            assert_equal(c.fullscreen, True)
    assert_equal(len(emit_list), 0)
    with use_log_level('warning', record=True, print_msg=False):
        # some backends print a warning b/c fullscreen can't be specified
        with Canvas(fullscreen=0) as c:
            assert_equal(c.fullscreen, True)
Esempio n. 47
0
def test_renderbuffer():
    
    # Set with no args
    assert_raises(ValueError, RenderBuffer)
    
    # Set shape only
    R = RenderBuffer((10, 20))
    assert R.shape == (10, 20)
    assert R.format is None
    
    # Set both shape and format
    R = RenderBuffer((10, 20), 'color')
    assert R.shape == (10, 20)
    assert R.format == 'color'
    #
    glir_cmds = R._glir.clear()
    assert len(glir_cmds) == 2
    assert glir_cmds[0][0] == 'CREATE'
    assert glir_cmds[1][0] == 'SIZE'
    
    # Orther formats
    assert RenderBuffer((10, 20), 'depth').format == 'depth'
    assert RenderBuffer((10, 20), 'stencil').format == 'stencil'
    
    # Test reset size and format
    R.resize((9, 9), 'depth')
    assert R.shape == (9, 9)
    assert R.format == 'depth'
    R.resize((8, 8), 'stencil')
    assert R.shape == (8, 8)
    assert R.format == 'stencil'
    
    # Wrong formats
    assert_raises(ValueError, R.resize, (9, 9), 'no_format')
    assert_raises(ValueError, R.resize, (9, 9), [])
    
    # Resizable
    R = RenderBuffer((10, 20), 'color', False)
    assert_raises(RuntimeError, R.resize, (9, 9), 'color')
    
    # Attaching sets the format
    F = FrameBuffer()
    #
    R = RenderBuffer((9, 9))
    F.color_buffer = R
    assert F.color_buffer is R
    assert R.format == 'color'
    #
    F.depth_buffer = RenderBuffer((9, 9))
    assert F.depth_buffer.format == 'depth'
    #
    F.stencil_buffer = RenderBuffer((9, 9))
    assert F.stencil_buffer.format == 'stencil'
Esempio n. 48
0
def test_renderbuffer():

    # Set with no args
    assert_raises(ValueError, RenderBuffer)

    # Set shape only
    R = RenderBuffer((10, 20))
    assert R.shape == (10, 20)
    assert R.format is None

    # Set both shape and format
    R = RenderBuffer((10, 20), 'color')
    assert R.shape == (10, 20)
    assert R.format is 'color'
    #
    glir_cmds = R._glir.clear()
    assert len(glir_cmds) == 2
    assert glir_cmds[0][0] == 'CREATE'
    assert glir_cmds[1][0] == 'SIZE'

    # Orther formats
    assert RenderBuffer((10, 20), 'depth').format == 'depth'
    assert RenderBuffer((10, 20), 'stencil').format == 'stencil'

    # Test reset size and format
    R.resize((9, 9), 'depth')
    assert R.shape == (9, 9)
    assert R.format == 'depth'
    R.resize((8, 8), 'stencil')
    assert R.shape == (8, 8)
    assert R.format == 'stencil'

    # Wrong formats
    assert_raises(ValueError, R.resize, (9, 9), 'no_format')
    assert_raises(ValueError, R.resize, (9, 9), [])

    # Resizable
    R = RenderBuffer((10, 20), 'color', False)
    assert_raises(RuntimeError, R.resize, (9, 9), 'color')

    # Attaching sets the format
    F = FrameBuffer()
    #
    R = RenderBuffer((9, 9))
    F.color_buffer = R
    assert F.color_buffer is R
    assert R.format == 'color'
    #
    F.depth_buffer = RenderBuffer((9, 9))
    assert F.depth_buffer.format == 'depth'
    #
    F.stencil_buffer = RenderBuffer((9, 9))
    assert F.stencil_buffer.format == 'stencil'
Esempio n. 49
0
def test_arrow_attributes():
    """Tests if the ArrowVisual performs the required checks for attributes."""
    with TestingCanvas() as c:
        arrow = visuals.Arrow(pos=vertices,
                              arrow_type="stealth",
                              arrows=arrows,
                              arrow_size=10,
                              color='red',
                              connect="segments",
                              parent=c.scene)

        def size_test():
            arrow.arrow_size = 0.0

        def type_test():
            arrow.arrow_type = "random_non_existent"

        assert_raises(ValueError, size_test)

        assert_raises(ValueError, type_test)
Esempio n. 50
0
def test_arrow_attributes():
    """Tests if the ArrowVisual performs the required checks for attributes."""
    with TestingCanvas() as c:
        arrow = visuals.Arrow(pos=vertices, arrow_type="stealth",
                              arrows=arrows, arrow_size=10, color='red',
                              connect="segments", parent=c.scene)

        def size_test():
            arrow.arrow_size = 0.0

        def type_test():
            arrow.arrow_type = "random_non_existent"

        assert_raises(
            ValueError, size_test
        )

        assert_raises(
            ValueError, type_test
        )
Esempio n. 51
0
def test_wavefront_non_triangular():
    '''Test wavefront writing with non-triangular faces'''
    vertices = np.array([[0.5, 1.375, 0.], [0.5, 0.625, 0.], [3.25, 1., 0.],
                         [1., 0.375, 0.], [2., 0.375, 0.], [1.5, 0.625, 0.],
                         [1.5, 1.375, 0.], [1., 1.625, 0.], [2., 1.625, 0.]])

    faces = np.array([[1, 0, 7, 6, 5, 3], [4, 5, 6, 8, 2]])
    fname_out = op.join(temp_dir, 'temp.obj')
    write_mesh(fname_out,
               vertices=vertices,
               faces=faces,
               normals=None,
               texcoords=None,
               overwrite=True,
               reshape_faces=False)
    assert_raises(RuntimeError, read_mesh, fname_out)
    with open(fname_out, 'r+') as out_file:
        lines = out_file.readlines()
    assert lines[-1].startswith('f 5 6 7 9 3')
    assert lines[-2].startswith('f 2 1 8 7 6 4')
Esempio n. 52
0
def _test_texture_formats(Texture, baseshape, formats):

    # valid channel count and format combinations
    for channels in range(1, 5):
        for format in [f for n, f in formats if n == channels]:
            shape = baseshape + (channels,)
            T = Texture(shape=shape, format=format)
            assert 'Texture' in repr(T)
            assert T._shape == shape
            data = np.zeros(shape, dtype=np.uint8)
            T = Texture(data=data, format=format)
            assert 'Texture' in repr(T)
            assert T._shape == shape

    # invalid channel count and format combinations
    for channels in range(1, 5):
        for format in [f for n, f in formats + [(5, 'junk')] if n != channels]:
            shape = baseshape + (channels,)
            assert_raises(ValueError, Texture, shape=shape, format=format)
            data = np.zeros(shape, dtype=np.uint8)
            assert_raises(ValueError, Texture, data=data, format=format)
Esempio n. 53
0
def _test_texture_formats(Texture, baseshape, formats):

    # valid channel count and format combinations
    for channels in range(1, 5):
        for format in [f for n, f in formats if n == channels]:
            shape = baseshape + (channels, )
            T = Texture(shape=shape, format=format)
            assert 'Texture' in repr(T)
            assert T._shape == shape
            data = np.zeros(shape, dtype=np.uint8)
            T = Texture(data=data, format=format)
            assert 'Texture' in repr(T)
            assert T._shape == shape

    # invalid channel count and format combinations
    for channels in range(1, 5):
        for format in [f for n, f in formats + [(5, 'junk')] if n != channels]:
            shape = baseshape + (channels, )
            assert_raises(ValueError, Texture, shape=shape, format=format)
            data = np.zeros(shape, dtype=np.uint8)
            assert_raises(ValueError, Texture, data=data, format=format)
Esempio n. 54
0
def test_set_data():
    """Test InfiniteLineVisual"""

    pos = 5.0
    color = [1.0, 1.0, 0.5, 0.5]
    expected_color = np.array(color, dtype=np.float32)

    for is_vertical, reference_image in [(True, 'infinite_line.png'),
                                         (False, 'infinite_line_h.png')]:

        with TestingCanvas() as c:
            # Check set_data is working correctly within visual constructor
            region = visuals.InfiniteLine(pos=pos,
                                          color=color,
                                          vertical=is_vertical,
                                          parent=c.scene)
            assert region.pos == pos
            assert np.all(region.color == expected_color)
            assert region.is_vertical == is_vertical

            # Check tuple color argument is accepted
            region.set_data(color=tuple(color))
            assert np.all(region.color == expected_color)

            assert_image_approved(c.render(), 'visuals/%s' % reference_image)

            # Check only numbers are accepted
            assert_raises(TypeError, region.set_data, pos=[[1, 2], [3, 4]])

            # Check color argument can be only a 4 length 1D array
            assert_raises(ValueError, region.set_data, color=[[1, 2], [3, 4]])
            assert_raises(ValueError, region.set_data, color=[1, 2])
Esempio n. 55
0
def test_use_framebuffer():
    """Test drawing to a framebuffer"""
    shape = (100, 300)  # for some reason Windows wants a tall window...
    data = np.random.rand(*shape).astype(np.float32)
    use_shape = shape + (3,)
    with Canvas(size=shape[::-1]) as c:
        orig_tex = Texture2D(data)
        fbo_tex = Texture2D(use_shape, format='rgb')
        rbo = RenderBuffer(shape, 'color')
        fbo = FrameBuffer(color=fbo_tex)
        c.context.glir.set_verbose(True)
        assert_equal(c.size, shape[::-1])
        set_viewport((0, 0) + c.size)
        with fbo:
            draw_texture(orig_tex)
        draw_texture(fbo_tex)
        out_tex = _screenshot()[::-1, :, 0].astype(np.float32)
        assert_equal(out_tex.shape, c.size[::-1])
        assert_raises(TypeError, FrameBuffer.color_buffer.fset, fbo, 1.)
        assert_raises(TypeError, FrameBuffer.depth_buffer.fset, fbo, 1.)
        assert_raises(TypeError, FrameBuffer.stencil_buffer.fset, fbo, 1.)
        fbo.color_buffer = rbo
        fbo.depth_buffer = RenderBuffer(shape)
        fbo.stencil_buffer = None
        print((fbo.color_buffer, fbo.depth_buffer, fbo.stencil_buffer))
        clear(color='black')
        with fbo:
            clear(color='black')
            draw_texture(orig_tex)
            out_rbo = _screenshot()[:, :, 0].astype(np.float32)
    assert_allclose(data * 255., out_tex, atol=1)
    assert_allclose(data * 255., out_rbo, atol=1)
Esempio n. 56
0
def test_use_framebuffer():
    """Test drawing to a framebuffer"""
    shape = (100, 300)  # for some reason Windows wants a tall window...
    data = np.random.rand(*shape).astype(np.float32)
    use_shape = shape + (3, )
    with Canvas(size=shape[::-1]) as c:
        orig_tex = Texture2D(data)
        fbo_tex = Texture2D(use_shape, format='rgb')
        rbo = RenderBuffer(shape, 'color')
        fbo = FrameBuffer(color=fbo_tex)
        c.context.glir.set_verbose(True)
        assert_equal(c.size, shape[::-1])
        set_viewport((0, 0) + c.size)
        with fbo:
            draw_texture(orig_tex)
        draw_texture(fbo_tex)
        out_tex = _screenshot()[::-1, :, 0].astype(np.float32)
        assert_equal(out_tex.shape, c.size[::-1])
        assert_raises(TypeError, FrameBuffer.color_buffer.fset, fbo, 1.)
        assert_raises(TypeError, FrameBuffer.depth_buffer.fset, fbo, 1.)
        assert_raises(TypeError, FrameBuffer.stencil_buffer.fset, fbo, 1.)
        fbo.color_buffer = rbo
        fbo.depth_buffer = RenderBuffer(shape)
        fbo.stencil_buffer = None
        print((fbo.color_buffer, fbo.depth_buffer, fbo.stencil_buffer))
        clear(color='black')
        with fbo:
            clear(color='black')
            draw_texture(orig_tex)
            out_rbo = _screenshot()[:, :, 0].astype(np.float32)
    assert_allclose(data * 255., out_tex, atol=1)
    assert_allclose(data * 255., out_rbo, atol=1)
Esempio n. 57
0
def test_set_data():
    """Test InfiniteLineVisual"""
    pos = 5.0
    color = [1.0, 1.0, 0.5, 0.5]
    expected_color = np.array(color, dtype=np.float32)

    for is_vertical, reference_image in [(True, 'infinite_line.png'),
                                         (False, 'infinite_line_h.png')]:

        with TestingCanvas() as c:
            # Check set_data is working correctly within visual constructor
            region = visuals.InfiniteLine(pos=pos,
                                          color=color,
                                          vertical=is_vertical,
                                          parent=c.scene)
            assert region.pos == pos
            assert np.all(region.color == expected_color)
            assert region.is_vertical == is_vertical

            # Check tuple color argument is accepted
            region.set_data(color=tuple(color))
            assert np.all(region.color == expected_color)

            assert_image_approved(c.render(), 'visuals/%s' % reference_image)

            # Check only numbers are accepted
            assert_raises(TypeError, region.set_data, pos=[[1, 2], [3, 4]])

            # Check color argument can be only a 4 length 1D array
            assert_raises(ValueError, region.set_data, color=[[1, 2], [3, 4]])
            assert_raises(ValueError, region.set_data, color=[1, 2])