Beispiel #1
0
def test_import_vispy_scene():
    """ Importing vispy.gloo.gl.desktop should not import PyOpenGL. """
    modnames = loaded_vispy_modules('vispy.scene', 2)
    more_modules = ['vispy.app', 'vispy.gloo', 'vispy.glsl', 'vispy.scene', 
                    'vispy.color', 
                    'vispy.io', 'vispy.geometry', 'vispy.visuals']
    assert_equal(modnames, set(_min_modules + more_modules))
Beispiel #2
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"]
Beispiel #3
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'))
Beispiel #4
0
def test_FunctionChain():
    
    f1 = Function("void f1(){}")
    f2 = Function("void f2(){}")
    f3 = Function("float f3(vec3 x){}")
    f4 = Function("vec3 f4(vec3 y){}")
    f5 = Function("vec3 f5(vec4 z){}")
    
    ch = FunctionChain('chain', [f1, f2])
    assert ch.name == 'chain'
    assert ch.args == []
    assert ch.rtype == 'void'
    
    assert_in('f1', ch.compile())
    assert_in('f2', ch.compile())
    
    ch.remove(f2)
    assert_not_in('f2', ch.compile())

    ch.append(f2)
    assert_in('f2', ch.compile())

    ch = FunctionChain(funcs=[f5, f4, f3])
    assert_equal('float', ch.rtype)
    assert_equal([('vec4', 'z')], ch.args)
    assert_in('f3', ch.compile())
    assert_in('f4', ch.compile())
    assert_in('f5', ch.compile())
    assert_in(f3, ch.dependencies())
    assert_in(f4, ch.dependencies())
    assert_in(f5, ch.dependencies())
Beispiel #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
Beispiel #6
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())
Beispiel #7
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)
Beispiel #8
0
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')
Beispiel #9
0
def test_serialize_command():
    command = ('CREATE', 4, 'VertexBuffer')
    command_serialized = _serialize_command(command)
    assert_equal(command_serialized, list(command))

    command = ('UNIFORM', 4, 'u_scale', 'vec3', (1, 2, 3))
    commands_serialized_expected = ['UNIFORM', 4, 'u_scale', 'vec3', [1, 2, 3]]
    command_serialized = _serialize_command(command)
    assert_equal(command_serialized, commands_serialized_expected)
Beispiel #10
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.)
Beispiel #11
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
Beispiel #12
0
def test_close_keys():
    """Test close keys"""
    c = Canvas(keys='interactive')
    x = list()

    @c.events.close.connect
    def closer(event):
        x.append('done')
    c.events.key_press(key=keys.ESCAPE, text='', modifiers=[])
    assert_equal(len(x), 1)  # ensure the close event was sent
    c.app.process_events()
