예제 #1
0
def _test_multiple_canvases(backend):
    """Helper for testing multiple canvases from the same application"""
    n_check = 3
    a = Application(backend)
    with Canvas(app=a, size=_win_size, title=backend + ' same_0') as c0:
        with Canvas(app=a, size=_win_size, title=backend + ' same_1') as c1:
            ct = [0, 0]

            @c0.events.paint.connect
            def paint0(event):
                ct[0] += 1
                c0.update()

            @c1.events.paint.connect  # noqa, analysis:ignore
            def paint1(event):
                ct[1] += 1
                c1.update()

            c0.show()  # ensure visible
            c1.show()
            c0.update()  # force first paint
            c1.update()

            timeout = time() + 2.0
            while (ct[0] < n_check or ct[1] < n_check) and time() < timeout:
                a.process_events()
            print((ct, n_check))
            assert_true(n_check <= ct[0] <= n_check + 1)
            assert_true(n_check <= ct[1] <= n_check + 1)

            # check timer
            global timer_ran
            timer_ran = False

            def on_timer(_):
                global timer_ran
                timer_ran = True
            timeout = time() + 2.0
            Timer(0.1, app=a, connect=on_timer, iterations=1, start=True)
            while not timer_ran and time() < timeout:
                a.process_events()
            assert_true(timer_ran)
예제 #2
0
    def __init__(self, connect=None, start=True, app=None):
        self.events = EmitterGroup(source=self,
                                   start=Event,
                                   stop=Event,
                                   midiIn=Event)

        if app is None:
            self._app = use_app(call_reuse=False)
        elif isinstance(app, Application):
            self._app = app
        elif isinstance(app, string_types):
            self._app = Application(app)
        else:
            raise ValueError('Invalid value for app %r' % app)
        self._running = False
        if connect is not None:
            self.connect(connect)
        if start:
            self.start()
예제 #3
0
def test_rfb_canvas():

    app = Application("jupyter_rfb")
    canvas = MyCanvas(app=app)
    canvas_backend = canvas.native

    assert isinstance(canvas_backend, _jupyter_rfb.CanvasBackend)

    # Check that resize works
    assert "42" not in canvas_backend.css_width
    canvas.size = 42, 42
    assert canvas_backend.css_width == "42px"
    # Manually mimic what a browser would do, but round to 50
    canvas_backend.handle_event({"event_type": "resize", "width": 50, "height": 50, "pixel_ratio": 2.0})
    assert canvas.size == (50, 50)
    assert canvas.physical_size == (100, 100)

    # Mimic a draw
    frame = canvas_backend.get_frame()
    assert frame.shape[:2] == (100, 100)
    assert np.all(frame[:, :, 0] == 0)
    assert np.all(frame[:, :, 1] == 255)

    # Pretend that the user resized in the browser
    canvas_backend.handle_event({"event_type": "resize", "width": 60, "height": 60, "pixel_ratio": 1.0})
    assert canvas.size == (60, 60)
    assert canvas.physical_size == (60, 60)

    # Mimic another draw
    frame = canvas_backend.get_frame()
    assert frame.shape[:2] == (60, 60)
    assert np.all(frame[:, :, 0] == 0)
    assert np.all(frame[:, :, 1] == 255)

    # Test mouse event
    events = []
    canvas.events.mouse_press.connect(lambda e: events.append(e))
    canvas_backend.handle_event({"event_type": "pointer_down", "x": 11, "y": 12, "button": 1, "modifiers": []})
    assert len(events) == 1
    assert tuple(events[0].pos) == (11, 12)
예제 #4
0
async def viewer(receive_channel, shape):
    display_shape = (512, 512)

    # init app
    app = Application()
    app.create()

    # init viewer
    canvas = scene.SceneCanvas(app=app, keys="interactive")
    canvas.size = display_shape

    # create view and image
    view = canvas.central_widget.add_view()

    # lock view
    view.camera = scene.PanZoomCamera(aspect=1, interactive=False)
    view.camera.flip = (0, 1, 0)

    image = scene.visuals.Image(np.empty(display_shape, np.uint8),
                                parent=view.scene,
                                cmap="grays")
    view.camera.set_range(margin=0)

    canvas.show()

    async with receive_channel:
        async for frame in receive_channel:
            # logger.debug(f".... average {frame.mean():.2f}")

            # resize
            frame = transform.resize(frame, display_shape)
            # rescale intensity to 8-bit
            frame = exposure.rescale_intensity(frame, out_range=np.uint8)
            # change dtype
            frame = frame.astype(np.uint8)

            image.set_data(frame)

            canvas.update()
            app.process_events()
