def __init__(self, et, timeline, downscale=1, stim_type='calibration_horizontal'): self.downscale = downscale self.et = et self.timeline = timeline app.use_app('pyglet') app.Canvas.__init__(self, keys='interactive', size=(1280, 720)) self.fullscreen = True self.width, self.height = self.physical_size print('window size : ', self.physical_size) self.stimulation = Stimulation(self.width // downscale, self.height // downscale, stim_type=stim_type) self.program = gloo.Program(vertex, fragment, count=4) self.program['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)] self.program['texcoord'] = [(1, 1), (1, 0), (0, 1), (0, 0)] self.program['texture'] = (255 * np.random.rand( self.height // downscale, self.width // downscale, 3)).astype( np.uint8) gloo.set_viewport(0, 0, self.width, self.height) self._timer = app.Timer('auto', connect=self.on_timer, start=True) self.start = time.time() self.stims_X_t = [] self.eye_x_t = [] self.native.set_mouse_visible(False) self.show()
def start_qt_app(): """Start a Qt application if necessary. If a new Qt application is created, this function returns it. If no new application is created, the function returns None. """ # Only start a Qt application if there is no # IPython event loop integration. if not _check_qt(): return global _APP if _try_enable_ipython_qt(): return try: from vispy import app app.use_app("pyqt4") except ImportError: pass if QtGui.QApplication.instance(): _APP = QtGui.QApplication.instance() return if _APP: return _APP = QtGui.QApplication(sys.argv) return _APP
def init_canvas(self): if self.verbose == 1: print('init_canvas') app.use_app('ipynb_webgl') ca = vispy.scene.SceneCanvas(keys='interactive', show=True,size=(self.canvas_width,self.canvas_height),bgcolor=[1,1,1]) ca.show() self.canvas = ca view = ca.central_widget.add_view() self.text = visuals.Text(anchor_x='right') view.add(self.text) self.label_texts = visuals.Text(anchor_x='right') view.add(self.label_texts) self.camera = CustomPanZoomCamera([self.text,self.label_texts]) view.camera = self.camera axis = visuals.Axis(parent=view.scene) self.view = view self.line = visuals.Line() self.line.set_data(pos=np.array([[0,0,0]]),color=np.array([[0,0,0,0]])) self.line.order = 1 self.view.add(self.line) self.mesh = visuals.Mesh() self.mesh.order = 0 self.view.add(self.mesh) app.run()
def set_vispy_env(): if sys.platform == 'win32': # app.use_app('PySide6') app.use_app('glfw') gloo.gl.use_gl('gl2') elif sys.platform == 'linux': app.use_app('glfw') gloo.gl.use_gl('gl2')
def __init__(self, parent, master): ''' In der __init__ Methode wird gloo konfiguriert und der pyqt Kontext festgelegt. Des Weiteren werden alle self.(...) Variablen und der Timer (siehe on_timer) initiiert. Parameter: parent wird benoetigt zur Festsetzung des Kontextes master wird zu Interaktion mit der GUI benötigt (z.B. Errors) Rückgabewerte: - ''' print('[* Canvas: initializing *]') app.use_app(backend_name='pyqt4', call_reuse=True) app.Canvas.__init__(self, size=(1465, 850), title='GraphicMolecule Vizualizer', keys='interactive', parent=parent) gloo.set_state(clear_color=(0.1, 0.14, 0.23, 1.00), depth_test=True, blend=True, blend_func=('src_alpha', 'one_minus_src_alpha')) gloo.wrappers.set_depth_range(near=0.9, far=1) #initializing all self._____ variables self._master = master self._molName = '' self._molecule = None self._programs = [] self._decreaseDrawHorizon = False self._increaseDrawHorizon = False self._drawHorizon = 0 self._rotSpeed = 0 self._zoom = -7 self._rotation = 0 self._rotationVec = [0, 0, 0] self._atomSizes = 0 self._atomColors = (0, 0, 0) self._bondSize = 0 self._bondColor = (0, 0, 0) self._atomDT = '' self._bondDT = '' #als observer anmelden self._master.registerObserver(self) self.timer = app.Timer('auto', self.on_timer, start=True)
def main(): if (args.no_audio): State.do_init(audio=False) # initialize the state objects/threads else: State.do_init(audio=True) # initialize the state objects/threads app.use_app(backend_name='PyGlet') c = Renderer() c.show() if (args.full): c.fullscreen = True # fullscreen mode c.app.run() State.destroy() Logger.warn('Exiting VisAR')
def __init__(self, retina): app.use_app('pyglet') self.retina = retina app.Canvas.__init__(self, keys='interactive', fullscreen=True, size=(1280, 960))# self.program = gloo.Program(vertex, fragment, count=4) self.program['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)] self.program['texcoord'] = [(1, 1), (1, 0), (0, 1), (0, 0)] self.program['texture'] = np.zeros((self.retina.h, self.retina.w, 3)).astype(np.uint8) width, height = self.physical_size gloo.set_viewport(0, 0, width, height) self._timer = app.Timer('auto', connect=self.on_timer, start=True) self.start = time.time() self.show()
def main(): if args.no_audio: State.do_init(audio=False) # initialize the state objects/threads else: State.do_init(audio=True) # initialize the state objects/threads app.use_app(backend_name="PyGlet") c = Renderer() c.show() if args.full: c.fullscreen = True # fullscreen mode c.app.run() State.destroy() Logger.warn("Exiting VisAR")
def __init__(self, plot_mode: str = 'windowed'): app.use_app('PySide2') app.Canvas.__init__(self, title='Use your wheel to zoom!', keys='interactive', app='PySide2') gloo.set_viewport(0, 0, *self.physical_size) gloo.set_state(clear_color='black', blend=True, blend_func=('src_alpha', 'one_minus_src_alpha')) self.plot_interact_flag = True self.is_initialized = False self.y = None self.plot_mode = plot_mode self.last_plotted_column = -1
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'))
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 contexts = [dict(samples=4), dict(stencil_size=8), dict(samples=4, stencil_size=8)] if a.backend_name.lower() != 'glfw': # glfw *always* double-buffers contexts.append(dict(double_buffer=False, samples=4)) contexts.append(dict(double_buffer=False)) else: assert_raises(RuntimeError, Canvas, app=a, context=dict(double_buffer=False)) if a.backend_name.lower() == 'sdl2' and os.getenv('TRAVIS') == 'true': raise SkipTest('Travis SDL cannot set context') for context in contexts: n_items = len(context) with Canvas(context=context): if 'true' in (os.getenv('TRAVIS', ''), os.getenv('APPVEYOR', '').lower()): # Travis and Appveyor cannot handle obtaining these values props = context else: props = get_gl_configuration() assert_equal(len(context), n_items) for key, val in context.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, context='foo') assert_raises(KeyError, Canvas, context=dict(foo=True)) assert_raises(TypeError, Canvas, context=dict(double_buffer='foo'))
def __init__(self, retina): app.use_app('pyglet') self.retina = retina app.Canvas.__init__( self, #title=retina.model['title'], keys='interactive', fullscreen=True, size=(1280, 960)) # self.program = gloo.Program(vertex, fragment, count=4) self.program['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)] self.program['texcoord'] = [(1, 1), (1, 0), (0, 1), (0, 0)] self.program['texture'] = np.zeros( (int(self.retina.h), int(self.retina.w), 3)).astype(np.uint8) width, height = self.physical_size gloo.set_viewport(0, 0, width, height) self._timer = app.Timer('auto', connect=self.on_timer, start=True) self.start = time.time() self.show() self.verb = False
def _load_webgl_backend(ipython): """ Load the webgl backend for the IPython notebook""" from vispy import app app_instance = app.use_app("ipynb_webgl") if app_instance.backend_name == "ipynb_webgl": ipython.write("Vispy IPython module has loaded successfully") else: # TODO: Improve this error message ipython.write_err("Unable to load webgl backend of Vispy")
def test_run(): """Test app running""" a = use_app() if a.backend_name.lower() == 'glut': raise SkipTest('cannot test running glut') # knownfail for _ in range(2): with Canvas(size=(100, 100), show=True, title='run') as c: @c.events.draw.connect def draw(event): print(event) # test event __repr__ c.app.quit() c.update() c.app.run() c.app.quit() # make sure it doesn't break if a user quits twice
def __init__(self, bgcolor, size, dpi, decorate, **kwargs): self._entered = False self._wanted_vp = None if decorate is None: # deal with GLFW's problems from vispy.app import use_app app = use_app() if _bad_glfw_decorate(app): decorate = True else: decorate = False SceneCanvas.__init__(self, bgcolor=bgcolor, size=size, dpi=dpi, decorate=decorate, **kwargs)
def __init__(self, et, timeline, downscale=1, stim_type='calibration_horizontal'): self.downscale = downscale self.et = et self.timeline = timeline img0 = np.zeros((self.window_h, self.window_w, 3)).astype(np.uint8) app.use_app('pyglet') app.Canvas.__init__(self, keys='interactive', size=(1280, 720)) self.fullscreen = True self.width, self.height = self.physical_size print ('window size : ', self.physical_size) self.stimulation = Stimulation(self.width//downscale, self.height//downscale, stim_type=stim_type) self.program = gloo.Program(vertex, fragment, count=4) self.program['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)] self.program['texcoord'] = [(1, 1), (1, 0), (0, 1), (0, 0)] self.program['texture'] = np.zeros((self.height//downscale, self.width//downscale, 3)).astype(np.uint8) gloo.set_viewport(0, 0, self.width, self.height) self._timer = app.Timer('auto', connect=self.on_timer, start=True) self.start = time.time() self.stims_X_t = [] self.native.set_mouse_visible(False) self.show()
def __init__(self, _interval, **kwargs): # DONT EVER REMOVE THIS # NOTE: GLFW has to be initialized, otherwise canvas positioning is not going to work properly glfw.init() # DONT EVER REMOVE THIS # Set canvas init arguments backend_kwargs = {} canvas_kwargs = { 'app': app.use_app(), 'title': 'vxPy visual stimulus display', 'position': (64, 64), 'size': (256, 256), 'resizable': True, 'always_on_top': True, 'vsync': True, 'decorate': False, 'autoswap': False } # Overwrite canvas arguments for key in list(kwargs.keys()): if key in canvas_kwargs: canvas_kwargs[key] = kwargs.pop(key) # Call parent init app.Canvas.__init__(self, **canvas_kwargs, backend_kwargs=backend_kwargs) self.current_visual: vxvisual.AbstractVisual = None self.t: float = time.perf_counter() self.new_t: float = time.perf_counter() gloo.set_clear_color((0.0, 0.0, 0.0, 1.0)) self.new_frame_drawn = False # Update size and position once self.update_dimensions() # Show self.show() # Clear after show self.clear()
def __init__(self, vertex_shader, fragment_shader_template, functions, *args, **kwargs): super().__init__(*args, **kwargs) self.vertex_shader = vertex_shader self.fragment_shader_template = fragment_shader_template self.functions = functions self.function_index = 0 self.program = Program(self.vertex_shader, self.fragment_shader) self.program['position'] = [(-1.0, -1.0), (-1.0, 1.0), (1.0, 1.0), (-1.0, -1.0), (1.0, 1.0), (1.0, -1.0)] self.program['resolution'] = self.size self.center = array([0.0, 0.0]) self.program['center'] = array( [*unpack_double(self.center[0]), *unpack_double(self.center[1])]) self.center_min, self.center_max = array([-10.0, -10.0]), array([10.0, 10.0]) self.scale = 2.5 self.program['scale'] = unpack_double(self.scale) self.scale_min, self.scale_max = 10.0**-10.0, 10.0**2.0 self.line = LinePlotVisual(array([[-10, -10]]), color='white') self.position_text = TextVisual('', color='white', font_size=10, anchor_x='right', anchor_y='top') self.iterations_text = TextVisual('', color='white', font_size=10, anchor_x='left', anchor_y='top') self.info_text = TextVisual(self.function_info, pos=(5, 5), color='white', font_size=10, anchor_x='left', anchor_y='bottom') if use_app().backend_name == 'PyQt5': self._backend.leaveEvent = self.on_mouse_exit self.timer = Timer(connect=self.update, start=True) self.show()
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)
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()
def __init__(self, **kwargs): vxprocess.AbstractProcess.__init__(self, **kwargs) self.app = app.use_app() self.visual_is_displayed = False self.enable_idle_timeout = False self.times = [] # Create canvas _interval = 1. / config.CONF_DISPLAY_FPS self.canvas = Canvas(_interval) # Process vispy events once too avoid frozen screen at start app.process_events() # Run event loop self.enable_idle_timeout = False self.run(interval=_interval)
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 if a.backend_name.lower() == 'osmesa': return # cannot set config on OSMesa # 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 IS_CI: raise SkipTest('Travis SDL cannot set context') for config in configs: n_items = len(config) with Canvas(config=config): if IS_CI: # Travis and Appveyor cannot handle obtaining these values props = config else: props = get_gl_configuration() assert len(config) == n_items for key, val in config.items(): # XXX knownfail for windows samples, and wx/tkinter (all platforms) if key == 'samples': will_fail_backend = a.backend_name.lower() in ('wx', 'tkinter') if not (sys.platform.startswith('win') or will_fail_backend): assert 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'))
def _handle_vispy_key_press_events(self, event: KeyEvent) -> None: """Router: Calls AppCommands functions based on the event that's given.""" key_commands = { '1': lambda: self.select_channel(1), '2': lambda: self.select_channel(2), '3': lambda: self.select_channel(3), '4': lambda: self.select_channel(4), 'W': lambda: self.move_section(z=30), 'S': lambda: self.move_section(z=-30), 'A': lambda: self.move_section(x=-30), 'D': lambda: self.move_section(x=30), 'Q': lambda: self.move_section(y=-30), 'E': lambda: self.move_section(y=30), 'I': lambda: self.move_section(rz=3), 'K': lambda: self.move_section(rz=-3), 'J': lambda: self.move_section(rx=-3), 'L': lambda: self.move_section(rx=3), 'U': lambda: self.move_section(ry=-3), 'O': lambda: self.move_section(ry=3), 'Escape': use_app().quit, } if command := key_commands.get(event.key.name): command()
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A GLSL sandbox application based on the spinning cube. Requires PySide or PyQt4. """ import numpy as np from vispy import app, gloo from vispy.io import read_mesh, load_data_file, load_crate from vispy.util.transforms import perspective, translate, rotate # Force using qt and take QtCore+QtGui from backend module try: app_object = app.use_app('pyqt4') except Exception: app_object = app.use_app('pyside') QtCore = app_object.backend_module.QtCore, QtGui = app_object.backend_module.QtGui VERT_CODE = """ uniform mat4 u_model; uniform mat4 u_view; uniform mat4 u_projection; attribute vec3 a_position; attribute vec2 a_texcoord; varying vec2 v_texcoord; void main()
from __future__ import division import numpy as np from vispy import app from vispy import gloo from vispy.gloo.util import _screenshot import OpenGL.GL as gl import os homeDir = os.path.dirname(__file__) app.use_app("glfw") def makeTexture(dataArray): ''' Reads an image file, converts from 0-255 to 0-1, and loads into a 2D texture. Args: * dataArray (str) returns gloo.Texture2D ''' scaledData = dataArray / dataArray.max() tex = gloo.Texture2D(scaledData.astype(np.float32)) return tex def getShader(shaderPath): ''' Loads a glsl shader as a string.
""" Custom Qt widgets that serve as native objects that the public-facing elements wrap. """ # set vispy to use same backend as qtpy from qtpy import API_NAME from vispy import app app.use_app(API_NAME) del app from qtpy.QtWidgets import ( QMainWindow, QWidget, QHBoxLayout, QLabel, QAction, QShortcut, ) from qtpy.QtGui import QKeySequence from ..util.theme import template class Window: """Application window that contains the menu bar and viewer. Parameters ---------- qt_viewer : QtViewer Contained viewer widget.
import logging import qtpy from vispy import app # set vispy application to the appropriate qt backend app.use_app(qtpy.API_NAME) del app # set vispy logger to show warning and errors only vispy_logger = logging.getLogger('vispy') vispy_logger.setLevel(logging.WARNING) from .camera import VispyCamera from .canvas import VispyCanvas from .overlays.axes import VispyAxesOverlay from .overlays.interaction_box import VispyInteractionBox from .overlays.scale_bar import VispyScaleBarOverlay from .overlays.text import VispyTextOverlay from .utils.quaternion import quaternion2euler from .utils.visual import create_vispy_visual
def test_application(): """Test application running""" app = use_app() print(app) # __repr__ without app app.create() wrong = 'glfw' if app.backend_name.lower() != 'glfw' else 'pyqt4' assert_raises(RuntimeError, use_app, wrong) app.process_events() print(app) # test __repr__ assert_raises(ValueError, Canvas, keys='foo') assert_raises(TypeError, Canvas, keys=dict(escape=1)) assert_raises(ValueError, Canvas, keys=dict(escape='foo')) # not an attr pos = [0, 0] if app.backend_module.capability['position'] else None size = (100, 100) # Use "with" statement so failures don't leave open window # (and test context manager behavior) title = 'default' with Canvas(title=title, size=size, app=app, show=True, position=pos) as canvas: context = canvas.context assert_true(canvas.create_native() is None) # should be done already assert_is(canvas.app, app) assert_true(canvas.native) assert_equal('swap_buffers', canvas.events.draw.callback_refs[-1]) canvas.measure_fps(0.001) sleep(0.002) canvas.update() app.process_events() assert_true(canvas.fps > 0) # Other methods print(canvas) # __repr__ assert_equal(canvas.title, title) canvas.title = 'you' with use_log_level('warning', record=True, print_msg=False) as l: if app.backend_module.capability['position']: # todo: disable more tests based on capability canvas.position = pos canvas.size = size if 'ipynb_vnc' in canvas.app.backend_name.lower(): assert_true(len(l) >= 1) else: assert_true(len(l) == 0) canvas.connect(on_mouse_move) assert_raises(ValueError, canvas.connect, _on_mouse_move) if sys.platform != 'darwin': # XXX knownfail, prob. needs warmup canvas.show(False) canvas.show() app.process_events() assert_raises(ValueError, canvas.connect, on_nonexist) # deprecation of "paint" with use_log_level('info', record=True, print_msg=False) as log: olderr = sys.stderr try: fid = StringIO() sys.stderr = fid @canvas.events.paint.connect def fake(event): pass finally: sys.stderr = olderr assert_equal(len(log), 1) assert_in('deprecated', log[0]) # screenshots gl.glViewport(0, 0, *size) ss = _screenshot() assert_array_equal(ss.shape, size + (4,)) assert_equal(len(canvas._backend._vispy_get_geometry()), 4) if sys.platform != 'win32': # XXX knownfail for windows assert_array_equal(canvas.size, size) assert_equal(len(canvas.position), 2) # XXX knawnfail, doesn't "take" # GLOO: should have an OpenGL context already, so these should work vert = "void main (void) {gl_Position = pos;}" frag = "void main (void) {gl_FragColor = pos;}" program = Program(vert, frag) assert_raises(RuntimeError, program.glir.flush, context.shared.parser) vert = "uniform vec4 pos;\nvoid main (void) {gl_Position = pos;}" frag = "uniform vec4 pos;\nvoid main (void) {gl_FragColor = pos;}" program = Program(vert, frag) #uniform = program.uniforms[0] program['pos'] = [1, 2, 3, 4] vert = "attribute vec4 pos;\nvoid main (void) {gl_Position = pos;}" frag = "void main (void) {}" program = Program(vert, frag) #attribute = program.attributes[0] program["pos"] = [1, 2, 3, 4] # use a real program program._glir.clear() vert = ("uniform mat4 u_model;" "attribute vec2 a_position; attribute vec4 a_color;" "varying vec4 v_color;" "void main (void) {v_color = a_color;" "gl_Position = u_model * vec4(a_position, 0.0, 1.0);" "v_color = a_color;}") frag = "void main() {gl_FragColor = vec4(0, 0, 0, 1);}" n, p = 250, 50 T = np.random.uniform(0, 2 * np.pi, n) position = np.zeros((n, 2), dtype=np.float32) position[:, 0] = np.cos(T) position[:, 1] = np.sin(T) color = np.ones((n, 4), dtype=np.float32) * (1, 1, 1, 1) data = np.zeros(n * p, [('a_position', np.float32, 2), ('a_color', np.float32, 4)]) data['a_position'] = np.repeat(position, p, axis=0) data['a_color'] = np.repeat(color, p, axis=0) program = Program(vert, frag) program.bind(VertexBuffer(data)) program['u_model'] = np.eye(4, dtype=np.float32) # different codepath if no call to activate() program.draw(gl.GL_POINTS) subset = IndexBuffer(np.arange(10, dtype=np.uint32)) program.draw(gl.GL_POINTS, subset) # bad programs frag_bad = ("varying vec4 v_colors") # no semicolon program = Program(vert, frag_bad) assert_raises(RuntimeError, program.glir.flush, context.shared.parser) frag_bad = None # no fragment code. no main is not always enough assert_raises(ValueError, Program, vert, frag_bad) # Timer timer = Timer(interval=0.001, connect=on_mouse_move, iterations=2, start=True, app=app) timer.start() timer.interval = 0.002 assert_equal(timer.interval, 0.002) assert_true(timer.running) sleep(.003) assert_true(timer.elapsed >= 0.002) timer.stop() assert_true(not timer.running) assert_true(timer.native) timer.disconnect() # test that callbacks take reasonable inputs _test_callbacks(canvas) # cleanup canvas.swap_buffers() canvas.update() app.process_events() # put this in even though __exit__ will call it to make sure we don't # have problems calling it multiple times canvas.close() # done by context
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A GLSL sandbox application based on the spinning cube. Requires PySide or PyQt4. """ import numpy as np from vispy import app, gloo, dataio from vispy.util.transforms import perspective, translate, rotate # Force using qt and take QtCore+QtGui from backend module app_object = app.use_app('pyqt4') QtCore = app_object.backend_module.QtCore, QtGui = app_object.backend_module.QtGui VERT_CODE = """ uniform mat4 u_model; uniform mat4 u_view; uniform mat4 u_projection; attribute vec3 a_position; attribute vec2 a_texcoord; varying vec2 v_texcoord; void main() { v_texcoord = a_texcoord; gl_Position = u_projection * u_view * u_model * vec4(a_position,1.0);
def visualize(z_in, azimuth=25., elevation=30., thresholds=[0.94, .89, .75, .5, .25, .1], opacities=[.9, .8, .7, .5, .2, .1], # thresholds=[0.94, .89, .75], opacities=[.99, .7, .2], # thresholds=[0.7, .5, .2], opacities=[.95, .5, .2], fourier_label = {'f_x':'f_x', 'f_y':'f_y', 'f_t':'f_t'}, name=None, ext=ext, do_axis=True, do_grids=False, draw_projections=True, colorbar=False, f_N=2., f_tN=2., figsize=figsize, **kwargs): """ Visualization of the Fourier spectrum by showing 3D contour plots at different thresholds parameters ---------- z : envelope of the cloud """ if not(os.path.isdir(figpath)): os.mkdir(figpath) z = z_in.copy() N_X, N_Y, N_frame = z.shape fx, fy, ft = get_grids(N_X, N_Y, N_frame) # Normalize the amplitude. z /= z.max() from vispy import app, scene app.use_app('pyglet') #from vispy.util.transforms import perspective, translate, rotate from vispy.color import Color transparent = Color(color='black', alpha=0.) import colorsys canvas = scene.SceneCanvas(size=figsize, bgcolor='white', dpi=450) view = canvas.central_widget.add_view() vol_data = np.rollaxis(np.rollaxis(z, 1), 2) # volume = scene.visuals.Volume(vol_data, parent=view.scene)#frame) center = scene.transforms.STTransform(translate=( -N_X/2, -N_Y/2, -N_frame/2)) # volume.transform = center # volume.cmap = 'blues' if draw_projections: from vispy.color import Colormap cm = Colormap([(1.0, 1.0, 1.0, 1.0), 'k']) opts = {'parent':view.scene, 'cmap':cm, 'clim':(0., 1.)} energy_xy = np.rot90(np.max(z, axis=2)[:, ::-1], 3) fourier_xy = scene.visuals.Image(np.rot90(energy_xy), **opts) tr_xy = scene.transforms.MatrixTransform() tr_xy.rotate(90, (0, 0, 1)) tr_xy.translate((N_X/2, -N_Y/2, -N_frame/2)) fourier_xy.transform = tr_xy energy_xt = np.rot90(np.max(z, axis=1)[:, ::-1], 3) fourier_xt = scene.visuals.Image(energy_xt, **opts) tr_xt = scene.transforms.MatrixTransform() tr_xt.rotate(90, (1, 0, 0)) tr_xt.translate((-N_X/2, N_Y/2, -N_frame/2)) fourier_xt.transform = tr_xt energy_yt = np.max(z, axis=0)[:, ::-1] fourier_yt = scene.visuals.Image(energy_yt, **opts) tr_yt = scene.transforms.MatrixTransform() tr_yt.rotate(90, (0, 1, 0)) tr_yt.translate((-N_X/2, -N_Y/2, N_frame/2)) fourier_yt.transform = tr_yt # Generate iso-surfaces at different energy levels surfaces = [] for i_, (threshold, opacity) in enumerate(zip(thresholds, opacities)): surfaces.append(scene.visuals.Isosurface(z, level=threshold, # color=Color(np.array(colorsys.hsv_to_rgb(1.*i_/len(thresholds), 1., 1.)), alpha=opacity), color=Color(np.array(colorsys.hsv_to_rgb(.66, 1., 1.)), alpha=opacity), shading='smooth', parent=view.scene) ) surfaces[-1].transform = center # Draw a sphere at the origin axis = scene.visuals.XYZAxis(parent=view.scene) for p in ([1, 1, 1, -1, 1, 1], [1, 1, -1, -1, 1, -1], [1, -1, 1, -1, -1, 1],[1, -1, -1, -1, -1, -1], [1, 1, 1, 1, -1, 1], [-1, 1, 1, -1, -1, 1], [1, 1, -1, 1, -1, -1], [-1, 1, -1, -1, -1, -1], [1, 1, 1, 1, 1, -1], [-1, 1, 1, -1, 1, -1], [1, -1, 1, 1, -1, -1], [-1, -1, 1, -1, -1, -1]): line = scene.visuals.Line(pos=np.array([[p[0]*N_X/2, p[1]*N_Y/2, p[2]*N_frame/2], [p[3]*N_X/2, p[4]*N_Y/2, p[5]*N_frame/2]]), color='black', parent=view.scene) axisX = scene.visuals.Line(pos=np.array([[0, -N_Y/2, 0], [0, N_Y/2, 0]]), color='red', parent=view.scene) axisY = scene.visuals.Line(pos=np.array([[-N_X/2, 0, 0], [N_X/2, 0, 0]]), color='green', parent=view.scene) axisZ = scene.visuals.Line(pos=np.array([[0, 0, -N_frame/2], [0, 0, N_frame/2]]), color='blue', parent=view.scene) if do_axis: t = {} for text in ['f_x', 'f_y', 'f_t']: t[text] = scene.visuals.Text(fourier_label[text], parent=canvas.scene, face='Helvetica', color='black') t[text].font_size = 8 t['f_x'].pos = canvas.size[0] // 3, canvas.size[1] - canvas.size[1] // 8 t['f_y'].pos = canvas.size[0] - canvas.size[0] // 8, canvas.size[1] - canvas.size[1] // 6 t['f_t'].pos = canvas.size[0] // 8, canvas.size[1] // 2 cam = scene.TurntableCamera(elevation=elevation, azimuth=azimuth, up='z') cam.fov = 48 cam.scale_factor = N_X * 1.8 if do_axis: margin = 1.35 else: margin = 1 cam.set_range((-N_X/2*margin, N_X/2/margin), (-N_Y/2*margin, N_Y/2/margin), (-N_frame/2*margin, N_frame/2/margin)) view.camera = cam im = canvas.render(size=figsize) app.quit() if not(name is None): import vispy.io as io io.write_png(name + ext, im) else: return im
def test_multiple_canvases(): """Testing multiple canvases""" n_check = 3 app = use_app() with Canvas(app=app, size=_win_size, title='same_0') as c0: with Canvas(app=app, size=_win_size, title='same_1') as c1: ct = [0, 0] @c0.events.draw.connect def draw0(event): ct[0] += 1 c0.update() @c1.events.draw.connect # noqa, analysis:ignore def draw1(event): ct[1] += 1 c1.update() c0.show() # ensure visible c1.show() c0.update() # force first draw c1.update() timeout = time() + 2.0 while (ct[0] < n_check or ct[1] < n_check) and time() < timeout: app.process_events() print((ct, n_check)) assert n_check <= ct[0] <= n_check + 2 # be a bit lenient assert n_check <= ct[1] <= n_check + 2 # check timer global timer_ran timer_ran = False def on_timer(_): global timer_ran timer_ran = True t = Timer(0.1, app=app, connect=on_timer, iterations=1, # noqa start=True) app.process_events() sleep(0.5) # long for slow systems app.process_events() app.process_events() assert timer_ran if app.backend_name.lower() == 'wx': raise SkipTest('wx fails test #2') # XXX TODO Fix this kwargs = dict(app=app, autoswap=False, size=_win_size, show=True) with Canvas(title='0', **kwargs) as c0: with Canvas(title='1', **kwargs) as c1: bgcolors = [None] * 2 @c0.events.draw.connect def draw00(event): print(' {0:7}: {1}'.format('0', bgcolors[0])) if bgcolors[0] is not None: gl.glViewport(0, 0, *list(_win_size)) gl.glClearColor(*bgcolors[0]) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glFinish() @c1.events.draw.connect def draw11(event): print(' {0:7}: {1}'.format('1', bgcolors[1])) if bgcolors[1] is not None: gl.glViewport(0, 0, *list(_win_size)) gl.glClearColor(*bgcolors[1]) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glFinish() for ci, canvas in enumerate((c0, c1)): print('draw %s' % canvas.title) bgcolors[ci] = [0.5, 0.5, 0.5, 1.0] _update_process_check(canvas, 127) for ci, canvas in enumerate((c0, c1)): print('test') _update_process_check(canvas, 127, draw=False) bgcolors[ci] = [1., 1., 1., 1.] _update_process_check(canvas, 255) bgcolors[ci] = [0.25, 0.25, 0.25, 0.25] _update_process_check(canvas, 64)
""" Custom Qt widgets that serve as native objects that the public-facing elements wrap. """ from PyQt5.QtWidgets import QApplication as QtApplication from ._viewer import QtViewer from ._layerPanel import QtLayerPanel from ._controls import QtControls from ._imageLayer import QtImageLayer from ._markersLayer import QtMarkersLayer from vispy import app app.use_app('pyqt5') del app
''' This code is modified from https://github.com/wadimkehl/ssd-6d.git ''' import numpy as np from vispy import app, gloo import OpenGL.GL as gl app.use_app('pyglet') # Set backend _vertex_code_colored = """ uniform mat4 u_mv; uniform mat4 u_mvp; uniform vec3 u_light_eye_pos; attribute vec3 a_position; attribute vec3 a_color; varying vec3 v_color; varying vec3 v_eye_pos; varying vec3 v_L; void main() { gl_Position = u_mvp * vec4(a_position, 1.0); v_color = a_color; v_eye_pos = (u_mv * vec4(a_position, 1.0)).xyz; // Vertex position in eye coordinates v_L = normalize(u_light_eye_pos - v_eye_pos); // Vector to the light } """
def main(args=None): p = ParserCreator() if args is None: args = sys.argv[1:] elif isinstance(args, string_types): args = args.split(' ') args = p.parse(args) if args is None: return if args.profiler or args.line_profiler: from phy.utils.testing import _enable_profiler, _profile prof = _enable_profiler(args.line_profiler) else: prof = None import phy if args.debug: phy.debug() # Hide the traceback. if args.hide_traceback: def exception_handler(exception_type, exception, traceback): print("{}: {}".format(exception_type.__name__, exception)) sys.excepthook = exception_handler # Activate IPython debugger. if args.pdb: from IPython.core import ultratb sys.excepthook = ultratb.FormattedTB(mode='Verbose', color_scheme='Linux', call_pdb=1, ) func = args.func if func is None: p.parser.print_help() return out = func(args) if not out: return cmd, ns = out if not cmd: return requires_qt = ns.pop('requires_qt', False) requires_vispy = ns.pop('requires_vispy', False) # Default variables in namespace. ns.update(phy=phy, path=args.file) if 'session' in ns: ns['model'] = ns['session'].model # Interactive mode with IPython. if args.ipython: print("\nStarting IPython...") from IPython import start_ipython args_ipy = ["-i", "-c='{}'".format(cmd)] if requires_qt or requires_vispy: # Activate Qt event loop integration with Qt. args_ipy += ["--gui=qt"] start_ipython(args_ipy, user_ns=ns) else: if not prof: exec_(cmd, {}, ns) else: _profile(prof, cmd, {}, ns) if requires_qt: # Launch the Qt app. from phy.gui import run_qt_app run_qt_app() elif requires_vispy: # Launch the VisPy Qt app. from vispy.app import use_app, run use_app('pyqt4') run()
def _test_module_properties(_module=None): """Test application module""" if _module is None: app = use_app() _module = app.backend_module # Test that the keymap contains all keys supported by vispy. module_fname = _module.__name__.split('.')[-1] if module_fname != '_egl': # skip keys for EGL keymap = _module.KEYMAP vispy_keys = keymap.values() for keyname in dir(keys): if keyname.upper() != keyname: continue key = getattr(keys, keyname) assert_in(key, vispy_keys) # For Qt backend, we have a common implementation alt_modname = '' if module_fname in ('_pyside', '_pyqt4', '_pyqt5'): alt_modname = _module.__name__.rsplit('.', 1)[0] + '._qt' # Test that all _vispy_x methods are there. exceptions = ( '_vispy_get_native_canvas', '_vispy_get_native_timer', '_vispy_get_native_app', '_vispy_reuse', '_vispy_mouse_move', '_vispy_mouse_press', '_vispy_mouse_release', '_vispy_mouse_double_click', '_vispy_detect_double_click', '_vispy_get_geometry', '_vispy_get_physical_size', '_process_backend_kwargs') # defined in base class class KlassRef(vispy.app.base.BaseCanvasBackend): def __init__(self, *args, **kwargs): pass # Do not call the base class, since it will check for Canvas Klass = _module.CanvasBackend base = KlassRef() for key in dir(KlassRef): if not key.startswith('__'): method = getattr(Klass, key) if key not in exceptions: print(key) args = [None] * (len(getargspec(method).args) - 1) assert_raises(NotImplementedError, getattr(base, key), *args) if hasattr(method, '__module__'): mod_str = method.__module__ # Py3k else: mod_str = method.im_func.__module__ assert_in(mod_str, (_module.__name__, alt_modname), "Method %s.%s not defined in %s" % (Klass, key, _module.__name__)) Klass = _module.TimerBackend KlassRef = vispy.app.timer.TimerBackend for key in dir(KlassRef): if not key.startswith('__'): method = getattr(Klass, key) if key not in exceptions: if hasattr(method, '__module__'): # Py3k assert_in(method.__module__, (_module.__name__, alt_modname)) else: t = method.im_func.__module__ == _module.__name__ assert t Klass = _module.ApplicationBackend KlassRef = vispy.app.application.ApplicationBackend for key in dir(KlassRef): if not key.startswith('__'): method = getattr(Klass, key) if key not in exceptions: if hasattr(method, '__module__'): # Py3k assert_in(method.__module__, (_module.__name__, alt_modname)) else: t = method.im_func.__module__ == _module.__name__ assert t # Test that all events seem to be emitted. # Get text fname = _module.__file__.rstrip('c') # "strip" will break windows! with open(fname, 'rb') as fid: text = fid.read().decode('utf-8') canvas = vispy.app.Canvas(create_native=False, app=DummyApplication()) # Stylus and touch are ignored because they are not yet implemented. # Mouse events are emitted from the CanvasBackend base class. ignore = set(['stylus', 'touch', 'mouse_press', 'paint', 'mouse_move', 'mouse_release', 'mouse_double_click', 'detect_double_click', 'close']) if module_fname == '_egl': ignore += ['key_release', 'key_press'] eventNames = set(canvas.events._emitters.keys()) - ignore if not alt_modname: # Only check for non-proxy modules for name in eventNames: assert_in('events.%s' % name, text, 'events.%s does not appear in %s' % (name, fname))
# -*- coding: utf-8 -*- """ A GLSL sandbox application based on the spinning cube. Requires PySide or PyQt4. """ from vispy.geometry.generation import create_sphere import numpy as np from vispy import app, gloo from vispy.io import read_mesh, load_data_file, load_crate from vispy.util.transforms import perspective, translate, rotate from vispy.color import Color, ColorArray, get_colormap from vispy.visuals.shaders import ModularProgram, Function # Force using qt and take QtCore+QtGui from backend module try: app_object = app.use_app('pyqt4') except Exception: app_object = app.use_app('pyside') QtCore = app_object.backend_module.QtCore, QtGui = app_object.backend_module.QtGui VERT_CODE = """ // Uniforms // ------------------------------------ uniform mat4 u_model; uniform mat4 u_view; uniform mat4 u_projection; uniform vec4 u_color; // Attributes
def canvas(qapp): use_app('pyqt4') c = BaseCanvas(keys='interactive') yield c c.close()
def _test_module_properties(_module=None): """Test application module""" if _module is None: app = use_app() _module = app.backend_module # Test that the keymap contains all keys supported by vispy. module_fname = _module.__name__.split(".")[-1] if module_fname != "_egl": # skip keys for EGL keymap = _module.KEYMAP vispy_keys = keymap.values() for keyname in dir(keys): if keyname.upper() != keyname: continue key = getattr(keys, keyname) assert_in(key, vispy_keys) # For Qt backend, we have a common implementation alt_modname = "" if module_fname in ("_pyside", "_pyqt4"): alt_modname = _module.__name__.rsplit(".", 1)[0] + "._qt" # Test that all _vispy_x methods are there. exceptions = ( "_vispy_init", "_vispy_get_native_canvas", "_vispy_get_native_timer", "_vispy_get_native_app", "_vispy_mouse_move", "_vispy_mouse_press", "_vispy_mouse_release", "_vispy_get_geometry", "_process_backend_kwargs", ) # defined in base class Klass = _module.CanvasBackend KlassRef = vispy.app.base.BaseCanvasBackend base = KlassRef(None, None) for key in dir(KlassRef): if not key.startswith("__"): method = getattr(Klass, key) if key not in exceptions: print(key) args = [None] * (len(getargspec(method).args) - 1) assert_raises(NotImplementedError, getattr(base, key), *args) if hasattr(method, "__module__"): mod_str = method.__module__ # Py3k else: mod_str = method.im_func.__module__ assert_in( mod_str, (_module.__name__, alt_modname), "Method %s.%s not defined in %s" % (Klass, key, _module.__name__), ) Klass = _module.TimerBackend KlassRef = vispy.app.timer.TimerBackend for key in dir(KlassRef): if not key.startswith("__"): method = getattr(Klass, key) if key not in exceptions: if hasattr(method, "__module__"): # Py3k assert_in(method.__module__, (_module.__name__, alt_modname)) else: t = method.im_func.__module__ == _module.__name__ assert t Klass = _module.ApplicationBackend KlassRef = vispy.app.application.ApplicationBackend for key in dir(KlassRef): if not key.startswith("__"): method = getattr(Klass, key) if key not in exceptions: if hasattr(method, "__module__"): # Py3k assert_in(method.__module__, (_module.__name__, alt_modname)) else: t = method.im_func.__module__ == _module.__name__ assert t # Test that all events seem to be emitted. # Get text fname = _module.__file__.rstrip("c") # "strip" will break windows! with open(fname, "rb") as fid: text = fid.read().decode("utf-8") canvas = vispy.app.Canvas(create_native=False, app=DummyApplication()) # Stylus and touch are ignored because they are not yet implemented. # Mouse events are emitted from the CanvasBackend base class. ignore = set(["stylus", "touch", "mouse_press", "paint", "mouse_move", "mouse_release", "close"]) if module_fname == "_egl": ignore += ["key_release", "key_press"] eventNames = set(canvas.events._emitters.keys()) - ignore if not alt_modname: # Only check for non-proxy modules for name in eventNames: assert_in("events.%s" % name, text, "events.%s does not appear in %s" % (name, fname))
#!/usr/bin/env python # -*- coding: utf-8 -*- """ A GLSL sandbox application based on the spinning cube. Requires PySide or PyQt4. """ import numpy as np from vispy import app, gloo from vispy.io import read_mesh, load_data_file, load_crate from vispy.util.transforms import perspective, translate, rotate # Force using qt and take QtCore+QtGui from backend module try: app_object = app.use_app("pyqt4") except Exception: app_object = app.use_app("pyside") QtCore = (app_object.backend_module.QtCore,) QtGui = app_object.backend_module.QtGui VERT_CODE = """ uniform mat4 u_model; uniform mat4 u_view; uniform mat4 u_projection; attribute vec3 a_position; attribute vec2 a_texcoord; varying vec2 v_texcoord;
def test_application(): """Test application running""" app = use_app() print(app) # __repr__ without app app.create() wrong = 'glut' if app.backend_name.lower() != 'glut' else 'pyglet' 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: assert_true(canvas.create_native() is None) # should be done already assert_is(canvas.app, app) assert_true(canvas.native) assert_equal('swap_buffers', canvas.events.draw.callback_refs[-1]) canvas.measure_fps(0.001) sleep(0.002) canvas.update() app.process_events() assert_true(canvas.fps > 0) # Other methods print(canvas) # __repr__ assert_equal(canvas.title, title) canvas.title = 'you' with use_log_level('warning', record=True, print_msg=False) as l: if app.backend_module.capability['position']: # todo: disable more tests based on capability canvas.position = pos canvas.size = size if 'ipynb_vnc' in canvas.app.backend_name.lower(): assert_true(len(l) >= 1) else: assert_true(len(l) == 0) canvas.connect(on_mouse_move) assert_raises(ValueError, canvas.connect, _on_mouse_move) if sys.platform != 'darwin': # XXX knownfail, prob. needs warmup canvas.show(False) canvas.show() app.process_events() assert_raises(ValueError, canvas.connect, on_nonexist) # deprecation of "paint" with use_log_level('info', record=True, print_msg=False) as log: olderr = sys.stderr try: with open(os.devnull, 'w') as fid: 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 (app.backend_name.lower() != 'glut' and # XXX knownfail for Almar sys.platform != 'win32'): # XXX knownfail for windows assert_array_equal(canvas.size, size) assert_equal(len(canvas.position), 2) # XXX knawnfail, doesn't "take" # GLOO: should have an OpenGL context already, so these should work vert = 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) 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
def test_multiple_canvases(): """Testing multiple canvases""" n_check = 3 app = use_app() if app.backend_name.lower() == "glut": raise SkipTest("glut cannot use multiple canvases") with Canvas(app=app, size=_win_size, title="same_0") as c0: with Canvas(app=app, size=_win_size, title="same_1") as c1: ct = [0, 0] @c0.events.draw.connect def draw0(event): ct[0] += 1 c0.update() @c1.events.draw.connect # noqa, analysis:ignore def draw1(event): ct[1] += 1 c1.update() c0.show() # ensure visible c1.show() c0.update() # force first draw c1.update() timeout = time() + 2.0 while (ct[0] < n_check or ct[1] < n_check) and time() < timeout: app.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=app, connect=on_timer, iterations=1, start=True) while not timer_ran and time() < timeout: app.process_events() assert_true(timer_ran) if app.backend_name.lower() == "wx": raise SkipTest("wx fails test #2") # XXX TODO Fix this kwargs = dict(app=app, autoswap=False, size=_win_size, show=True) with Canvas(title="0", **kwargs) as c0: with Canvas(title="1", **kwargs) as c1: bgcolors = [None] * 2 @c0.events.draw.connect def draw00(event): print(" {0:7}: {1}".format("0", bgcolors[0])) if bgcolors[0] is not None: gl.glViewport(0, 0, *list(_win_size)) gl.glClearColor(*bgcolors[0]) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glFinish() @c1.events.draw.connect def draw11(event): print(" {0:7}: {1}".format("1", bgcolors[1])) if bgcolors[1] is not None: gl.glViewport(0, 0, *list(_win_size)) gl.glClearColor(*bgcolors[1]) gl.glClear(gl.GL_COLOR_BUFFER_BIT) gl.glFinish() for ci, canvas in enumerate((c0, c1)): print("draw %s" % canvas.title) bgcolors[ci] = [0.5, 0.5, 0.5, 1.0] _update_process_check(canvas, 127) for ci, canvas in enumerate((c0, c1)): print("test") _update_process_check(canvas, 127, draw=False) bgcolors[ci] = [1.0, 1.0, 1.0, 1.0] _update_process_check(canvas, 255) bgcolors[ci] = [0.25, 0.25, 0.25, 0.25] _update_process_check(canvas, 64)
# Author: Tomas Hodan ([email protected]) # Center for Machine Perception, Czech Technical University in Prague import numpy as np from vispy import app, gloo import OpenGL.GL as gl # WARNING: doesn't work with Qt4 (update() does not call on_draw()??) app.use_app('PyGlet') # Set backend # Color vertex shader #------------------------------------------------------------------------------- _color_vertex_code = """ uniform mat4 u_mv; uniform mat4 u_mvp; uniform vec3 u_light_eye_pos; attribute vec3 a_position; attribute vec4 a_color; varying vec4 v_color; varying vec3 v_eye_pos; varying vec3 v_L; void main() { gl_Position = u_mvp * vec4(a_position, 1.0); v_color = a_color; v_eye_pos = (u_mv * vec4(a_position, 1.0)).xyz; // Vertex position in eye coordinates v_L = normalize(u_light_eye_pos - v_eye_pos); // Vector to the light } """
import numpy as np from vispy import app, gloo import OpenGL.GL as gl app.use_app('pyglet') # Set backend _vertex_code_colored = """ uniform mat4 u_mv; uniform mat4 u_mvp; uniform vec3 u_light_eye_pos; attribute vec3 a_position; attribute vec3 a_color; varying vec3 v_color; varying vec3 v_eye_pos; varying vec3 v_L; void main() { gl_Position = u_mvp * vec4(a_position, 1.0); v_color = a_color; v_eye_pos = (u_mv * vec4(a_position, 1.0)).xyz; // Vertex position in eye coordinates v_L = normalize(u_light_eye_pos - v_eye_pos); // Vector to the light } """ _fragment_code_colored = """ uniform float u_light_ambient_w;
def cube(im_in, azimuth=30., elevation=45., name=None, ext=ext, do_axis=True, show_label=True, cube_label = {'x':'x', 'y':'y', 't':'t'}, colormap='gray', roll=-180., vmin=0., vmax=1., figsize=figsize, **kwargs): """ Visualization of the stimulus as a cube """ if not(os.path.isdir(figpath)): os.mkdir(figpath) im = im_in.copy() N_X, N_Y, N_frame = im.shape fx, fy, ft = get_grids(N_X, N_Y, N_frame) import numpy as np from vispy import app, scene app.use_app('pyglet') from vispy.util.transforms import perspective, translate, rotate canvas = scene.SceneCanvas(size=figsize, bgcolor='white', dpi=450) view = canvas.central_widget.add_view() # frame = scene.visuals.Cube(size = (N_X/2, N_frame/2, N_Y/2), color=(0., 0., 0., 0.), # edge_color='k', # parent=view.scene) for p in ([1, 1, 1, -1, 1, 1], [1, 1, -1, -1, 1, -1], [1, -1, 1, -1, -1, 1],[1, -1, -1, -1, -1, -1], [1, 1, 1, 1, -1, 1], [-1, 1, 1, -1, -1, 1], [1, 1, -1, 1, -1, -1], [-1, 1, -1, -1, -1, -1], [1, 1, 1, 1, 1, -1], [-1, 1, 1, -1, 1, -1], [1, -1, 1, 1, -1, -1], [-1, -1, 1, -1, -1, -1]): # line = scene.visuals.Line(pos=np.array([[p[0]*N_Y/2, p[1]*N_X/2, p[2]*N_frame/2], [p[3]*N_Y/2, p[4]*N_X/2, p[5]*N_frame/2]]), color='black', parent=view.scene) line = scene.visuals.Line(pos=np.array([[p[0]*N_X/2, p[1]*N_frame/2, p[2]*N_Y/2], [p[3]*N_X/2, p[4]*N_frame/2, p[5]*N_Y/2]]), color='black', parent=view.scene) opts = {'parent':view.scene, 'cmap':'grays', 'clim':(0., 1.)} image_xy = scene.visuals.Image(np.rot90(im[:, :, 0], 3), **opts) tr_xy = scene.transforms.MatrixTransform() tr_xy.rotate(90, (1, 0, 0)) tr_xy.translate((-N_X/2, -N_frame/2, -N_Y/2)) image_xy.transform = tr_xy image_xt = scene.visuals.Image(np.fliplr(im[:, -1, :]), **opts) tr_xt = scene.transforms.MatrixTransform() tr_xt.rotate(90, (0, 0, 1)) tr_xt.translate((N_X/2, -N_frame/2, N_Y/2)) image_xt.transform = tr_xt image_yt = scene.visuals.Image(np.rot90(im[-1, :, :], 1), **opts) tr_yt = scene.transforms.MatrixTransform() tr_yt.rotate(90, (0, 1, 0)) tr_yt.translate((+N_X/2, -N_frame/2, N_Y/2)) image_yt.transform = tr_yt if do_axis: t = {} for text in ['x', 'y', 't']: t[text] = scene.visuals.Text(cube_label[text], parent=canvas.scene, face='Helvetica', color='black') t[text].font_size = 8 t['x'].pos = canvas.size[0] // 3, canvas.size[1] - canvas.size[1] // 8 t['t'].pos = canvas.size[0] - canvas.size[0] // 5, canvas.size[1] - canvas.size[1] // 6 t['y'].pos = canvas.size[0] // 12, canvas.size[1] // 2 cam = scene.TurntableCamera(elevation=35, azimuth=30) cam.fov = 45 cam.scale_factor = N_X * 1.7 if do_axis: margin = 1.3 else: margin = 1 cam.set_range((-N_X/2, N_X/2), (-N_Y/2*margin, N_Y/2/margin), (-N_frame/2, N_frame/2)) view.camera = cam if not(name is None): im = canvas.render(size=figsize) app.quit() import vispy.io as io io.write_png(name + ext, im) else: app.quit() return im
from collections import OrderedDict from vispy import geometry from vispy import scene from vispy import app from vispy import visuals qtapp = app.use_app("pyqt4") QtCore = qtapp.backend_module.QtCore QtGui = qtapp.backend_module.QtGui __class__ = ["StructureWidget", "StructureViewer"] class StructureCanvas(scene.SceneCanvas): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def on_close(self, event): app.quit() super().on_close(event) class StructureViewer: """This viewer only use Vispy and automatic backend associated. Usage ----- >>> v = StructureViewer()
from .qt_dims import QtDims from .qt_layerlist import QtLayerList from ..resources import resources_dir from ..util.theme import template from ..util.misc import is_multichannel from ..util.keybindings import components_to_key_combo from ..util.io import read from .qt_controls import QtControls from .qt_layer_buttons import QtLayersButtons from .qt_console import QtConsole # set vispy application to the appropriate qt backend use_app(API_NAME) class QtViewer(QSplitter): with open(os.path.join(resources_dir, 'stylesheet.qss'), 'r') as f: raw_stylesheet = f.read() def __init__(self, viewer): super().__init__() QCoreApplication.setAttribute( Qt.AA_UseStyleSheetPropagationInWidgetStyles, True ) self.viewer = viewer self.dims = QtDims(self.viewer.dims)
Author: Penny Xuran Qian (NAOC/SAO) [email protected] Date: Feb 15, 2016 License: GPL Usage: running the code with 'python selection_vispy_github.py'. press '1' or '2' to switch between view mode and selection mode for lasso method and picking method, respectively. """ import sys import numpy as np from PyQt4 import QtGui, QtCore from vispy import app, scene from matplotlib import path app.use_app("pyqt4") def rectangle_vertice(center, height, width): # Borrow from _generate_vertices in vispy/visual/rectangle.py half_height = height / 2.0 half_width = width / 2.0 bias1 = np.ones(4) * half_width bias2 = np.ones(4) * half_height corner1 = np.empty([1, 3], dtype=np.float32) corner2 = np.empty([1, 3], dtype=np.float32) corner3 = np.empty([1, 3], dtype=np.float32) corner4 = np.empty([1, 3], dtype=np.float32)
""" __DEBUG__ = False from math import pi from scipy.ndimage import imread from vispy import app from vispy.gloo import clear, set_clear_color, set_viewport, Program from jinja2 import Template from wavesynlib.languagecenter.pysl.utils import hit_circle, hit_line from wavesynlib.languagecenter.pysl.constants import pi as PI_STR # The PyQt5 support of VisPy still has some problems. # Hence we use the GLFW backend here. app.use_app(backend_name='glfw') vertex = """ #version 420 attribute vec2 position; out vec2 texcoord; void main(){ gl_Position = vec4(position, 0.0, 1.0 ); texcoord = position; } """
def _test_module_properties(_module=None): """Test application module""" if _module is None: app = use_app() _module = app.backend_module # Test that the keymap contains all keys supported by vispy. module_fname = _module.__name__.split('.')[-1] if module_fname != '_egl': # skip keys for EGL keymap = _module.KEYMAP vispy_keys = keymap.values() for keyname in dir(keys): if keyname.upper() != keyname: continue key = getattr(keys, keyname) assert_in(key, vispy_keys) # For Qt backend, we have a common implementation alt_modname = '' if module_fname in ('_pyside', '_pyqt4', '_pyqt5'): alt_modname = _module.__name__.rsplit('.', 1)[0] + '._qt' # Test that all _vispy_x methods are there. exceptions = ('_vispy_get_native_canvas', '_vispy_get_native_timer', '_vispy_get_native_app', '_vispy_reuse', '_vispy_mouse_move', '_vispy_mouse_press', '_vispy_mouse_release', '_vispy_get_geometry', '_process_backend_kwargs' ) # defined in base class class KlassRef(vispy.app.base.BaseCanvasBackend): def __init__(self, *args, **kwargs): pass # Do not call the base class, since it will check for Canvas Klass = _module.CanvasBackend base = KlassRef() for key in dir(KlassRef): if not key.startswith('__'): method = getattr(Klass, key) if key not in exceptions: print(key) args = [None] * (len(getargspec(method).args) - 1) assert_raises(NotImplementedError, getattr(base, key), *args) if hasattr(method, '__module__'): mod_str = method.__module__ # Py3k else: mod_str = method.im_func.__module__ assert_in( mod_str, (_module.__name__, alt_modname), "Method %s.%s not defined in %s" % (Klass, key, _module.__name__)) Klass = _module.TimerBackend KlassRef = vispy.app.timer.TimerBackend for key in dir(KlassRef): if not key.startswith('__'): method = getattr(Klass, key) if key not in exceptions: if hasattr(method, '__module__'): # Py3k assert_in(method.__module__, (_module.__name__, alt_modname)) else: t = method.im_func.__module__ == _module.__name__ assert t Klass = _module.ApplicationBackend KlassRef = vispy.app.application.ApplicationBackend for key in dir(KlassRef): if not key.startswith('__'): method = getattr(Klass, key) if key not in exceptions: if hasattr(method, '__module__'): # Py3k assert_in(method.__module__, (_module.__name__, alt_modname)) else: t = method.im_func.__module__ == _module.__name__ assert t # Test that all events seem to be emitted. # Get text fname = _module.__file__.rstrip('c') # "strip" will break windows! with open(fname, 'rb') as fid: text = fid.read().decode('utf-8') canvas = vispy.app.Canvas(create_native=False, app=DummyApplication()) # Stylus and touch are ignored because they are not yet implemented. # Mouse events are emitted from the CanvasBackend base class. ignore = set([ 'stylus', 'touch', 'mouse_press', 'paint', 'mouse_move', 'mouse_release', 'close' ]) if module_fname == '_egl': ignore += ['key_release', 'key_press'] eventNames = set(canvas.events._emitters.keys()) - ignore if not alt_modname: # Only check for non-proxy modules for name in eventNames: assert_in('events.%s' % name, text, 'events.%s does not appear in %s' % (name, fname))
from PyQt5.QtWidgets import QApplication, QMainWindow import sys from PyQt5 import QtCore, QtGui, QtWidgets import time import numpy as np from vispy import app import vispy from PyQt5.QtWidgets import * import vispy.app import sys from vispy.app import use_app use_app('PyQt5') from vispy import scene from vispy import color from vispy.color.colormap import Colormap import h5py import imageio from vispy import visuals import tensorly as tl from tensorly.decomposition import tucker from tensorly import tucker_to_tensor class Canvas(scene.SceneCanvas): def __init__(self):
import sys import numpy as np from PyQt4 import QtGui, QtCore from vispy import app, scene from matplotlib import path import pyfits from astropy.io import fits from astropy.utils.data import get_pkg_data_filename from multivol import MultiVolume from multivol import get_translucent_cmap import flood_fill_3d import math app.use_app('pyqt4') def rectangle_vertice(center, height, width): # Borrow from _generate_vertices in vispy/visuals/rectangle.py half_height = height / 2. half_width = width / 2. bias1 = np.ones(4) * half_width bias2 = np.ones(4) * half_height corner1 = np.empty([1, 3], dtype=np.float32) corner2 = np.empty([1, 3], dtype=np.float32) corner3 = np.empty([1, 3], dtype=np.float32) corner4 = np.empty([1, 3], dtype=np.float32)
import os import numpy as np from rendkit.envmap.io import unstack_cross, load_envmap, stack_cross from rendkit.envmap.prefilter import prefilter_irradiance from vispy import app from matplotlib import pyplot as plt _package_dir = os.path.dirname(os.path.realpath(__file__)) _resource_dir = os.path.join(_package_dir, '..', 'resources') _cubemap_dir = os.path.join(_resource_dir, 'cubemaps') app.use_app('glfw') def main(): app.Canvas(show=False) cube_faces = unstack_cross( stack_cross(load_envmap(os.path.join(_cubemap_dir, 'yokohama')))) irradiance_map = prefilter_irradiance(cube_faces) plt.imshow( np.vstack((stack_cross(cube_faces), stack_cross(irradiance_map)))) plt.show() if __name__ == '__main__': main()
1. Not showing the canvas (show=False). 2. Rendering to an FBO. 3. Manually triggering a rendering pass with self.update(). 4. Retrieving the scene with _screenshot(). 5. Closing the app after the first rendering pass (if that's the intended scenario). """ from vispy import gloo from vispy import app from vispy.util.ptime import time from vispy.gloo.util import _screenshot # WARNING: doesn't work with Qt4 (update() does not call on_draw()??) app.use_app('glfw') vertex = """ attribute vec2 position; void main() { gl_Position = vec4(position, 0, 1.0); } """ fragment = """ uniform vec2 resolution; uniform vec2 center; uniform float scale; uniform int iter;