Beispiel #13
0
def test_create_glir_message_binary():
    arr = np.zeros((3, 2)).astype(np.float32)
    arr2 = np.ones((4, 5)).astype(np.int16)

    commands = [('CREATE', 1, 'VertexBuffer'),
                ('UNIFORM', 2, 'u_scale', 'vec3', (1, 2, 3)),
                ('DATA', 3, 0, arr),
                ('UNIFORM', 4, 'u_pan', 'vec2', np.array([1, 2, 3])),
                ('DATA', 5, 20, arr2)]
    msg = create_glir_message(commands)
    assert_equal(msg['msg_type'], 'glir_commands')

    commands_serialized = msg['commands']
    assert_equal(commands_serialized,
                 [['CREATE', 1, 'VertexBuffer'],
                  ['UNIFORM', 2, 'u_scale', 'vec3', [1, 2, 3]],
                  ['DATA', 3, 0, {'buffer_index': 0,
                                  'buffer_shape': [3, 2],
                                  'buffer_dtype': 'float32'}],
                  ['UNIFORM', 4, 'u_pan', 'vec2', [1, 2, 3]],
                  ['DATA', 5, 20, {'buffer_index': 1,
                                   'buffer_shape': [4, 5],
                                   'buffer_dtype': 'int16'}]])

    buffers_serialized = msg['buffers']
    buf0 = buffers_serialized[0]
    assert_equal(buf0, b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')  # noqa

    buf1 = buffers_serialized[1]
    assert_equal(buf1, b'\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00\x01\x00')  # noqa
Beispiel #14
0
def test_import_vispy_scene():
    """ Importing vispy.gloo.gl.desktop should not import PyOpenGL. """
    modnames = loaded_vispy_modules("vispy.scene", 2)
    more_modules = [
        "vispy.app",
        "vispy.gloo",
        "vispy.glsl",
        "vispy.scene",
        "vispy.color",
        "vispy.io",
        "vispy.geometry",
        "vispy.visuals",
    ]
    assert_equal(modnames, set(_min_modules + more_modules))
Beispiel #15
0
def test_logging():
    """Test logging context manager"""
    ll = logger.level
    with use_log_level('warning', print_msg=False):
        assert_equal(logger.level, logging.WARN)
    assert_equal(logger.level, ll)
    with use_log_level('debug', print_msg=False):
        assert_equal(logger.level, logging.DEBUG)
    assert_equal(logger.level, ll)
Beispiel #16
0
def test_wavefront():
    """Test wavefront reader"""
    fname_mesh = load_data_file('orig/triceratops.obj.gz')
    fname_out = op.join(temp_dir, 'temp.obj')
    mesh1 = read_mesh(fname_mesh)
    assert_raises(IOError, read_mesh, 'foo.obj')
    assert_raises(ValueError, read_mesh, op.abspath(__file__))
    assert_raises(ValueError, write_mesh, fname_out, *mesh1, format='foo')
    write_mesh(fname_out, mesh1[0], mesh1[1], mesh1[2], mesh1[3])
    assert_raises(IOError, write_mesh, fname_out, *mesh1)
    write_mesh(fname_out, *mesh1, overwrite=True)
    mesh2 = read_mesh(fname_out)
    assert_equal(len(mesh1), len(mesh2))
    for m1, m2 in zip(mesh1, mesh2):
        if m1 is None:
            assert_equal(m2, None)
        else:
            assert_allclose(m1, m2, rtol=1e-5)
    # test our efficient normal calculation routine
    assert_allclose(mesh1[2], _slow_calculate_normals(mesh1[0], mesh1[1]),
                    rtol=1e-7, atol=1e-7)
Beispiel #17
0
def test_transforms():
    """Test basic transforms"""
    xfm = np.random.randn(4, 4).astype(np.float32)

    # Do a series of rotations that should end up into the same orientation
    # again, to ensure the order of computation is all correct
    # i.e. if rotated would return the transposed matrix this would not work
    # out (the translation part would be incorrect)
    new_xfm = xfm.dot(rotate(180, (1, 0, 0)).dot(rotate(-90, (0, 1, 0))))
    new_xfm = new_xfm.dot(rotate(90, (0, 0, 1)).dot(rotate(90, (0, 1, 0))))
    new_xfm = new_xfm.dot(rotate(90, (1, 0, 0)))
    assert_allclose(xfm, new_xfm)

    new_xfm = translate((1, -1, 1)).dot(translate((-1, 1, -1))).dot(xfm)
    assert_allclose(xfm, new_xfm)

    new_xfm = scale((1, 2, 3)).dot(scale((1, 1. / 2., 1. / 3.))).dot(xfm)
    assert_allclose(xfm, new_xfm)

    # These could be more complex...
    xfm = ortho(-1, 1, -1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))

    xfm = frustum(-1, 1, -1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))

    xfm = perspective(1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))
Beispiel #18
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'})
Beispiel #19
0
def test_transforms():
    """Test basic transforms"""
    xfm = np.random.randn(4, 4).astype(np.float32)

    for rot in [xrotate, yrotate, zrotate]:
        new_xfm = rot(rot(xfm, 90), -90)
        assert_allclose(xfm, new_xfm)

    new_xfm = rotate(rotate(xfm, 90, 1, 0, 0), 90, -1, 0, 0)
    assert_allclose(xfm, new_xfm)

    new_xfm = translate(translate(xfm, 1, -1), 1, -1, 1)
    assert_allclose(xfm, new_xfm)

    new_xfm = scale(scale(xfm, 1, 2, 3), 1, 1. / 2., 1. / 3.)
    assert_allclose(xfm, new_xfm)

    # These could be more complex...
    xfm = ortho(-1, 1, -1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))

    xfm = frustum(-1, 1, -1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))

    xfm = perspective(1, 1, -1, 1)
    assert_equal(xfm.shape, (4, 4))