예제 #5
0
파일: test_app.py 프로젝트: kif/vispy
def _test_application(backend):
    """Test application running"""
    app = Application()
    assert_raises(ValueError, app.use, "foo")
    app.use(backend)
    wrong = "Glut" if app.backend_name != "Glut" else "Pyglet"
    assert_raises(RuntimeError, app.use, wrong)
    app.process_events()
    if backend is not None:
        # "in" b/c "qt" in "PySide (qt)"
        assert_in(backend, app.backend_name)
    print(app)  # test __repr__

    # Canvas
    pos = [0, 0]
    size = (100, 100)
    # Use "with" statement so failures don't leave open window
    # (and test context manager behavior)
    title = "default" if backend is None else backend
    with Canvas(title=title, size=size, app=app, show=True, position=pos) as canvas:
        assert_is(canvas.app, app)
        assert_true(canvas.native)
        assert_equal("swap_buffers", canvas.events.paint.callback_refs[-1])
        print(canvas)  # __repr__
        assert_array_equal(canvas.size, size)
        assert_equal(canvas.title, title)
        canvas.title = "you"
        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)

        # screenshots
        gl.glViewport(0, 0, *size)
        ss = _screenshot()
        assert_array_equal(ss.shape, size + (3,))
        assert_equal(len(canvas._backend._vispy_get_geometry()), 4)
        assert_array_equal(canvas.size, size)
        assert_equal(len(canvas.position), 2)  # XXX knawnfail, doesn't "take"

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

        vert = VertexShader("uniform vec4 pos;" "void main (void) {gl_Position = pos;}")
        frag = FragmentShader("uniform vec4 pos;" "void main (void) {gl_FragColor = pos;}")
        program = Program(vert, frag)
        # uniform = program.uniforms[0]
        program["pos"] = [1, 2, 3, 4]
        program.activate()  # should print
        # uniform.upload(program)
        program.detach(vert)
        program.detach(frag)
        assert_raises(RuntimeError, program.detach, vert)
        assert_raises(RuntimeError, program.detach, frag)

        vert = VertexShader("attribute vec4 pos;" "void main (void) {gl_Position = pos;}")
        frag = FragmentShader("void main (void) {}")
        program = Program(vert, frag)
        # attribute = program.attributes[0]
        program["pos"] = [1, 2, 3, 4]
        program.activate()
        # attribute.upload(program)
        # cannot get element count
        # assert_raises(RuntimeError, program.draw, 'POINTS')

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

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

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

        # 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)
        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()