Beispiel #20
0
def test_color_conversion():
    """Test color conversions"""
    # HSV
    # test known values
    test = ColorArray()
    for key in hsv_dict:
        c = ColorArray(key)
        test.hsv = hsv_dict[key]
        assert_allclose(c.RGB, test.RGB, atol=1)
    test.value = 0
    assert_equal(test.value, 0)
    assert_equal(test, ColorArray('black'))
    c = ColorArray('black')
    assert_array_equal(c.hsv.ravel(), (0, 0, 0))
    rng = np.random.RandomState(0)
    for _ in range(50):
        hsv = rng.rand(3)
        hsv[0] *= 360
        hsv[1] = hsv[1] * 0.99 + 0.01  # avoid ugly boundary effects
        hsv[2] = hsv[2] * 0.99 + 0.01
        c.hsv = hsv
        assert_allclose(c.hsv.ravel(), hsv, rtol=1e-4, atol=1e-4)

    # Lab
    test = ColorArray()
    for key in lab_dict:
        c = ColorArray(key)
        test.lab = lab_dict[key]
        assert_allclose(c.rgba, test.rgba, atol=1e-4, rtol=1e-4)
        assert_allclose(test.lab.ravel(), lab_dict[key], atol=1e-4, rtol=1e-4)
    for _ in range(50):
        # boundaries can have ugly rounding errors in some parameters
        rgb = (rng.rand(3)[np.newaxis, :] * 0.9 + 0.05)
        c.rgb = rgb
        lab = c.lab
        c.lab = lab
        assert_allclose(c.lab, lab, atol=1e-4, rtol=1e-4)
        assert_allclose(c.rgb, rgb, atol=1e-4, rtol=1e-4)
Beispiel #21
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()
Beispiel #22
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,))
Beispiel #23
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.)
Beispiel #24
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)
Beispiel #25
0
def test_debug_logging():
    """Test advanced debugging logging"""
    with use_log_level('debug', 'Selected', True, False) as l:
        logger.debug('Selected foo')
    assert_equal(len(l), 1)
    assert_in('test_logging', l[0])  # can't really parse this location

    with use_log_level('debug', record=True, print_msg=False) as l:
        logger.debug('foo')
    assert_equal(len(l), 1)
    assert_in('test_logging', l[0])

    with use_log_level('debug', 'foo', True, False) as l:
        logger.debug('bar')
    assert_equal(len(l), 0)

    with use_log_level('info', record=True, print_msg=False) as l:
        logger.debug('foo')
        logger.info('bar')
    assert_equal(len(l), 1)
    assert_not_in('unknown', l[0])
Beispiel #26
0
def _test_fbo():
    
    w, h = 120, 130
    
    # Create frame buffer
    hframebuf = gl.glCreateFramebuffer()
    gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, hframebuf)
    
    #Create render buffer (for depth)
    hrenderbuf = gl.glCreateRenderbuffer()
    gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, hrenderbuf)
    gl.glRenderbufferStorage(gl.GL_RENDERBUFFER, gl.GL_DEPTH_COMPONENT16, w, h)
    gl.glFramebufferRenderbuffer(gl.GL_FRAMEBUFFER, gl.GL_DEPTH_ATTACHMENT,
                                 gl.GL_RENDERBUFFER, hrenderbuf)
    
    # Create texture (for color)
    htex = gl.glCreateTexture()
    gl.glBindTexture(gl.GL_TEXTURE_2D, htex)
    gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, gl.GL_RGB, 
                    gl.GL_UNSIGNED_BYTE, (h, w))
    gl.glFramebufferTexture2D(gl.GL_FRAMEBUFFER, gl.GL_COLOR_ATTACHMENT0,
                              gl.GL_TEXTURE_2D, htex, 0)
    
    # Check framebuffer status
    status = gl.glCheckFramebufferStatus(gl.GL_FRAMEBUFFER)
    assert_equal(status, gl.GL_FRAMEBUFFER_COMPLETE)
    
    # Tests renderbuffer params
    name = gl.glGetFramebufferAttachmentParameter(
        gl.GL_FRAMEBUFFER, gl.GL_DEPTH_ATTACHMENT, 
        gl.GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME)
    assert_equal(name, hrenderbuf)
    #
    width = gl.glGetRenderbufferParameter(gl.GL_RENDERBUFFER,
                                          gl.GL_RENDERBUFFER_WIDTH)
    assert_equal(width, w)
    
    # Touch copy tex functions
    gl.glBindTexture(gl.GL_TEXTURE_2D, htex)
    gl.glCopyTexSubImage2D(gl.GL_TEXTURE_2D, 0, 5, 5, 5, 5, 20, 20)
    gl.glCopyTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_RGB, 0, 0, 30, 30,  0)
    
    gl.check_error()
    
    # Clean up
    gl.glDeleteTexture(htex)
    gl.glDeleteRenderbuffer(hrenderbuf)
    gl.glDeleteFramebuffer(hframebuf)
    
    gl.check_error()
Beispiel #27
0
def test_color():
    """Basic tests for Color class"""
    x = Color('white')
    assert_array_equal(x.rgba, [1.] * 4)
    assert_array_equal(x.rgb, [1.] * 3)
    assert_array_equal(x.RGBA, [255] * 4)
    assert_array_equal(x.RGB, [255] * 3)
    assert_equal(x.value, 1.)
    assert_equal(x.alpha, 1.)
    x.rgb = [0, 0, 1]
    assert_array_equal(x.hsv, [240, 1, 1])
    assert_equal(x.hex, '#0000ff')
    x.hex = '#00000000'
    assert_array_equal(x.rgba, [0.]*4)
Beispiel #28
0
def _check_result(assert_result=True):
    """ Test the color of each quadrant by picking the center pixel 
    of each quadrant and comparing it with the reference color.
    """
    
    # Take screenshot
    x, y, w, h = gl.glGetParameter(gl.GL_VIEWPORT)
    data = gl.glReadPixels(x, y, w, h, gl.GL_RGB, gl.GL_UNSIGNED_BYTE)
    im = np.frombuffer(data, np.uint8)
    im.shape = h, w, 3
    
    # Get center pixel from each quadrant
    pix1 = tuple(im[int(1*h/4), int(1*w/4)])
    pix2 = tuple(im[int(3*h/4), int(1*w/4)])
    pix3 = tuple(im[int(3*h/4), int(3*w/4)])
    pix4 = tuple(im[int(1*h/4), int(3*w/4)])
    #print(pix1, pix2, pix3, pix4)
   
    if assert_result:
        # Test their value
        assert_equal(pix1, (0, 0, 0))
        assert_equal(pix2, (255, 0, 0))
        assert_equal(pix3, (0, 255, 0))
        assert_equal(pix4, (0, 0, 255))
Beispiel #29
0
def _test_setting_parameters():
    # Set some parameters and get result
    clr = 1.0, 0.1, 0.2, 0.7
    gl.glClearColor(*clr)
    assert_almost_equal(gl.glGetParameter(gl.GL_COLOR_CLEAR_VALUE), clr)
    #
    gl.glCullFace(gl.GL_FRONT)
    assert_equal(gl.glGetParameter(gl.GL_CULL_FACE_MODE), gl.GL_FRONT)
    gl.glCullFace(gl.GL_BACK)
    assert_equal(gl.glGetParameter(gl.GL_CULL_FACE_MODE), gl.GL_BACK)
    #
    gl.glDepthFunc(gl.GL_NOTEQUAL)
    assert_equal(gl.glGetParameter(gl.GL_DEPTH_FUNC), gl.GL_NOTEQUAL)
    #
    val = 0.2, 0.3
    gl.glDepthRange(*val)
    assert_almost_equal(gl.glGetParameter(gl.GL_DEPTH_RANGE), val)
    
    gl.check_error()
Beispiel #30
0
def _test_enabling_disabling():
    # Enabling/disabling
    gl.glEnable(gl.GL_DEPTH_TEST)
    assert_equal(gl.glIsEnabled(gl.GL_DEPTH_TEST), True)
    assert_equal(gl.glGetParameter(gl.GL_DEPTH_TEST), 1)
    gl.glDisable(gl.GL_DEPTH_TEST)
    assert_equal(gl.glIsEnabled(gl.GL_DEPTH_TEST), False)
    assert_equal(gl.glGetParameter(gl.GL_DEPTH_TEST), 0)
    #
    gl.glEnable(gl.GL_BLEND)
    assert_equal(gl.glIsEnabled(gl.GL_BLEND), True)
    assert_equal(gl.glGetParameter(gl.GL_BLEND), 1)
    gl.glDisable(gl.GL_BLEND)
    assert_equal(gl.glIsEnabled(gl.GL_BLEND), False)
    assert_equal(gl.glGetParameter(gl.GL_BLEND), 0)

    gl.check_error()