예제 #6
0
def _test_application(backend):
    """Test application running"""
    app = Application()
    assert_raises(ValueError, app.use, 'foo')
    app.use(backend)
    wrong = 'Glut' if app.backend_name != 'Glut' else 'Pyglet'
    assert_raises(RuntimeError, app.use, wrong)
    app.process_events()
    if backend is not None:
        # "in" b/c "qt" in "PySide (qt)"
        assert_true(backend in app.backend_name)
    print(app)  # test __repr__

    # Canvas
    pos = [0, 0, 1, 1]
    # Use "with" statement so failures don't leave open window
    # (and test context manager behavior)
    with Canvas(title='me', app=app, show=True, position=pos) as canvas:
        assert_true(canvas.app is app)
        assert_true(canvas.native)
        print(canvas.size >= (1, 1))
        canvas.resize(90, 90)
        canvas.move(1, 1)
        assert_equal(canvas.title, 'me')
        canvas.title = 'you'
        canvas.position = (0, 0)
        canvas.size = (100, 100)
        canvas.connect(on_mouse_move)
        assert_raises(ValueError, canvas.connect, _on_mouse_move)
        canvas.show()
        assert_raises(ValueError, canvas.connect, on_nonexist)

        # screenshots
        ss = _screenshot()
        assert_array_equal(ss.shape[2], 3)  # XXX other dimensions not correct?
        # XXX it would be good to do real checks, but sometimes the
        # repositionings don't "take" (i.e., lead to random errors)
        assert_equal(len(canvas._backend._vispy_get_geometry()), 4)
        assert_equal(len(canvas.size), 2)
        assert_equal(len(canvas.position), 2)

        # GLOO: should have an OpenGL context already, so these should work
        vert = VertexShader("void main (void) {gl_Position = pos;}")
        frag = FragmentShader("void main (void) {gl_FragColor = pos;}")
        program = Program(vert, frag)
        assert_raises(ShaderError, program.activate)

        vert = VertexShader("uniform vec4 pos;"
                            "void main (void) {gl_Position = pos;}")
        frag = FragmentShader("uniform vec4 pos;"
                              "void main (void) {gl_FragColor = pos;}")
        program = Program(vert, frag)
        uniform = program.uniforms[0]
        uniform.set_data([1, 2, 3, 4])
        program.activate()  # should print
        uniform.upload(program)
        program.detach(vert, frag)
        assert_raises(ShaderError, program.detach, vert)
        assert_raises(ShaderError, program.detach, frag)

        vert = VertexShader("attribute vec4 pos;"
                            "void main (void) {gl_Position = pos;}")
        frag = FragmentShader("void main (void) {}")
        program = Program(vert, frag)
        attribute = program.attributes[0]
        attribute.set_data([1, 2, 3, 4])
        program.activate()
        attribute.upload(program)
        # cannot get element count
        assert_raises(ProgramError, program.draw, 'POINTS')

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

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

        # bad programs
        frag_bad = ("varying vec4 v_colors")  # no semicolon
        program = Program(vert, frag_bad)
        assert_raises(ShaderError, program.activate)
        frag_bad = None  # no fragment code. no main is not always enough
        program = Program(vert, frag_bad)
        assert_raises(ProgramError, program.activate)

        # 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)
        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()
        # put this in even though __exit__ will call it to make sure we don't
        # have problems calling it multiple times
        canvas.close()
    app.quit()
    app.quit()  # make sure it doesn't break if a user does something silly
예제 #7
0
def test_show_entity():
    """Test showing an entity"""
    # Create a figure
    app = Application()
    fig = scene.CanvasWithScene(app=app)
    app.create()
    fig.size = 1, 1
    fig.show()
    camcontainer = scene.PixelCamera(fig.viewbox)
    camera = scene.ThreeDCamera(camcontainer)
    camera._fov = 90
    fig.viewbox.camera = camera
    pointscontainer = scene.Entity(fig.viewbox)
    scene.PointsEntity(pointscontainer, 1000)
    app.process_events()
    app.process_events()  # for good measure

    # Now do first-person
    camcontainer = scene.PixelCamera(fig.viewbox)
    camera = scene.FirstPersonCamera(camcontainer)
    camera.update_angles()
    fig.viewbox.camera = camera
    pointscontainer = scene.Entity(fig.viewbox)
    scene.PointsEntity(pointscontainer, 1000)
    app.process_events()
    app.process_events()  # for good measure

    # Now do 2D
    camcontainer = scene.PixelCamera(fig.viewbox)
    camera = scene.TwoDCamera(camcontainer)
    camera.xlim = -100, 500
    camera.ylim = -100, 500
    fig.viewbox.camera = camera
    pointscontainer = scene.Entity(fig.viewbox)
    scene.PointsEntity(pointscontainer, 1000)
    transforms.translate(camcontainer.transform, 50, 50)
    transforms.rotate(camcontainer.transform, 10, 0, 0, 1)
    app.process_events()
    app.process_events()  # for good measure

    fig.close()
    app.quit()
예제 #8
0
"""Module with helper functions for plotting
"""
from vispy.app import Application
from PyQt5.QtWidgets import QApplication

app = Application('pyqt5')

from vispy.scene import SceneCanvas, TurntableCamera
from vispy.visuals import Visual
from vispy.scene.visuals import create_visual_node
from vispy.geometry import create_sphere, MeshData
from numpy import array, clip, float32, r_
from vispy.gloo import VertexBuffer
from vispy.io.image import _make_png
from vispy.gloo.wrappers import read_pixels

COLORMAP = 'coolwarm'


class Viz(SceneCanvas):
    _view = None

    def __init__(self):
        super().__init__(keys='interactive', show=True, bgcolor='white')
        self._view = self.central_widget.add_view()

    def _add_mesh(self, mesh):
        self._view.add(mesh)

    def _repr_png_(self):
        """This is used by ipython to plot inline.