Beispiel #31
0
def test_import_vispy_util():
    """Importing vispy.util should not pull in other vispy submodules."""
    modnames = loaded_vispy_modules('vispy.util', 2)
    assert_equal(modnames, set(_min_modules))
Beispiel #32
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'}, ('120', ''), None),
                 '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')
Beispiel #33
0
def test_event_connect_order():
    """Test event connection order"""
    def a():
        return

    def b():
        return

    def c():
        return

    def d():
        return

    def e():
        return

    def f():
        return

    em = EventEmitter(type='test_event')
    assert_raises(ValueError, em.connect, c, before=['c', 'foo'])
    assert_raises(ValueError, em.connect, c, position='foo')
    assert_raises(TypeError, em.connect, c, ref=dict())
    em.connect(c, ref=True)
    assert_equal((c,), tuple(em.callbacks))
    em.connect(c)
    assert_equal((c,), tuple(em.callbacks))
    em.connect(d, ref=True, position='last')
    assert_equal((c, d), tuple(em.callbacks))
    em.connect(b, ref=True)  # position='first'
    assert_equal((b, c, d), tuple(em.callbacks))
    assert_raises(RuntimeError, em.connect, a, before='c', after='d')  # can't
    em.connect(a, ref=True, before=['c', 'd'])  # first possible pos == 0
    assert_equal((a, b, c, d), tuple(em.callbacks))
    em.connect(f, ref=True, after=['c', 'd'])
    assert_equal((a, b, c, d, f), tuple(em.callbacks))
    em.connect(e, ref=True, after='d', before='f')
    assert_equal(('a', 'b', 'c', 'd', 'e', 'f'), tuple(em.callback_refs))
    em.disconnect(e)
    em.connect(e, ref=True, after='a', before='f', position='last')
    assert_equal(('a', 'b', 'c', 'd', 'e', 'f'), tuple(em.callback_refs))
    em.disconnect(e)
    em.connect(e, ref='e', after='d', before='f', position='last')
    assert_equal(('a', 'b', 'c', 'd', 'e', 'f'), tuple(em.callback_refs))
    em.disconnect(e)
    em.connect(e, after='d', before='f', position='first')  # no name
    assert_equal(('a', 'b', 'c', 'd', None, 'f'), tuple(em.callback_refs))
    em.disconnect(e)
    assert_raises(ValueError, em.connect, e, ref='d')  # duplicate name
    em.connect(e, ref=True, after=[], before='f', position='last')
    assert_equal(('a', 'b', 'c', 'd', 'e', 'f'), tuple(em.callback_refs))
    assert_equal((a, b, c, d, e, f), tuple(em.callbacks))

    old_e = e

    def e():
        return

    assert_raises(ValueError, em.connect, e, ref=True)  # duplicate name
    em.connect(e)
    assert_equal((None, 'a', 'b', 'c', 'd', 'e', 'f'),
                 tuple(em.callback_refs))
    assert_equal((e, a, b, c, d, old_e, f), tuple(em.callbacks))
Beispiel #34
0
def test_TextExpression():
    exp = TextExpression('foo bar')
    assert_equal('foo bar', exp.expression(None))
    assert_equal(None, exp.definition(None, ('120', '')))
    assert_raises(TypeError, TextExpression, 4)
Beispiel #35
0
def test_function_basics():

    # Test init fail
    assert_raises(TypeError, Function)  # no args
    assert_raises(ValueError, Function, 3)  # need string

    # Test init success 1
    fun = Function('void main(){}')
    assert_equal(fun.name, 'main')
    assert len(fun.template_vars) == 0

    # Test init success with template vars
    fun = Function('void main(){$foo; $bar;}')
    assert_equal(fun.name, 'main')
    assert len(fun.template_vars) == 2
    assert_in('foo', fun.template_vars)
    assert_in('bar', fun.template_vars)

    # Test setting verbatim expressions
    assert_raises(KeyError, fun.__setitem__, 'bla', '33')  # no such template
    fun['foo'] = '33'
    fun['bar'] = 'bla bla'
    assert_is(type(fun['foo']), TextExpression)
    assert_equal(fun['foo'].expression(None), '33')
    assert_is(type(fun['bar']), TextExpression)
    assert_equal(fun['bar'].expression(None), 'bla bla')

    # Test setting call expressions
    fun = Function('void main(){\n$foo;\n$bar;\n$spam(XX);\n$eggs(YY);\n}')
    trans = Function('float transform_scale(float x) {return x+1.0;}')
    assert_raises(TypeError, trans)  # requires 1 arg 
    assert_raises(TypeError, trans, '1', '2')
    fun['foo'] = trans('2')
    fun['bar'] = trans('3')
    fun['spam'] = trans
    fun['eggs'] = trans
    #
    for name in ['foo', 'bar']:
        assert_is(type(fun[name]), FunctionCall)
        assert_equal(fun[name].function, trans)
        assert_in(trans, fun.dependencies())
    for name in ['spam', 'eggs']:
        assert_equal(fun[name], trans)

    #
    text = fun.compile()
    assert_in('\ntransform_scale(2);\n', text)
    assert_in('\ntransform_scale(3);\n', text)
    assert_in('\ntransform_scale(XX);\n', text)
    assert_in('\ntransform_scale(YY);\n', text)

    # test pre/post assignments
    fun = Function('void main() {some stuff;}')
    fun['pre'] = '__pre__'
    fun['post'] = '__post__'
    text = fun.compile()
    assert text == 'void main() {\n    __pre__\nsome stuff;\n    __post__\n}\n'

    # Test variable expressions
    fun = Function('void main(){$foo; $bar;}')
    fun['foo'] = Variable('uniform float bla')
    fun['bar'] = Variable('attribute float bla')
    assert_is(type(fun['foo']), Variable)
    assert_is(type(fun['bar']), Variable)
    assert_in(fun['foo'], fun.dependencies())
    assert_in(fun['bar'], fun.dependencies())

    # Test special variables
    fun = Function('void main(){$foo; $bar;}')
    variable = Variable('attribute vec3 v_pos')
    varying = Variable('varying vec3 color')
    # These do not work due to index
    assert_raises(TypeError, fun.__setitem__, 3, 3)  # not a string
    assert_raises(KeyError, fun.__setitem__, 'xxx', 3)  # unknown template var
    assert_raises(TypeError, fun.__setitem__, variable, 3)  # only varyings
    # These work
    fun['gl_PointSize'] = '3.0'
    fun[varying] = variable
    # And getting works
    assert_equal(fun['gl_PointSize'].text, '3.0')
    assert_equal(fun[varying], variable)
Beispiel #36
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
Beispiel #37
0
def test_event_connect_order():
    """Test event connection order"""
    def a():
        return

    def b():
        return

    def c():
        return

    def d():
        return

    def e():
        return

    def f():
        return

    em = EventEmitter(type='test_event')
    assert_raises(ValueError, em.connect, c, before=['c', 'foo'])
    assert_raises(ValueError, em.connect, c, position='foo')
    assert_raises(TypeError, em.connect, c, ref=dict())
    em.connect(c, ref=True)
    assert_equal((c, ), tuple(em.callbacks))
    em.connect(c)
    assert_equal((c, ), tuple(em.callbacks))
    em.connect(d, ref=True, position='last')
    assert_equal((c, d), tuple(em.callbacks))
    em.connect(b, ref=True)  # position='first'
    assert_equal((b, c, d), tuple(em.callbacks))
    assert_raises(RuntimeError, em.connect, a, before='c', after='d')  # can't
    em.connect(a, ref=True, before=['c', 'd'])  # first possible pos == 0
    assert_equal((a, b, c, d), tuple(em.callbacks))
    em.connect(f, ref=True, after=['c', 'd'])
    assert_equal((a, b, c, d, f), tuple(em.callbacks))
    em.connect(e, ref=True, after='d', before='f')
    assert_equal(('a', 'b', 'c', 'd', 'e', 'f'), tuple(em.callback_refs))
    em.disconnect(e)
    em.connect(e, ref=True, after='a', before='f', position='last')
    assert_equal(('a', 'b', 'c', 'd', 'e', 'f'), tuple(em.callback_refs))
    em.disconnect(e)
    em.connect(e, ref='e', after='d', before='f', position='last')
    assert_equal(('a', 'b', 'c', 'd', 'e', 'f'), tuple(em.callback_refs))
    em.disconnect(e)
    em.connect(e, after='d', before='f', position='first')  # no name
    assert_equal(('a', 'b', 'c', 'd', None, 'f'), tuple(em.callback_refs))
    em.disconnect(e)
    assert_raises(ValueError, em.connect, e, ref='d')  # duplicate name
    em.connect(e, ref=True, after=[], before='f', position='last')
    assert_equal(('a', 'b', 'c', 'd', 'e', 'f'), tuple(em.callback_refs))
    assert_equal((a, b, c, d, e, f), tuple(em.callbacks))

    old_e = e

    def e():
        return

    assert_raises(ValueError, em.connect, e, ref=True)  # duplicate name
    em.connect(e)
    assert_equal((None, 'a', 'b', 'c', 'd', 'e', 'f'), tuple(em.callback_refs))
    assert_equal((e, a, b, c, d, old_e, f), tuple(em.callbacks))
Beispiel #38
0
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 'pyqt5'
    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 knownfail, 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.0, 0.0, 1.0);}"
        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
Beispiel #39
0
def test_import_nothing():
    """Not importing vispy should not import any vispy modules."""
    modnames = loaded_vispy_modules('os', 2)
    assert_equal(modnames, set())
Beispiel #40
0
def test_import_vispy_gloo():
    """Importing vispy.gloo should not pull in other vispy submodules."""
    modnames = loaded_vispy_modules('vispy.gloo', 2)
    assert_equal(
        modnames,
        set(_min_modules + ['vispy.gloo', 'vispy.glsl', 'vispy.color']))
Beispiel #41
0
def _test_object_creation_and_deletion():

    # Stuff that is originally glGenX
    
    # Note that if we test glIsTexture(x), we cannot assume x to be a
    # nonexisting texture; we might have created a texture in another
    # test and failed to clean it up.
    
    # Create/delete texture
    #assert_equal(gl.glIsTexture(12), False)
    handle = gl.glCreateTexture()
    gl.glBindTexture(gl.GL_TEXTURE_2D, handle)
    assert_equal(gl.glIsTexture(handle), True)
    gl.glDeleteTexture(handle)
    assert_equal(gl.glIsTexture(handle), False)

    # Create/delete buffer
    #assert_equal(gl.glIsBuffer(12), False)
    handle = gl.glCreateBuffer()
    gl.glBindBuffer(gl.GL_ARRAY_BUFFER, handle)
    assert_equal(gl.glIsBuffer(handle), True)
    gl.glDeleteBuffer(handle)
    assert_equal(gl.glIsBuffer(handle), False)

    # Create/delete framebuffer
    #assert_equal(gl.glIsFramebuffer(12), False)
    handle = gl.glCreateFramebuffer()
    gl.glBindFramebuffer(gl.GL_FRAMEBUFFER, handle)
    assert_equal(gl.glIsFramebuffer(handle), True)
    gl.glDeleteFramebuffer(handle)
    assert_equal(gl.glIsFramebuffer(handle), False)

    # Create/delete renderbuffer
    #assert_equal(gl.glIsRenderbuffer(12), False)
    handle = gl.glCreateRenderbuffer()
    gl.glBindRenderbuffer(gl.GL_RENDERBUFFER, handle)
    assert_equal(gl.glIsRenderbuffer(handle), True)
    gl.glDeleteRenderbuffer(handle)
    assert_equal(gl.glIsRenderbuffer(handle), False)

    # Stuff that is originally called glCreate

    # Create/delete program
    #assert_equal(gl.glIsProgram(12), False)
    handle = gl.glCreateProgram()
    assert_equal(gl.glIsProgram(handle), True)
    gl.glDeleteProgram(handle)
    assert_equal(gl.glIsProgram(handle), False)

    # Create/delete shader
    #assert_equal(gl.glIsShader(12), False)
    handle = gl.glCreateShader(gl.GL_VERTEX_SHADER)
    assert_equal(gl.glIsShader(handle), True)
    gl.glDeleteShader(handle)
    assert_equal(gl.glIsShader(handle), False)
    
    gl.check_error()
Beispiel #42
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())