repo
stringclasses
856 values
pull_number
int64
3
127k
instance_id
stringlengths
12
58
issue_numbers
sequencelengths
1
5
base_commit
stringlengths
40
40
patch
stringlengths
67
1.54M
test_patch
stringlengths
0
107M
problem_statement
stringlengths
3
307k
hints_text
stringlengths
0
908k
created_at
timestamp[s]
vispy/vispy
444
vispy__vispy-444
[ "426" ]
da8942dd91b753fe27d6a650d503614f27b6dd02
diff --git a/examples/basics/visuals/text_visual.py b/examples/basics/visuals/text_visual.py --- a/examples/basics/visuals/text_visual.py +++ b/examples/basics/visuals/text_visual.py @@ -15,11 +15,11 @@ def __init__(self): self.font_size = 48. self.text = Text('', bold=True) self.apply_zoom() - + def on_draw(self, event): gloo.clear(color='white') self.draw_visual(self.text) - + def on_mouse_wheel(self, event): """Use the mouse wheel to zoom.""" self.font_size *= 1.25 if event.delta[1] > 0 else 0.8 diff --git a/vispy/scene/visuals/text/text.py b/vispy/scene/visuals/text/text.py --- a/vispy/scene/visuals/text/text.py +++ b/vispy/scene/visuals/text/text.py @@ -12,9 +12,11 @@ import numpy as np from copy import deepcopy +from os import path as op from ._sdf import SDFRenderer -from ....gloo import TextureAtlas, set_state, IndexBuffer, VertexBuffer +from ....gloo import (TextureAtlas, set_state, IndexBuffer, VertexBuffer, + set_viewport, get_parameter) from ....gloo.wrappers import _check_valid from ....ext.six import string_types from ....util.fonts import _load_glyph @@ -36,6 +38,8 @@ class TextureFont(object): def __init__(self, font, renderer): self._atlas = TextureAtlas() self._atlas.wrapping = 'clamp_to_edge' + self._kernel = np.load(op.join(op.dirname(__file__), '..', '..', '..', + 'data', 'spatial-filters.npy')) self._renderer = renderer self._font = deepcopy(font) self._font['size'] = 256 # use high resolution point size for SDF @@ -131,6 +135,9 @@ def _text_to_vbo(text, font, anchor_x, anchor_y, lowres_size): width = height = ascender = descender = 0 ratio, slop = 1. / font.ratio, font.slop x_off = -slop + # Need to store the original viewport, because the font[char] will + # trigger SDF rendering, which changes our viewport + orig_viewport = get_parameter('viewport') for ii, char in enumerate(text): glyph = font[char] kerning = glyph['kerning'].get(prev, 0.) * ratio @@ -151,6 +158,7 @@ def _text_to_vbo(text, font, anchor_x, anchor_y, lowres_size): width += x_move height = max(height, glyph['size'][1] - 2*slop) prev = char + set_viewport(*orig_viewport) # Tight bounding box (loose would be width, font.height /.asc / .desc) width -= glyph['advance'] * ratio - (glyph['size'][0] - 2*slop) @@ -221,19 +229,116 @@ class Text(Visual): """ FRAGMENT_SHADER = """ + // Adapted from glumpy with permission + const float M_SQRT1_2 = 0.707106781186547524400844362104849039; + const float kernel_bias = -0.234377; + const float kernel_scale = 1.241974; + uniform sampler2D u_font_atlas; + uniform vec2 u_font_atlas_shape; uniform vec4 u_color; + uniform float u_npix; + uniform sampler2D u_kernel; varying vec2 v_texcoord; const float center = 0.5; + // CatRom interpolation code + vec4 filter1D_radius2(sampler2D kernel, float index, float x, + vec4 c0, vec4 c1, vec4 c2, vec4 c3) { + float w, w_sum = 0.0; + vec4 r = vec4(0.0,0.0,0.0,0.0); + w = texture2D(kernel, vec2(0.500000+(x/2.0),index) ).r; + w = w*kernel_scale + kernel_bias; + r += c0 * w; + w = texture2D(kernel, vec2(0.500000-(x/2.0),index) ).r; + w = w*kernel_scale + kernel_bias; + r += c2 * w; + w = texture2D(kernel, vec2(0.000000+(x/2.0),index) ).r; + w = w*kernel_scale + kernel_bias; + r += c1 * w; + w = texture2D(kernel, vec2(1.000000-(x/2.0),index) ).r; + w = w*kernel_scale + kernel_bias; + r += c3 * w; + return r; + } + + vec4 filter2D_radius2(sampler2D texture, sampler2D kernel, float index, + vec2 uv, vec2 pixel) { + vec2 texel = uv/pixel - vec2(0.0,0.0) ; + vec2 f = fract(texel); + texel = (texel-fract(texel)+vec2(0.001,0.001))*pixel; + vec4 t0 = filter1D_radius2(kernel, index, f.x, + texture2D( texture, texel + vec2(-1,-1)*pixel), + texture2D( texture, texel + vec2(0,-1)*pixel), + texture2D( texture, texel + vec2(1,-1)*pixel), + texture2D( texture, texel + vec2(2,-1)*pixel)); + vec4 t1 = filter1D_radius2(kernel, index, f.x, + texture2D( texture, texel + vec2(-1,0)*pixel), + texture2D( texture, texel + vec2(0,0)*pixel), + texture2D( texture, texel + vec2(1,0)*pixel), + texture2D( texture, texel + vec2(2,0)*pixel)); + vec4 t2 = filter1D_radius2(kernel, index, f.x, + texture2D( texture, texel + vec2(-1,1)*pixel), + texture2D( texture, texel + vec2(0,1)*pixel), + texture2D( texture, texel + vec2(1,1)*pixel), + texture2D( texture, texel + vec2(2,1)*pixel)); + vec4 t3 = filter1D_radius2(kernel, index, f.x, + texture2D( texture, texel + vec2(-1,2)*pixel), + texture2D( texture, texel + vec2(0,2)*pixel), + texture2D( texture, texel + vec2(1,2)*pixel), + texture2D( texture, texel + vec2(2,2)*pixel)); + return filter1D_radius2(kernel, index, f.y, t0, t1, t2, t3); + } + + vec4 CatRom(sampler2D texture, vec2 shape, vec2 uv) { + return filter2D_radius2(texture, u_kernel, 0.468750, + uv, 1.0/shape); + } + + float contour(in float d, in float w) + { + return smoothstep(center - w, center + w, d); + } + + float sample(sampler2D texture, vec2 uv, float w) + { + return contour(texture2D(texture, uv).r, w); + } + void main(void) { vec4 color = u_color; vec2 uv = v_texcoord.xy; - vec4 rgb = texture2D(u_font_atlas, uv); + vec4 rgb; + + // Use interpolation at high font sizes + if(u_npix >= 50.0) + rgb = CatRom(u_font_atlas, u_font_atlas_shape, uv); + else + rgb = texture2D(u_font_atlas, uv); float distance = rgb.r; - float width = fwidth(distance); - float alpha = smoothstep(center - width, center + width, distance); + + // GLSL's fwidth = abs(dFdx(uv)) + abs(dFdy(uv)) + float width = 0.5 * fwidth(distance); // sharpens a bit + + // Regular SDF + float alpha = contour(distance, width); + + if (u_npix < 30.) { + // Supersample, 4 extra points + // Half of 1/sqrt2; you can play with this + float dscale = 0.5 * M_SQRT1_2; + vec2 duv = dscale * (dFdx(v_texcoord) + dFdy(v_texcoord)); + vec4 box = vec4(v_texcoord-duv, v_texcoord+duv); + float asum = sample(u_font_atlas, box.xy, width) + + sample(u_font_atlas, box.zw, width) + + sample(u_font_atlas, box.xw, width) + + sample(u_font_atlas, box.zy, width); + // weighted average, with 4 extra points having 0.5 weight + // each, so 1 + 0.5*4 = 3 is the divisor + alpha = (alpha + 0.5 * asum) / 3.0; + } + gl_FragColor = vec4(color.rgb, color.a * alpha); } """ @@ -341,7 +446,10 @@ def draw(self, event=None): self._program.prepare() # Force ModularProgram to set shaders # todo: do some testing to verify that the scaling is correct - ps = (self._font_size / 72) * 92 + ps = (self._font_size / 72.) * 92. + self._program['u_npix'] = ps + self._program['u_font_atlas_shape'] = self._font._atlas.shape[:2] + self._program['u_kernel'] = self._font._kernel self._program['u_scale'] = ps * px_scale[0], ps * px_scale[1] self._program['u_rotation'] = self._rotation self._program['u_pos'] = self._pos
diff --git a/vispy/scene/visuals/tests/test_text.py b/vispy/scene/visuals/tests/test_text.py --- a/vispy/scene/visuals/tests/test_text.py +++ b/vispy/scene/visuals/tests/test_text.py @@ -1,31 +1,19 @@ # -*- coding: utf-8 -*- -from nose.tools import assert_equal - -from vispy.app import Canvas from vispy.scene.visuals import Text -from vispy import gloo -from vispy.testing import requires_application +from vispy.testing import (requires_application, TestingCanvas, + assert_image_equal) @requires_application() def test_text(): """Test basic text support""" - with Canvas(size=(100, 100)) as c: - text = Text('X', bold=True, font_size=30, color='w') - gloo.set_viewport(0, 0, *c.size) - gloo.clear(color=(0., 0., 0., 1.)) - text.draw() - - s = gloo.util._screenshot() - assert_equal(s.min(), 0) - assert_equal(s.max(), 255) - - # let's just peek at the texture, make sure it has something - gloo.clear(color=(0., 0., 0., 1.)) - gloo.util.draw_texture(text._font._atlas) - s = gloo.util._screenshot() - assert_equal(s.max(), 255) - assert_equal(s.min(), 0) - -if __name__ == '__main__': - test_text() + with TestingCanvas(bgcolor='w', size=(92, 92)) as c: + pos = [92 // 2] * 2 + text = Text('testing', font_size=20, color='k', + pos=pos, anchor_x='center', anchor_y='baseline') + c.draw_visual(text) + # This limit seems large, but the images actually match quite well... + # TODO: we should probably make more "modes" for assert_image_equal + # at some point + # Test image created in Illustrator CS5, 1"x1" output @ 92 DPI + assert_image_equal("screenshot", 'visuals/text1.png', limit=840) diff --git a/vispy/testing/_testing.py b/vispy/testing/_testing.py --- a/vispy/testing/_testing.py +++ b/vispy/testing/_testing.py @@ -13,8 +13,10 @@ import inspect import base64 try: - from nose.tools import nottest + from nose.tools import nottest, assert_equal, assert_true except ImportError: + assert_equal = assert_true = None + class nottest(object): def __init__(self, *args): pass # Avoid "object() takes no parameters" @@ -264,7 +266,7 @@ def _has_scipy(min_version): def requires_scipy(min_version='0.13'): return np.testing.dec.skipif(not _has_scipy(min_version), 'Requires Scipy version >= %s' % min_version) - + def _save_failed_test(data, expect, filename): commit, error = run_subprocess(['git', 'rev-parse', 'HEAD']) @@ -272,7 +274,7 @@ def _save_failed_test(data, expect, filename): name.insert(-1, commit.strip()) filename = '/'.join(name) host = 'data.vispy.org' - + # concatenate data, expect, and diff into a single image ds = data.shape es = expect.shape @@ -289,11 +291,11 @@ def _save_failed_test(data, expect, filename): img = np.empty(shape, dtype=np.ubyte) img[:] = 255 img[:ds[0], :ds[1], :ds[2]] = data - img[:es[0], ds[1]+1+es[1]:, :es[2]] = expect - + img[:es[0], ds[1]+1+es[1]:, :es[2]] = expect + png = make_png(img) conn = httplib.HTTPConnection(host) - req = urllib.urlencode({'name': filename, + req = urllib.urlencode({'name': filename, 'data': base64.b64encode(png)}) conn.request('POST', '/upload.py', req) response = conn.getresponse().read() @@ -304,7 +306,7 @@ def _save_failed_test(data, expect, filename): print(response) -def assert_image_equal(image, reference): +def assert_image_equal(image, reference, limit=40): """Downloads reference image and compares with image Parameters @@ -313,6 +315,8 @@ def assert_image_equal(image, reference): 'screenshot' or image data reference: str 'The filename on the remote ``test-data`` repository to download' + limit : int + Number of pixels that can differ in the image. """ from ..gloo.util import _screenshot from ..util.dataio import read_png @@ -320,9 +324,9 @@ def assert_image_equal(image, reference): if image == "screenshot": image = _screenshot(alpha=False) - ref = read_png(get_testing_file(reference)) + ref = read_png(get_testing_file(reference))[:, :, :3] - assert image.shape == ref.shape + assert_equal(image.shape, ref.shape) # check for minimum number of changed pixels, allowing for overall 1-pixel # shift in any direcion @@ -332,11 +336,12 @@ def assert_image_equal(image, reference): for j in range(3): a = image[slices[i], slices[j]] b = ref[slices[2-i], slices[2-j]] - diff = (a != b).sum() + diff = np.any(a != b, axis=2).sum() if diff < min_diff: min_diff = diff try: - assert min_diff <= 40 + assert_true(min_diff <= limit, + 'min_diff (%s) > %s' % (min_diff, limit)) except AssertionError: _save_failed_test(image, ref, reference) raise
Implement pixel hinting in text visual Would be nice to have pixel hinting such that text edges are more likely to land on a pixel boundary. In the image below, the two "1" glyphs have very different appearances due to their location relative to the pixel grid. ![anticipation1](https://cloud.githubusercontent.com/assets/940580/3980464/d40c5914-2862-11e4-8980-9348db2a9d0e.png) We might also consider better anialiasing methods--the one used appears just a bit soft to me.
Such hinting can lead to a jumpy appearance of text because it changes the distance between glyphs. I think Windows uses this technique, but e.g. OSX does not. You get consistent distances, at the cost of slightly more blurry text. I am +1 for improving the aa methods. ping @rougier Article about this topic, with links to posts by Jeff Atwood and Joel Spolsky: http://damieng.com/blog/2007/06/13/font-rendering-philosophies-of-windows-and-mac-os-x Hinting can only be applied on the horizontal direction and requires an accurate rastering engine (no way for SDF) See http://jcgt.org/published/0002/01/04/ However, for SDF, it is possible to improve rendering by using bicubic interpolation at big size and multi-samples at small sizes. See https://github.com/rougier/glumpy/blob/master/glumpy/shaders/sdf-glyph.frag +1 for using what @rougier posted, or something like it. It is likely that the SDF rendering could be greatly improved by someone who actually knew what they were doing (as opposed to me) :)
2014-08-22T00:18:16
vispy/vispy
447
vispy__vispy-447
[ "441" ]
ff3df1b9bfecbd4d9267c03f91de01cf241a429c
diff --git a/vispy/app/backends/_ipynb_vnc.py b/vispy/app/backends/_ipynb_vnc.py --- a/vispy/app/backends/_ipynb_vnc.py +++ b/vispy/app/backends/_ipynb_vnc.py @@ -18,7 +18,7 @@ BaseTimerBackend) from .. import Application, Canvas from ...util import logger -from ...util.event import Event # For timer +#from ...util.event import Event # For timer # Imports for screenshot # Perhaps we should refactor these to have just one import @@ -69,6 +69,9 @@ def _set_config(c): else: # Try importing IPython try: + import IPython + if IPython.version_info < (2,): + raise RuntimeError('ipynb_vnc backend need IPython version >= 2.0') from IPython.html.widgets import DOMWidget from IPython.utils.traitlets import Unicode, Int, Float, Bool from IPython.display import display, Javascript @@ -219,7 +222,7 @@ def _on_draw(self, event=None): # Handle initialization if not self._initialized: self._initialized = True - self._vispy_canvas.events.add(timer=Event) + #self._vispy_canvas.events.add(timer=Event) self._vispy_canvas.events.initialize() self._on_resize() @@ -305,7 +308,8 @@ def _gen_event(self, ev): if self._need_draw: self._on_draw() # Generate a timer event on every poll from JS - self._vispy_canvas.events.timer(type="timer") + # AK: no, just use app.Timer as usual! + #self._vispy_canvas.events.timer(type="timer") def _prepare_js(self): pkgdir = op.dirname(__file__)
Error "no module named widgets" when using ipynb examples ``` /home/luke/vispy/vispy/app/application.py in _use(self, backend_name) 158 if not try_others: 159 # Fail if user wanted to use a specific backend --> 160 raise RuntimeError(msg) 161 elif key in imported_toolkits: 162 # Warn if were unable to use an already imported toolkit RuntimeError: Could not import backend "ipynb_vnc": No module named widgets ``` Hints?
You have IPython 2.0+? No. Perhaps this should be detected and provide a more helpful error.. (ubuntu currently has 1.2.1, so there are bound to be many users with the same issue) +1, I thought it was already the case! I may do a PR later, unless @almarklein beats me to it... I doubt that I won't :) Euh.. I mean I doubt that I will
2014-08-22T20:02:12
vispy/vispy
463
vispy__vispy-463
[ "462" ]
3c09444377ef91ca313fce861d67263deec58ef9
diff --git a/vispy/util/fonts/_freetype.py b/vispy/util/fonts/_freetype.py --- a/vispy/util/fonts/_freetype.py +++ b/vispy/util/fonts/_freetype.py @@ -9,9 +9,6 @@ import sys import numpy as np -from ...ext.freetype import (FT_LOAD_RENDER, FT_LOAD_NO_HINTING, - FT_LOAD_NO_AUTOHINT, Face) - # Convert face to filename from ._vispy_fonts import _vispy_fonts, _get_vispy_font_filename @@ -25,7 +22,11 @@ _font_dict = {} +# Nest freetype imports in case someone doesn't have freetype on their system +# and isn't using fonts (Windows) + def _load_font(face, bold, italic): + from ...ext.freetype import Face key = '%s-%s-%s' % (face, bold, italic) if key in _font_dict: return _font_dict[key] @@ -40,6 +41,8 @@ def _load_font(face, bold, italic): def _load_glyph(f, char, glyphs_dict): """Load glyph from font into dict""" + from ...ext.freetype import (FT_LOAD_RENDER, FT_LOAD_NO_HINTING, + FT_LOAD_NO_AUTOHINT) flags = FT_LOAD_RENDER | FT_LOAD_NO_HINTING | FT_LOAD_NO_AUTOHINT face = _load_font(f['face'], f['bold'], f['italic']) face.set_char_size(f['size'] * 64)
Bug when running Vispy offline for the first time There appears to be a bug when you run Vispy offline and you don't have the freetype thing already downloaded. Not completely sure about the exact conditions responsible for the crash, require some testing...
If you're offline then it shouldn't be able to download the library, and it should give an error saying it couldn't import it. Is this what you mean by "crash"? I guess we should raise a clearer `ImportError` and say people either need to have Freetype installed and available on their system, or be connected to the internet. but what if I don't need to use freetype in my visualization? I may want to be able to use Vispy offline without showing text 2014-08-26 17:45 GMT+01:00 Eric89GXL [email protected]: > If you're offline then it shouldn't be able to download the library, and > it should give an error saying it couldn't import it. Is this what you mean > by "crash"? I guess we should raise a clearer ImportError and say people > either need to have Freetype installed and available on their system, or be > connected to the internet. > > — > Reply to this email directly or view it on GitHub > https://github.com/vispy/vispy/issues/462#issuecomment-53451389. Oh, right. Yes, in principle it should only give an error if you try to use `freetype` / fonts / text. I can open a PR for it. Do you have a suitable test setup?
2014-08-26T17:47:22
vispy/vispy
467
vispy__vispy-467
[ "459" ]
77c03dbafc65e8ac96bb99d2ac4a6ae3301110c1
diff --git a/vispy/gloo/program.py b/vispy/gloo/program.py --- a/vispy/gloo/program.py +++ b/vispy/gloo/program.py @@ -193,10 +193,12 @@ def _activate(self): # Check whether we need to rebuild shaders and create variables if any(s._need_compile for s in self.shaders): - self._build() + self._need_build = True # Stuff we need to do *before* glUse-ing the program + did_build = False if self._need_build: + did_build = True self._build() self._need_build = False @@ -205,6 +207,15 @@ def _activate(self): # Stuff we need to do *after* glUse-ing the program self._activate_variables() + + # Validate. We need to validate after textures units get assigned + # (glUniform1i() gets called in _update() in variable.py) + if did_build: + gl.glValidateProgram(self._handle) + if not gl.glGetProgramParameter(self._handle, + gl.GL_VALIDATE_STATUS): + print(gl.glGetProgramInfoLog(self._handle)) + raise RuntimeError('Program validation error') def _deactivate(self): """Deactivate the program.""" @@ -245,12 +256,6 @@ def _build(self): if not gl.glGetProgramParameter(self._handle, gl.GL_LINK_STATUS): print(gl.glGetProgramInfoLog(self._handle)) raise RuntimeError('Program linking error') - - # Validate - gl.glValidateProgram(self._handle) - if not gl.glGetProgramParameter(self._handle, gl.GL_VALIDATE_STATUS): - print(gl.glGetProgramInfoLog(self._handle)) - raise RuntimeError('Program validation error') # Now we know what variable will be used by the program self._enable_variables()
Error when using both 2D and 3D textures There seems to be a problem if one tries to use both a 2D and a 3D texture in a shader program. I uncovered this when trying to implement a basic volume rendering example, see https://github.com/vispy/vispy/pull/458. The example itself is https://github.com/izaid/vispy/blob/ray_cast/examples/basics/gloo/display_volume.py. Note specifically the fragment shader program RAYS_FRAG_SHADER. As currently written, the Python program works (but does nothing). If you comment out the line "texture3D(u_data, vec3(0, 0, 0));" in RAYS_FRAG_SHADER and uncomment the lines above involving "stop" and "u_stop", you should see a square of different colors. If you now uncomment the simple 3D texture fetch "texture3D(u_data, vec3(0, 0, 0));", you get an error that says: ## Validation Failed: Sampler error: Samplers of different types use the same texture image unit. - or - A sampler's texture unit is out of range (greater than max allowed or negative). ## I tried to sort this out myself, but failed. Is it possible that the textures are being bound to the same unit before validation, as discussed in http://www.opengl.org/discussion_boards/showthread.php/176366-Samplers-of-different-types-use-the-same-textur ?
I don't get this error on my Ubuntu/NVIDIA machine, which is strange. What OS / graphics card are you using? I can also try on my OSX NVIDIA machine, which seems to be pickier about GLSL datatypes. To be clear, do you have both texture2D and texture3D uncommented? I'm using OSX with Intel HD Graphics 4000. Yeah, I do. I'll try my OSX laptop now... Have you tried actually using all three? There seems to be a conflict where the variables get optimized out if they aren't actually used, and this screws up the `gloo` program's accounting. Wait, I still get the error on my machine... still trying to track it down. Tried using all 3, still get the error. I agree with you @izaid that we probably do indeed need to set the `glUniform1i`'s before validating the program. @almarklein you'll probably need to tackle this one. It seems like there are two options: 1. Add into line ~248 of `gloo/program.py` something that sets the `glUniform1i` parameter, which is currently done well after the `_build` step, once all the variables are parsed it eventually gets set on line 256 of `gloo/variable.py`. 2. Delay the validation of the program until after the variables are updated. This is not a good solution because it forces us to wait until the program is drawn to find errors. I have tried implementing (1) but have failed... @izaid is this urgent for you or can this wait until we get to #464? @almarklein FWIW this should break any code that uses 2D and 3D textures in the same program, which seems kind of bad... And whatever solution we figure out here (if we pursue it) should be useful for #464. That's true, though I suspect its not a common use-case since we have no volume rendering yet :) But yeah, I'll probably check this out this week :) It's urgent only in the sense that I can devote tomorrow and Thurs to volume rendering if we can fix it. :) (Otherwise I might have to cycle back to it later.) And buying a new laptop with a less picky graphics card isn't an option? :) I can get to it tomorrow afternoon. BTW, just got an email that you will be at the sprint this Sunday. Awesome! Cheers, thanks Almar! Yep, Cambridge is not too far away for me to come. Generally keen to help with VisPy's 3D features.
2014-08-27T13:30:13
vispy/vispy
473
vispy__vispy-473
[ "246" ]
6eac7af504e75781d7623d8c866016d7e8315444
diff --git a/vispy/gloo/wrappers.py b/vispy/gloo/wrappers.py --- a/vispy/gloo/wrappers.py +++ b/vispy/gloo/wrappers.py @@ -73,22 +73,18 @@ def _check_conversion(key, valid_dict): # Viewport, DepthRangef, CullFace, FrontFace, LineWidth, PolygonOffset # -def set_viewport(x, y, w, h): +def set_viewport(*args): """Set the OpenGL viewport This is a wrapper for gl.glViewport. Parameters ---------- - x : int - X coordinate. - y : int - Y coordinate. - w : int - Viewport width. - h : int - Viewport height. + x, y, w, h : int | tuple + X and Y coordinates, plus width and height. Can be passed in as + individual components, or as a single tuple with four values. """ + x, y, w, h = args[0] if len(args) == 1 else args gl.glViewport(int(x), int(y), int(w), int(h)) diff --git a/vispy/scene/visuals/text/_sdf.py b/vispy/scene/visuals/text/_sdf.py --- a/vispy/scene/visuals/text/_sdf.py +++ b/vispy/scene/visuals/text/_sdf.py @@ -251,12 +251,6 @@ def render_to_texture(self, data, texture, offset, size): size : tuple of int Size (w, h) to render inside the texture. """ - offset = np.array(offset) - size = np.array(size) - for x in (offset, size): - assert x.size == 2 and x.ndim == 1 - assert x.dtype.kind == 'i' - assert data.ndim == 2 and data.dtype == np.uint8 assert isinstance(texture, Texture2D) set_state(blend=False, depth_test=False) @@ -276,7 +270,7 @@ def render_to_texture(self, data, texture, offset, size): self.program_insert['u_neg_texture'] = edf_neg_tex self.fbo_to[-1].color_buffer = texture with self.fbo_to[-1]: - set_viewport(offset[0], offset[1], size[0], size[1]) + set_viewport(tuple(offset) + tuple(size)) self.program_insert.draw('triangle_strip') def _render_edf(self, orig_tex):
diff --git a/vispy/gloo/tests/test_use_gloo.py b/vispy/gloo/tests/test_use_gloo.py --- a/vispy/gloo/tests/test_use_gloo.py +++ b/vispy/gloo/tests/test_use_gloo.py @@ -32,7 +32,7 @@ def test_use_framebuffer(): rbo = ColorBuffer(shape=shape) fbo = FrameBuffer(color=fbo_tex) with Canvas(size=(100, 100)) as c: - set_viewport(0, 0, *c.size) + set_viewport((0, 0) + c.size) with fbo: draw_texture(orig_tex) draw_texture(fbo_tex)
Minor inconsistency in the number of arguments between gloo.set_clear_color and gloo.set_viewport `gloo.set_clear_color` accepts 1 tuple of 4 floats, but `gloo.set_viewport` accepts 4 floats. Might be slightly confusing?
I'm fine with it either way, PR welcome if others agree :) I think I prefer separate arguments, because `set_viewport(*args)` looks nicer than `set_clear_color((r, g, b, a))`. I forgot part of the motivation for `set_clear_color` taking a tuple is that it allows one to do `set_state(clear_color=(0, 0, 0, 0))` and the wrapping is very simple. Basically anything that works with `set_state` needs to take a single argument. Otherwise a special catch will need to go in the wrapper to check and distribute arguments. We can probably work out a clean solution under the hood if separate arguments is more intuitive for people. I actually just remembered a different (and probably better) motivation for `set_clear_color(color)` instead of `set_clear_color(r, g, b, a)`. The first will eventually be more pythonic / user-friendly soon, because one will be able to just do `set_clear_color('white')` once `vispy.colors` exists. I'm not sure if there is any analogous functionality planned for `set_viewport` (I doubt it), but that's an argument for changing `set_viewport` to be `set_viewport(view)` instead of `set_viewport(x, y, w, h)` for consistency. I have a slight preference for a single argument instead of 4. The point is essentially to have consistency between the methods. `set_viewport((x, y, w, h))` would be fine by me. +1. Are you volunteering to make a PR? :) Sure, @almarklein @rougier are you ok with this decision? Fine by me. Why not support both methods? ``` def foo(*x): if len(x)==1 and isinstance(x, tuple): x = x[0] ``` That's not the most elegant thing in the world (there should be only 1 way to do something), but why not. Maybe it could be implemented in a decorator? > That's not the most elegant thing in the world But `set_clear_color((r, g, b, a))` also looks a bit clumsy :) If I had to chose, I think I would prefer having four arguments, because if one has four values, it would look right, and if one had a tuple, one can use `set_clear_color(*clr)`. @almarklein but in the hopefully near future, one would just be able to say `set_clear_color('white')` once `vispy.colors` works. This is an argument for having a single input, which can be a string, vispy `Color`, tuple of floats, or whatever. Having separate arguments for each component is not very future-compatible. > Having separate arguments for each component is not very future-compatible. Ah, doh. You are right. Ok, then my preference is for allowing both, but I am ok if it is decided to support only single-arguments. It does look clumsy to have those double parentheses, but that's already the case in most NumPy functions, so people should be used to it already. ;) On Sat, May 10, 2014 at 4:14 PM, Eric89GXL [email protected] wrote: > @almarklein https://github.com/almarklein but in the hopefully near > future, one would just be able to say set_clear_color('white') once > vispy.colors works. This is an argument for having a single input, which > can be a string, vispy Color, tuple of floats, or whatever. Having > separate arguments for each component is not very future-compatible. > > Disagree--it is not at all difficult to ducktype between a string, a tuple, > and 3 or 4 integers. In pyqtgraph, all setColor methods have the same signature, which includes nearly every possible format you might conceive: ``` setColor(r, g, b) setColor(r, g, b, a) setColor((r, g, b)) setColor(ndarray) setColor(l) # luminance setColor('w') . . . ``` I am usually opposed to excessive ducktyping, but if the logical input to the function is _only_ a color, then it seems natural to allow that color to be specified in a variety of ways. On the other hand, there will be many other places in the package (probably most places?) where `color` is just one of multiple arguments, so in those places the colors will need to be passed as tuples if one uses `(r, g, b, a)` format. This would make our handling of colors inconsistent to allow `func(r, g, b, a)` for some functions (this one, maybe a few others), and have do something else (single input) everywhere else. So I'm still -1 on the multi-arguments. It would be good to get this fixed before 0.3 so that we don't need to make an API change. I can take care of it. It sounds like we have settled on one argument for `set_viewport` for consistency with other `gloo` functions like `set_clear_color`, is that still okay with people? cc @rossant @almarklein @lcampagn > we have settled on one argument for set_viewport for consistency with other gloo functions like set_clear_color, is that still okay with people? +1 I'm leaning towards allowing both syntaxes. Mainly because of the awkwardness of `set_viewport((x, y, w, h))`. It should be easy to implement both, I'll do that.
2014-08-27T16:12:11
vispy/vispy
476
vispy__vispy-476
[ "471" ]
6eac7af504e75781d7623d8c866016d7e8315444
diff --git a/vispy/__init__.py b/vispy/__init__.py --- a/vispy/__init__.py +++ b/vispy/__init__.py @@ -8,25 +8,13 @@ Vispy ===== -Vispy is a collaborative project that has the goal to allow more sharing -of code between visualization projects based on OpenGL. It does this -by providing powerful interfaces to OpenGL, at different levels of -abstraction and generality. - -Vispy consists of the following modules: - * vispy.app: for creating windows, timers and mainloops for various backends - * vispy.gloo: Object oriented GL API - * vispy.gloo.gl: Low level OpenGL API - * vispy.util: various utilities - * vispy.scene: Higher level visualization objects (work in progress) - * vispy.mpl_plot: matplotlib interface (work in progress) - * ... more to come - -Vispy comes with a powerful event system and a simple application -framework that works on multiple backends. This allows easy creation -of figures, and enables integrating visualizations in a GUI application. - -For more information see http://vispy.org. +Vispy is a **high-performance interactive 2D/3D data visualization +library**. Vispy leverages the computational power of modern **Graphics +Processing Units (GPUs)** through the **OpenGL** library to display very +large datasets. + +For more information, see http://vispy.org. + """ from __future__ import division
Adding more documentation Currently, we only have the API reference. There's no other documentation at the moment. Here are a few references we could take inspiration from/copy. - [@rougier's tutorial](http://www.loria.fr/~rougier/teaching/opengl/) - Recipe from the IPython Cookbook (link coming soon) - [Paper in Frontiers in Neuroinformatics](http://journal.frontiersin.org/Journal/10.3389/fninf.2013.00036/full)
2014-08-27T17:45:33
vispy/vispy
484
vispy__vispy-484
[ "461" ]
459886e62661fe4130f2f02c431baec37d89fd81
diff --git a/vispy/color/_color.py b/vispy/color/_color.py --- a/vispy/color/_color.py +++ b/vispy/color/_color.py @@ -79,6 +79,30 @@ def _array_clip_val(val): return val +############################################################################### +# RGB<->HEX conversion + +def _hex_to_rgba(hexs): + """Convert hex to rgba, permitting alpha values in hex""" + hexs = np.atleast_1d(np.array(hexs, '|U9')) + out = np.ones((len(hexs), 4), np.float32) + for hi, h in enumerate(hexs): + assert isinstance(h, string_types) + off = 1 if h[0] == '#' else 0 + assert len(h) in (6+off, 8+off) + e = (len(h)-off) // 2 + out[hi, :e] = [int(h[i:i+2], 16) / 255. + for i in range(off, len(h), 2)] + return out + + +def _rgb_to_hex(rgbs): + """Convert rgb to hex triplet""" + rgbs, n_dim = _check_color_dim(rgbs) + return np.array(['#%02x%02x%02x' % tuple((255*rgb[:3]).astype(np.uint8)) + for rgb in rgbs], '|U7') + + ############################################################################### # RGB<->HSV conversion @@ -313,7 +337,7 @@ def __getitem__(self, item): elif subrgba.ndim == 2: assert subrgba.shape[1] in (3, 4) return ColorArray(subrgba) - + def __setitem__(self, item, value): if isinstance(item, tuple): raise ValueError('ColorArray indexing is only allowed along ' @@ -322,7 +346,7 @@ def __setitem__(self, item, value): if isinstance(value, ColorArray): value = value.rgba self._rgba[item] = value - + # RGB(A) @property def rgba(self): @@ -384,6 +408,18 @@ def alpha(self, val): """Set the color using alpha""" self._rgba[:, 3] = _array_clip_val(val) + ########################################################################### + # HEX + @property + def hex(self): + """Numpy array with N elements, each one a hex triplet string""" + return _rgb_to_hex(self._rgba) + + @hex.setter + def hex(self, val): + """Set the color values using a list of hex strings""" + self.rgba = _hex_to_rgba(val) + ########################################################################### # HSV @property @@ -546,6 +582,10 @@ def RGB(self): def alpha(self): return super(Color, self).alpha[0] + @ColorArray.hex.getter + def hex(self): + return super(Color, self).hex[0] + @ColorArray.hsv.getter def hsv(self): return super(Color, self).hsv[0]
diff --git a/vispy/color/tests/test_color.py b/vispy/color/tests/test_color.py --- a/vispy/color/tests/test_color.py +++ b/vispy/color/tests/test_color.py @@ -21,6 +21,9 @@ def test_color(): 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) def test_color_array(): @@ -85,8 +88,9 @@ def test_color_interpretation(): r.alpha = 0 r.rgb = (1, 0, 0) assert_equal(r.alpha, 0) + assert_equal(r.hex, ['#ff0000']) r.alpha = 1 - r.rgb = 0, 1, 0 + r.hex = '00ff00' assert_equal(r, ColorArray('g')) assert_array_equal(r.rgb.ravel(), (0., 1., 0.)) r.RGB = 255, 0, 0
Adding .hex field to ColorArray Would be an array of string with the hexadecimal code of RGB values. Useful when dealing with HTML backend.
+1 PR welcome
2014-08-28T17:07:07
vispy/vispy
491
vispy__vispy-491
[ "481" ]
2eaa450507c20b87437483220298d3e53a3be5c6
diff --git a/make/make.py b/make/make.py --- a/make/make.py +++ b/make/make.py @@ -209,7 +209,7 @@ def images(self, arg): return self.help('images') # Create subdirs if needed - for subdir in ['gallery', 'thumbs', 'test']: + for subdir in ['gallery', 'thumbs', 'carousel', 'test']: subdir = op.join(IMAGES_DIR, subdir) if not op.isdir(subdir): os.mkdir(subdir) @@ -307,7 +307,7 @@ def grabscreenshot(event): # Get canvas if hasattr(m, 'canvas'): c = m.canvas # scene examples - elif hasattr(m, 'Canvas'): + elif hasattr(m, 'Canvas'): c = m.Canvas() else: print('Ignore: %s, no canvas' % name) @@ -334,16 +334,25 @@ def _images_thumbnails(self): import numpy as np gallery_dir = op.join(IMAGES_DIR, 'gallery') thumbs_dir = op.join(IMAGES_DIR, 'thumbs') + carousel_dir = op.join(IMAGES_DIR, 'carousel') for fname in os.listdir(gallery_dir): filename1 = op.join(gallery_dir, fname) filename2 = op.join(thumbs_dir, fname) + filename3 = op.join(carousel_dir, fname) # im = imread(filename1) + newx = 200 newy = int(newx * im.shape[0] / im.shape[1]) im = (resize(im, (newy, newx), 2) * 255).astype(np.uint8) imsave(filename2, im) - print('Created thumbnail %s' % fname) + + newy = 160 # This should match the carousel size! + newx = int(newy * im.shape[1] / im.shape[0]) + im = (resize(im, (newy, newx), 1) * 255).astype(np.uint8) + imsave(filename3, im) + + print('Created thumbnail and carousel %s' % fname) def copyright(self, arg): """ Update all copyright notices to the current year. @@ -421,12 +430,14 @@ def sphinx_clean(build_dir): def sphinx_build(src_dir, build_dir): import sphinx - sphinx.main(('sphinx-build', # Dummy - '-b', 'html', - '-d', op.join(build_dir, 'doctrees'), - src_dir, # Source - op.join(build_dir, 'html'), # Dest - )) + ret = sphinx.main(('sphinx-build', # Dummy + '-b', 'html', + '-d', op.join(build_dir, 'doctrees'), + src_dir, # Source + op.join(build_dir, 'html'), # Dest + )) + if ret != 0: + raise RuntimeError('Sphinx error: %s' % ret) print("Build finished. The HTML pages are in %s/html." % build_dir)
Add left/right arrows on the carousel
@Eric89GXL you want to do it? I'm not sure I'll have time to do it today. Hopefully we can make the release today... @rossant @almarklein if you can give me a link to the example you built the current carousel off of, I can give it a shot, yeah I found the relevant code. I'll see if I can figure it out. For future reference it lives in `_website/_scripts.py`
2014-08-29T19:19:49
vispy/vispy
527
vispy__vispy-527
[ "522" ]
28f9e083e35963050ba681478051aec87cb6e644
diff --git a/examples/basics/visuals/colored_line.py b/examples/basics/visuals/colored_line.py --- a/examples/basics/visuals/colored_line.py +++ b/examples/basics/visuals/colored_line.py @@ -15,6 +15,7 @@ from vispy.color import colormaps from vispy.scene import visuals from vispy.scene.transforms import STTransform +from vispy.ext.six import next colormaps = itertools.cycle(colormaps) @@ -30,7 +31,7 @@ def __init__(self): vispy.scene.SceneCanvas.__init__(self, keys='interactive', size=(400, 200), show=True) # Create a visual that updates the line with different colormaps - color = colormaps.next() + color = next(colormaps) self.line = visuals.Line(pos=pos, color=color, mode='gl') self.line.transform = STTransform(translate=[0, 140]) # redraw the canvas if the visual requests an update diff --git a/vispy/scene/visuals/line/line.py b/vispy/scene/visuals/line/line.py --- a/vispy/scene/visuals/line/line.py +++ b/vispy/scene/visuals/line/line.py @@ -169,6 +169,7 @@ class Line(Visual): color : Color, tuple, or array The color to use when drawing the line. If an array is given, it must be of shape (..., 4) and provide one rgba color per vertex. + Can also be a colormap name, or appropriate `Function`. width: The width of the line in px. Line widths > 1px are only guaranteed to work when using 'agg' mode. @@ -187,7 +188,7 @@ class Line(Visual): * "gl" uses OpenGL's built-in line rendering. This is much faster, but produces much lower-quality results and is not guaranteed to obey the requested line width or join/endcap styles. - antialias : bool + antialias : bool For mode='gl', specifies whether to use line smoothing or not. """ def __init__(self, pos=None, color=(0.5, 0.5, 0.5, 1), width=1, @@ -201,7 +202,7 @@ def __init__(self, pos=None, color=(0.5, 0.5, 0.5, 1), width=1, try: self._color = Function(get_colormap(color)) except KeyError: - self._color = Function(color) + self._color = ColorArray(color) elif isinstance(color, Function): self._color = Function(color) else: @@ -224,7 +225,7 @@ def __init__(self, pos=None, color=(0.5, 0.5, 0.5, 1), width=1, self._da = None self._U = None self._dash_atlas = None - + # now actually set the mode, which will call set_data self.mode = mode
Bug with text demo Ubuntu 14.04, Python 3.4, Intel GPU ``` cyrille@Cyrille-ASUS:~$ python git/vispy/examples/basics/scene/text.py Downloading data from https://github.com/vispy/demo-data/raw/master/fonts/OpenSans-Regular.ttf (212 kB) [........................................] 100.00000 \ downloading File saved as /home/cyrille/.vispy/data/fonts/OpenSans-Regular.ttf. #f006 WARNING: Traceback (most recent call last): File "git/vispy/examples/basics/scene/text.py", line 43, in <module> canvas.app.run() File "/home/cyrille/git/vispy/vispy/app/application.py", line 88, in run return self._backend._vispy_run() File "/home/cyrille/git/vispy/vispy/app/backends/_qt.py", line 175, in _vispy_run return app.exec_() File "/home/cyrille/git/vispy/vispy/app/backends/_qt.py", line 334, in paintGL self._vispy_canvas.events.draw(region=None) File "/home/cyrille/git/vispy/vispy/util/event.py", line 418, in __call__ self._invoke_callback(cb, event) File "/home/cyrille/git/vispy/vispy/util/event.py", line 446, in _invoke_callback self, cb_event=(cb, event)) << caught exception here: >> File "/home/cyrille/git/vispy/vispy/scene/shaders/function.py", line 464, in signature self._signature = parsing.parse_function_signature(self._code) File "/home/cyrille/git/vispy/vispy/scene/shaders/parsing.py", line 62, in parse_function_signature raise Exception("Failed to parse function signature. " Exception: Failed to parse function signature. Full code is printed above. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/home/cyrille/git/vispy/vispy/util/event.py", line 435, in _invoke_callback cb(event) File "/home/cyrille/git/vispy/vispy/scene/canvas.py", line 148, in on_draw self.draw_visual(self.scene) File "/home/cyrille/git/vispy/vispy/scene/canvas.py", line 181, in draw_visual visual.draw(scene_event) File "/home/cyrille/git/vispy/vispy/scene/subscene.py", line 41, in draw self.process_system(event, 'draw') File "/home/cyrille/git/vispy/vispy/scene/subscene.py", line 49, in process_system self._systems[system_name].process(event, self) File "/home/cyrille/git/vispy/vispy/scene/systems.py", line 22, in process self._process_entity(event, subscene, force_recurse=True) File "/home/cyrille/git/vispy/vispy/scene/systems.py", line 47, in _process_entity self._process_entity(event, sub_entity) File "/home/cyrille/git/vispy/vispy/scene/systems.py", line 33, in _process_entity _handle_exception(False, 'reminders', self, entity=entity) File "/home/cyrille/git/vispy/vispy/scene/systems.py", line 29, in _process_entity entity.draw(event) File "/home/cyrille/git/vispy/vispy/scene/widgets/viewbox.py", line 212, in draw self.scene.draw(event) File "/home/cyrille/git/vispy/vispy/scene/subscene.py", line 41, in draw self.process_system(event, 'draw') File "/home/cyrille/git/vispy/vispy/scene/subscene.py", line 49, in process_system self._systems[system_name].process(event, self) File "/home/cyrille/git/vispy/vispy/scene/systems.py", line 22, in process self._process_entity(event, subscene, force_recurse=True) File "/home/cyrille/git/vispy/vispy/scene/systems.py", line 47, in _process_entity self._process_entity(event, sub_entity) File "/home/cyrille/git/vispy/vispy/scene/systems.py", line 33, in _process_entity _handle_exception(False, 'reminders', self, entity=entity) File "/home/cyrille/git/vispy/vispy/scene/systems.py", line 29, in _process_entity entity.draw(event) File "/home/cyrille/git/vispy/vispy/scene/visuals/line/line.py", line 372, in draw self._gl_draw(event) File "/home/cyrille/git/vispy/vispy/scene/visuals/line/line.py", line 385, in _gl_draw '(gl_Position.x + 1.0) / 2.0') File "/home/cyrille/git/vispy/vispy/scene/shaders/function.py", line 456, in __call__ return FunctionCall(self, args) File "/home/cyrille/git/vispy/vispy/scene/shaders/function.py", line 926, in __init__ sig_len = len(function.args) File "/home/cyrille/git/vispy/vispy/scene/shaders/function.py", line 483, in args return self.signature[1] File "/home/cyrille/git/vispy/vispy/scene/shaders/function.py", line 466, in signature raise ValueError('Invalid code: ' + str(err)) ValueError: Invalid code: Failed to parse function signature. Full code is printed above. WARNING: Error invoking callback <bound method SceneCanvas.on_draw of <Vispy canvas (PyQt4 (qt) backend) at 0x7f2bd935ce48>> for event: <DrawEvent blocked=False handled=False native=None region=None source=<Vispy canvas (PyQt4 (qt) backend) at 0x7f2bd935ce48> sources=[<Vispy canvas (PyQt4 (qt) backend) at 0x7f2bd935ce48>] type=draw> #f006 WARNING: Error invoking callback <bound method SceneCanvas.on_draw of <Vispy canvas (PyQt4 (qt) backend) at 0x7f2bd935ce48>> repeat 2 #f006 WARNING: Error invoking callback <bound method SceneCanvas.on_draw of <Vispy canvas (PyQt4 (qt) backend) at 0x7f2bd935ce48>> repeat 3 ```
Ahh, this is because of the recent changes where `str` is interpreted as a colormap... argh. Generally a good idea to run through all of the examples before merging, it only takes a minute. Maybe we could add a unit test that just runs the examples and checks for exceptions..
2014-09-03T20:05:53
vispy/vispy
531
vispy__vispy-531
[ "528" ]
28f9e083e35963050ba681478051aec87cb6e644
diff --git a/examples/basics/gloo/post_processing.py b/examples/basics/gloo/post_processing.py --- a/examples/basics/gloo/post_processing.py +++ b/examples/basics/gloo/post_processing.py @@ -131,13 +131,14 @@ def on_draw(self, event): set_state(depth_test=True) self.cube.draw('triangles', self.indices) self.framebuffer.deactivate() + set_viewport(0, 0, *self.size) clear(color=True) set_state(depth_test=False) self.quad.draw('triangle_strip') def on_resize(self, event): self._set_projection(event.size) - + def _set_projection(self, size): width, height = size set_viewport(0, 0, width, height) diff --git a/examples/demo/gloo/realtime_signals.py b/examples/demo/gloo/realtime_signals.py --- a/examples/demo/gloo/realtime_signals.py +++ b/examples/demo/gloo/realtime_signals.py @@ -120,7 +120,7 @@ def __init__(self): app.Canvas.__init__(self, title='Use your wheel to zoom!', keys='interactive') self.program = gloo.Program(VERT_SHADER, FRAG_SHADER) - self.program['a_position'] = y.ravel() + self.program['a_position'] = y.reshape(-1, 1) self.program['a_color'] = color self.program['a_index'] = index self.program['u_scale'] = (1., 1.) diff --git a/examples/demo/gloo/spacy.py b/examples/demo/gloo/spacy.py --- a/examples/demo/gloo/spacy.py +++ b/examples/demo/gloo/spacy.py @@ -85,7 +85,7 @@ def __init__(self): # Set attributes self.program['a_position'] = np.zeros((N, 3), np.float32) - self.program['a_offset'] = np.zeros((N,), np.float32) + self.program['a_offset'] = np.zeros((N, 1), np.float32) # Init self._timeout = 0
Bug with realtime_signals example ``` cyrille@Cyrille-ASUS:~/git/vispy/examples/demo/gloo$ python realtime_signals.py ERROR: Could not set variable 'a_position' with value [-0.0093575 0.1638512 0.15590386 ..., 0.07139178 -0.14649338 0.06221156] Traceback (most recent call last): File "realtime_signals.py", line 162, in <module> c = Canvas() File "realtime_signals.py", line 123, in __init__ self.program['a_position'] = y.ravel() File "/home/cyrille/git/vispy/vispy/gloo/program.py", line 353, in __setitem__ self._attributes[name].set_data(data) File "/home/cyrille/git/vispy/vispy/gloo/variable.py", line 326, in set_data assert count == data.shape[1] IndexError: tuple index out of range ```
idem with spacy
2014-09-04T10:04:35
vispy/vispy
537
vispy__vispy-537
[ "536" ]
45e4b8f5a154d85390de9b5e6358c672ee9e28a0
diff --git a/examples/basics/scene/console.py b/examples/basics/scene/console.py --- a/examples/basics/scene/console.py +++ b/examples/basics/scene/console.py @@ -15,14 +15,14 @@ from vispy.scene.visuals import Text canvas = scene.SceneCanvas(keys='interactive', size=(400, 400)) -vb = scene.widgets.ViewBox(parent=canvas.scene, border_color='b') +grid = canvas.central_widget.add_grid() + +vb = scene.widgets.ViewBox(border_color='b') vb.camera.rect = -1, -1, 2, 2 +grid.add_widget(vb, row=0, col=0) text = Text('Starting timer...', color='w', font_size=24, parent=vb.scene) console = Console(text_color='g', font_size=12., border_color='g') - -grid = canvas.central_widget.add_grid() -grid.add_widget(vb, row=0, col=0) grid.add_widget(console, row=1, col=0) diff --git a/vispy/scene/canvas.py b/vispy/scene/canvas.py --- a/vispy/scene/canvas.py +++ b/vispy/scene/canvas.py @@ -99,10 +99,12 @@ def __init__(self, *args, **kwargs): self._transform_caches = weakref.WeakKeyDictionary() # Set up default entity stack: ndc -> fb -> canvas -> scene - self.render_cs = Entity() - self.framebuffer_cs = Entity(parent=self.render_cs) + self.render_cs = Entity(name="render_cs") + self.framebuffer_cs = Entity(parent=self.render_cs, + name="framebuffer_cs") self.framebuffer_cs.transform = STTransform() - self.canvas_cs = Entity(parent=self.framebuffer_cs) + self.canvas_cs = Entity(parent=self.framebuffer_cs, + name="canvas_cs") self.canvas_cs.transform = STTransform() # By default, the document coordinate system is the canvas. self.canvas_cs.document = self.canvas_cs diff --git a/vispy/scene/widgets/grid.py b/vispy/scene/widgets/grid.py --- a/vispy/scene/widgets/grid.py +++ b/vispy/scene/widgets/grid.py @@ -24,7 +24,27 @@ def __init__(self, **kwds): def add_widget(self, widget=None, row=None, col=None, row_span=1, col_span=1): """ - Add a new widget to this grid. + Add a new widget to this grid. This will cause other widgets in the + grid to be resized to make room for the new widget. + + Parameters + ---------- + widget : Widget + The Widget to add + row : int + The row in which to add the widget (0 is the topmost row) + col : int + The column in which to add the widget (0 is the leftmost column) + row_span : int + The number of rows to be occupied by this widget. Default is 1. + col_span : int + The number of columns to be occupied by this widget. Default is 1. + + Notes + ----- + + The widget's parent is automatically set to this grid, and all other + parent(s) are removed. """ if row is None: row = self._next_cell[0] @@ -37,7 +57,7 @@ def add_widget(self, widget=None, row=None, col=None, row_span=1, _row = self._cells.setdefault(row, {}) _row[col] = widget self._grid_widgets[widget] = row, col, row_span, col_span - widget.add_parent(self) + widget.parent = self self._next_cell = [row, col+col_span] self._update_child_widgets()
Bug with console example occurs when clicking in the window (tested on Windows) ``` WARNING: Traceback (most recent call last): File "examples/basics/scene/console.py", line 46, in <module> canvas.app.run() File "D:\Git\vispy\vispy\app\application.py", line 88, in run return self._backend._vispy_run() File "D:\Git\vispy\vispy\app\backends\_qt.py", line 175, in _vispy_run return app.exec_() File "D:\Git\vispy\vispy\app\backends\_qt.py", line 370, in mouseMoveEvent modifiers=self._modifiers(ev), File "D:\Git\vispy\vispy\app\base.py", line 201, in _vispy_mouse_move ev = self._vispy_canvas.events.mouse_move(**kwds) File "D:\Git\vispy\vispy\util\event.py", line 418, in __call__ self._invoke_callback(cb, event) File "D:\Git\vispy\vispy\util\event.py", line 446, in _invoke_callback self, cb_event=(cb, event)) << caught exception here: >> File "D:\Git\vispy\vispy\util\event.py", line 435, in _invoke_callback cb(event) File "D:\Git\vispy\vispy\scene\canvas.py", line 194, in _process_mouse_event self._scene._process_mouse_event(scene_event) File "D:\Git\vispy\vispy\scene\subscene.py", line 44, in _process_mouse_event self.process_system(event, 'mouse') File "D:\Git\vispy\vispy\scene\subscene.py", line 49, in process_system self._systems[system_name].process(event, self) File "D:\Git\vispy\vispy\scene\systems.py", line 63, in process self._process_entity(event, subscene) File "D:\Git\vispy\vispy\scene\systems.py", line 84, in _process_entity self._process_entity(event, sub_entity) File "D:\Git\vispy\vispy\scene\systems.py", line 84, in _process_entity self._process_entity(event, sub_entity) File "D:\Git\vispy\vispy\scene\systems.py", line 84, in _process_entity self._process_entity(event, sub_entity) File "D:\Git\vispy\vispy\scene\systems.py", line 76, in _process_entity deliver = entity.rect.contains(*event.press_event.pos[:2]) File "D:\Git\vispy\vispy\scene\events.py", line 332, in pos return self.map_from_canvas(self.mouse_event.pos) File "D:\Git\vispy\vispy\scene\events.py", line 191, in map_from_canvas return self.canvas_transform().imap(obj) File "D:\Git\vispy\vispy\scene\events.py", line 179, in canvas_transform return self.entity_transform(map_to=self.canvas_cs, map_from=entity) File "D:\Git\vispy\vispy\scene\events.py", line 273, in entity_transform (map_from, map_to)) RuntimeError: Unable to find unique path from <ViewBox at 0x753ad30> to <Entity at 0x7536c50> WARNING: Error invoking callback <bound method SceneCanvas._process_mouse_event of <Vispy canvas (PyQt4 (qt) backend) at 0x3aa4080L>> for event: <MouseEvent blo cked=False button=1 buttons=[1] delta=(0.0, 0.0) handled=False is_dragging=True last_event=<MouseEvent blocked=False button=1 buttons=[1] delta=(0.0, 0.0) handl ed=False is_dragging=False last_event=<...> modifiers=() native=<PyQt4.QtGui.QMo useEvent object at 0x00000000077149D8> pos=(258, 84) press_event=None source=Non e sources=[] type=mouse_press> modifiers=() native=<PyQt4.QtGui.QMouseEvent obje ct at 0x00000000077149D8> pos=(258, 85) press_event=<MouseEvent blocked=False bu tton=1 buttons=[1] delta=(0.0, 0.0) handled=False is_dragging=False last_event=< ...> modifiers=() native=<PyQt4.QtGui.QMouseEvent object at 0x00000000077149D8> pos=(258, 84) press_event=None source=None sources=[] type=mouse_press> source=< Vispy canvas (PyQt4 (qt) backend) at 0x3aa4080L> sources=[<Vispy canvas (PyQt4 ( qt) backend) at 0x3aa4080L>] type=mouse_move> WARNING: Traceback (most recent call last): File "examples/basics/scene/console.py", line 46, in <module> canvas.app.run() File "D:\Git\vispy\vispy\app\application.py", line 88, in run return self._backend._vispy_run() File "D:\Git\vispy\vispy\app\backends\_qt.py", line 175, in _vispy_run return app.exec_() File "D:\Git\vispy\vispy\app\backends\_qt.py", line 361, in mouseReleaseEvent modifiers = self._modifiers(ev), File "D:\Git\vispy\vispy\app\base.py", line 208, in _vispy_mouse_release ev = self._vispy_canvas.events.mouse_release(**kwds) File "D:\Git\vispy\vispy\util\event.py", line 418, in __call__ self._invoke_callback(cb, event) File "D:\Git\vispy\vispy\util\event.py", line 446, in _invoke_callback self, cb_event=(cb, event)) << caught exception here: >> File "D:\Git\vispy\vispy\util\event.py", line 435, in _invoke_callback cb(event) File "D:\Git\vispy\vispy\scene\canvas.py", line 194, in _process_mouse_event self._scene._process_mouse_event(scene_event) File "D:\Git\vispy\vispy\scene\subscene.py", line 44, in _process_mouse_event self.process_system(event, 'mouse') File "D:\Git\vispy\vispy\scene\subscene.py", line 49, in process_system self._systems[system_name].process(event, self) File "D:\Git\vispy\vispy\scene\systems.py", line 63, in process self._process_entity(event, subscene) File "D:\Git\vispy\vispy\scene\systems.py", line 84, in _process_entity self._process_entity(event, sub_entity) File "D:\Git\vispy\vispy\scene\systems.py", line 84, in _process_entity self._process_entity(event, sub_entity) File "D:\Git\vispy\vispy\scene\systems.py", line 84, in _process_entity self._process_entity(event, sub_entity) File "D:\Git\vispy\vispy\scene\systems.py", line 76, in _process_entity deliver = entity.rect.contains(*event.press_event.pos[:2]) File "D:\Git\vispy\vispy\scene\events.py", line 332, in pos return self.map_from_canvas(self.mouse_event.pos) File "D:\Git\vispy\vispy\scene\events.py", line 191, in map_from_canvas return self.canvas_transform().imap(obj) File "D:\Git\vispy\vispy\scene\events.py", line 179, in canvas_transform return self.entity_transform(map_to=self.canvas_cs, map_from=entity) File "D:\Git\vispy\vispy\scene\events.py", line 273, in entity_transform (map_from, map_to)) RuntimeError: Unable to find unique path from <ViewBox at 0x753ad30> to <Entity at 0x7536c50> WARNING: Error invoking callback <bound method SceneCanvas._process_mouse_event of <Vispy canvas (PyQt4 (qt) backend) at 0x3aa4080L>> for event: <MouseEvent blo cked=False button=1 buttons=[1] delta=(0.0, 0.0) handled=False is_dragging=True last_event=<MouseEvent blocked=False button=1 buttons=[1] delta=(0.0, 0.0) handl ed=False is_dragging=True last_event=<...> modifiers=() native=<PyQt4.QtGui.QMou seEvent object at 0x00000000077149D8> pos=(258, 85) press_event=<...> source=Non e sources=[] type=mouse_move> modifiers=() native=<PyQt4.QtGui.QMouseEvent objec t at 0x00000000077149D8> pos=(258, 85) press_event=<MouseEvent blocked=False but ton=1 buttons=[1] delta=(0.0, 0.0) handled=False is_dragging=False last_event=<. ..> modifiers=() native=<PyQt4.QtGui.QMouseEvent object at 0x00000000077149D8> p os=(258, 84) press_event=None source=None sources=[] type=mouse_press> source=<V ispy canvas (PyQt4 (qt) backend) at 0x3aa4080L> sources=[<Vispy canvas (PyQt4 (q t) backend) at 0x3aa4080L>] type=mouse_release> ```
Yep, this is a problem. @lcampagn I think it just has to do with the fact that it's a `Widget` (i.e., not specific to the console widget) -- any idea what this is about?
2014-09-05T16:56:29
vispy/vispy
540
vispy__vispy-540
[ "420" ]
45e4b8f5a154d85390de9b5e6358c672ee9e28a0
diff --git a/examples/demo/gloo/shadertoy.py b/examples/demo/gloo/shadertoy.py new file mode 100644 --- /dev/null +++ b/examples/demo/gloo/shadertoy.py @@ -0,0 +1,428 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# vispy: gallery 2 +# Copyright (c) 2014, Vispy Development Team. +# Distributed under the (new) BSD License. See LICENSE.txt for more info. + +""" +Shadertoy demo. You can copy-paste shader code from an example on +www.shadertoy.com and get the demo. + +TODO: support cubes and videos as channel inputs (currently, only images +are supported). + +""" + +import sys +from datetime import datetime, time +import numpy as np +from vispy import gloo +from vispy import app + + +vertex = """ +#version 120 + +attribute vec2 position; +void main() +{ + gl_Position = vec4(position, 0.0, 1.0); +} +""" + +fragment = """ +#version 120 + +uniform vec3 iResolution; // viewport resolution (in pixels) +uniform float iGlobalTime; // shader playback time (in seconds) +uniform vec4 iMouse; // mouse pixel coords +uniform vec4 iDate; // (year, month, day, time in seconds) +uniform float iSampleRate; // sound sample rate (i.e., 44100) +uniform sampler2D iChannel0; // input channel. XX = 2D/Cube +uniform sampler2D iChannel1; // input channel. XX = 2D/Cube +uniform sampler2D iChannel2; // input channel. XX = 2D/Cube +uniform sampler2D iChannel3; // input channel. XX = 2D/Cube +uniform vec3 iChannelResolution[4]; // channel resolution (in pixels) +uniform float iChannelTime[4]; // channel playback time (in seconds) + +%s +""" + + +def get_idate(): + now = datetime.now() + utcnow = datetime.utcnow() + midnight_utc = datetime.combine(utcnow.date(), time(0)) + delta = utcnow - midnight_utc + return (now.year, now.month, now.day, delta.seconds) + + +def noise(resolution=64, nchannels=1): + # Random texture. + return np.random.randint(low=0, high=256, + size=(resolution, resolution, nchannels) + ).astype(np.uint8) + + +class Canvas(app.Canvas): + + def __init__(self, shadertoy=None): + app.Canvas.__init__(self, keys='interactive') + if shadertoy is None: + shadertoy = """ + void main(void) + { + vec2 uv = gl_FragCoord.xy / iResolution.xy; + gl_FragColor = vec4(uv,0.5+0.5*sin(iGlobalTime),1.0); + }""" + self.program = gloo.Program(vertex, fragment % shadertoy) + + self.program["position"] = [(-1, -1), (-1, 1), (1, 1), + (-1, -1), (1, 1), (1, -1)] + + self.program['iSampleRate'] = 44100. + for i in range(4): + self.program['iChannelTime[%d]' % i] = 0. + self._timer = app.Timer('auto', connect=self.on_timer, start=True) + + def set_channel_input(self, img, i=0): + tex = gloo.Texture2D(img) + tex.interpolation = 'linear' + tex.wrapping = 'repeat' + self.program['iChannel%d' % i] = tex + self.program['iChannelResolution[%d]' % i] = img.shape + + def on_draw(self, event): + self.program.draw() + + def on_mouse_click(self, event): + # BUG: DOES NOT WORK YET, NO CLICK EVENT IN VISPY FOR NOW... + imouse = event.pos + event.pos + self.program['iMouse'] = imouse + + def on_mouse_move(self, event): + if event.is_dragging: + x, y = event.pos + px, py = event.press_event.pos + imouse = (x, self.size[1] - y, px, self.size[1] - py) + self.program['iMouse'] = imouse + + def on_timer(self, event): + self.program['iGlobalTime'] = event.elapsed + self.program['iDate'] = get_idate() + self.update() + + def on_resize(self, event): + width, height = event.size + gloo.set_viewport(0, 0, width, height) + self.program['iResolution'] = (width, height, 0.) + +# ------------------------------------------------------------------------- +# COPY-PASTE SHADERTOY CODE BELOW +# ------------------------------------------------------------------------- +SHADERTOY = """ +// From: https://www.shadertoy.com/view/MdX3Rr + +// Created by inigo quilez - iq/2013 +// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 +// Unported License. + +//stereo thanks to Croqueteer +//#define STEREO + +// value noise, and its analytical derivatives +vec3 noised( in vec2 x ) +{ + vec2 p = floor(x); + vec2 f = fract(x); + + vec2 u = f*f*(3.0-2.0*f); + + float a = texture2D(iChannel0,(p+vec2(0.5,0.5))/256.0,-100.0).x; + float b = texture2D(iChannel0,(p+vec2(1.5,0.5))/256.0,-100.0).x; + float c = texture2D(iChannel0,(p+vec2(0.5,1.5))/256.0,-100.0).x; + float d = texture2D(iChannel0,(p+vec2(1.5,1.5))/256.0,-100.0).x; + + return vec3(a+(b-a)*u.x+(c-a)*u.y+(a-b-c+d)*u.x*u.y, + 6.0*f*(1.0-f)*(vec2(b-a,c-a)+(a-b-c+d)*u.yx)); +} + +const mat2 m2 = mat2(0.8,-0.6,0.6,0.8); + +float terrain( in vec2 x ) +{ + vec2 p = x*0.003; + float a = 0.0; + float b = 1.0; + vec2 d = vec2(0.0); + for( int i=0; i<6; i++ ) + { + vec3 n = noised(p); + d += n.yz; + a += b*n.x/(1.0+dot(d,d)); + b *= 0.5; + p = m2*p*2.0; + } + + return 140.0*a; +} + +float terrain2( in vec2 x ) +{ + vec2 p = x*0.003; + float a = 0.0; + float b = 1.0; + vec2 d = vec2(0.0); + for( int i=0; i<14; i++ ) + { + vec3 n = noised(p); + d += n.yz; + a += b*n.x/(1.0+dot(d,d)); + b *= 0.5; + p=m2*p*2.0; + } + + return 140.0*a; +} + +float terrain3( in vec2 x ) +{ + vec2 p = x*0.003; + float a = 0.0; + float b = 1.0; + vec2 d = vec2(0.0); + for( int i=0; i<4; i++ ) + { + vec3 n = noised(p); + d += n.yz; + a += b*n.x/(1.0+dot(d,d)); + b *= 0.5; + p = m2*p*2.0; + } + + return 140.0*a; +} + +float map( in vec3 p ) +{ + float h = terrain(p.xz); + return p.y - h; +} + +float map2( in vec3 p ) +{ + float h = terrain2(p.xz); + return p.y - h; +} + +float interesct( in vec3 ro, in vec3 rd ) +{ + float h = 1.0; + float t = 1.0; + for( int i=0; i<120; i++ ) + { + if( h<0.01 || t>2000.0 ) break; + t += 0.5*h; + h = map( ro + t*rd ); + } + + if( t>2000.0 ) t = -1.0; + return t; +} + +float sinteresct(in vec3 ro, in vec3 rd ) +{ +#if 0 + // no shadows + return 1.0; +#endif + +#if 0 + // fake shadows + vec3 nor; + vec3 eps = vec3(20.0,0.0,0.0); + nor.x = terrain3(ro.xz-eps.xy) - terrain3(ro.xz+eps.xy); + nor.y = 1.0*eps.x; + nor.z = terrain3(ro.xz-eps.yx) - terrain3(ro.xz+eps.yx); + nor = normalize(nor); + return clamp( 4.0*dot(nor,rd), 0.0, 1.0 ); +#endif + +#if 1 + // real shadows + float res = 1.0; + float t = 0.0; + for( int j=0; j<48; j++ ) + { + vec3 p = ro + t*rd; + float h = map( p ); + res = min( res, 16.0*h/t ); + t += h; + if( res<0.001 ||p.y>300.0 ) break; + } + + return clamp( res, 0.0, 1.0 ); +#endif +} + +vec3 calcNormal( in vec3 pos, float t ) +{ + float e = 0.001; + e = 0.001*t; + vec3 eps = vec3(e,0.0,0.0); + vec3 nor; +#if 0 + nor.x = map2(pos+eps.xyy) - map2(pos-eps.xyy); + nor.y = map2(pos+eps.yxy) - map2(pos-eps.yxy); + nor.z = map2(pos+eps.yyx) - map2(pos-eps.yyx); +#else + nor.x = terrain2(pos.xz-eps.xy) - terrain2(pos.xz+eps.xy); + nor.y = 2.0*e; + nor.z = terrain2(pos.xz-eps.yx) - terrain2(pos.xz+eps.yx); +#endif + return normalize(nor); +} + +vec3 camPath( float time ) +{ + vec2 p = 1100.0*vec2( cos(0.0+0.23*time), cos(1.5+0.21*time) ); + + return vec3( p.x, 0.0, p.y ); +} + + +float fbm( vec2 p ) +{ + float f = 0.0; + + f += 0.5000*texture2D( iChannel0, p/256.0 ).x; p = m2*p*2.02; + f += 0.2500*texture2D( iChannel0, p/256.0 ).x; p = m2*p*2.03; + f += 0.1250*texture2D( iChannel0, p/256.0 ).x; p = m2*p*2.01; + f += 0.0625*texture2D( iChannel0, p/256.0 ).x; + + return f/0.9375; +} + + +void main(void) +{ + vec2 xy = -1.0 + 2.0*gl_FragCoord.xy / iResolution.xy; + + vec2 s = xy*vec2(iResolution.x/iResolution.y,1.0); + + #ifdef STEREO + float isCyan = mod(gl_FragCoord.x + mod(gl_FragCoord.y,2.0),2.0); + #endif + + float time = iGlobalTime*0.15 + 0.3 + 4.0*iMouse.x/iResolution.x; + + vec3 light1 = normalize( vec3(-0.8,0.4,-0.3) ); + + + + vec3 ro = camPath( time ); + vec3 ta = camPath( time + 3.0 ); + ro.y = terrain3( ro.xz ) + 11.0; + ta.y = ro.y - 20.0; + + float cr = 0.2*cos(0.1*time); + vec3 cw = normalize(ta-ro); + vec3 cp = vec3(sin(cr), cos(cr),0.0); + vec3 cu = normalize( cross(cw,cp) ); + vec3 cv = normalize( cross(cu,cw) ); + vec3 rd = normalize( s.x*cu + s.y*cv + 2.0*cw ); + + #ifdef STEREO + ro += 2.0*cu*isCyan; + #endif + + float sundot = clamp(dot(rd,light1),0.0,1.0); + vec3 col; + float t = interesct( ro, rd ); + if( t<0.0 ) + { + // sky + col = vec3(0.3,.55,0.8)*(1.0-0.8*rd.y); + col += 0.25*vec3(1.0,0.7,0.4)*pow( sundot,5.0 ); + col += 0.25*vec3(1.0,0.8,0.6)*pow( sundot,64.0 ); + col += 0.2*vec3(1.0,0.8,0.6)*pow( sundot,512.0 ); + vec2 sc = ro.xz + rd.xz*(1000.0-ro.y)/rd.y; + col = mix( col, vec3(1.0,0.95,1.0), + 0.5*smoothstep(0.5,0.8,fbm(0.0005*sc)) ); + } + else + { + // mountains + vec3 pos = ro + t*rd; + + vec3 nor = calcNormal( pos, t ); + + float r = texture2D( iChannel0, 7.0*pos.xz/256.0 ).x; + + col = (r*0.25+0.75)*0.9*mix( vec3(0.08,0.05,0.03), + vec3(0.10,0.09,0.08), texture2D(iChannel0,0.00007*vec2( + pos.x,pos.y*48.0)).x ); + col = mix( col, 0.20*vec3(0.45,.30,0.15)*(0.50+0.50*r), + smoothstep(0.70,0.9,nor.y) ); + col = mix( col, 0.15*vec3(0.30,.30,0.10)*(0.25+0.75*r), + smoothstep(0.95,1.0,nor.y) ); + + // snow + float h = smoothstep(55.0,80.0,pos.y + 25.0*fbm(0.01*pos.xz) ); + float e = smoothstep(1.0-0.5*h,1.0-0.1*h,nor.y); + float o = 0.3 + 0.7*smoothstep(0.0,0.1,nor.x+h*h); + float s = h*e*o; + col = mix( col, 0.29*vec3(0.62,0.65,0.7), smoothstep( + 0.1, 0.9, s ) ); + + // lighting + float amb = clamp(0.5+0.5*nor.y,0.0,1.0); + float dif = clamp( dot( light1, nor ), 0.0, 1.0 ); + float bac = clamp( 0.2 + 0.8*dot( normalize( + vec3(-light1.x, 0.0, light1.z ) ), nor ), 0.0, 1.0 ); + float sh = 1.0; if( dif>=0.0001 ) sh = sinteresct( + pos+light1*20.0,light1); + + vec3 lin = vec3(0.0); + lin += dif*vec3(7.00,5.00,3.00)*vec3( sh, sh*sh*0.5+0.5*sh, + sh*sh*0.8+0.2*sh ); + lin += amb*vec3(0.40,0.60,0.80)*1.5; + lin += bac*vec3(0.40,0.50,0.60); + col *= lin; + + + float fo = 1.0-exp(-0.0005*t); + vec3 fco = 0.55*vec3(0.55,0.65,0.75) + 0.1*vec3(1.0,0.8,0.5)*pow( + sundot, 4.0 ); + col = mix( col, fco, fo ); + + col += 0.3*vec3(1.0,0.8,0.4)*pow( sundot, + 8.0 )*(1.0-exp(-0.002*t)); + } + + col = pow(col,vec3(0.4545)); + + // vignetting + col *= 0.5 + 0.5*pow( (xy.x+1.0)*(xy.y+1.0)*(xy.x-1.0)*(xy.y-1.0), + 0.1 ); + + #ifdef STEREO + col *= vec3( isCyan, 1.0-isCyan, 1.0-isCyan ); + #endif + +// col *= smoothstep( 0.0, 2.0, iGlobalTime ); + + gl_FragColor=vec4(col,1.0); +} +""" +# ------------------------------------------------------------------------- + +canvas = Canvas(SHADERTOY) +# Input data. +canvas.set_channel_input(noise(resolution=256, nchannels=1), i=0) + +if __name__ == '__main__': + + canvas.show() + if sys.flags.interactive == 0: + canvas.app.run()
Add a shadertoy example in `examples/demo/gloo` This example should let one see shadertoy demos (like [this](https://www.shadertoy.com/view/MdlGW7) (omg)) by copying/pasting a shader directly from the website, or just by specifying a shadertoy identifier (like `MdlGW7`). Not sure how shadertoy processes the shaders exactly.
2014-09-06T17:07:13
vispy/vispy
544
vispy__vispy-544
[ "542" ]
1767548a6b82b2540fd3d177acf53779bd7e720c
diff --git a/vispy/app/canvas.py b/vispy/app/canvas.py --- a/vispy/app/canvas.py +++ b/vispy/app/canvas.py @@ -217,9 +217,10 @@ def toggle_fs(): self._keys_check = keys def keys_check(event): - use_name = event.key.name.lower() - if use_name in self._keys_check: - self._keys_check[use_name]() + if event.key is not None: + use_name = event.key.name.lower() + if use_name in self._keys_check: + self._keys_check[use_name]() self.events.key_press.connect(keys_check, ref=True) @property
Bug when pressing a weird button on the keyboard ``` WARNING: Traceback (most recent call last): File ".\examples\demo\gloo\brain.py", line 156, in <module> app.run() File "D:\Git\vispy\vispy\app\_default_app.py", line 54, in run return default_app.run() File "D:\Git\vispy\vispy\app\application.py", line 88, in run return self._backend._vispy_run() File "D:\Git\vispy\vispy\app\backends\_qt.py", line 175, in _vispy_run return app.exec_() File "D:\Git\vispy\vispy\app\backends\_qt.py", line 391, in keyPressEvent self._keyEvent(self._vispy_canvas.events.key_press, ev) File "D:\Git\vispy\vispy\app\backends\_qt.py", line 406, in _keyEvent func(native=ev, key=key, text=text_type(ev.text()), modifiers=mod) File "D:\Git\vispy\vispy\util\event.py", line 418, in __call__ self._invoke_callback(cb, event) File "D:\Git\vispy\vispy\util\event.py", line 446, in _invoke_callback self, cb_event=(cb, event)) << caught exception here: >> File "D:\Git\vispy\vispy\util\event.py", line 435, in _invoke_callback cb(event) File "D:\Git\vispy\vispy\app\canvas.py", line 220, in keys_check use_name = event.key.name.lower() AttributeError: 'NoneType' object has no attribute 'name' WARNING: Error invoking callback <function keys_check at 0x00000000067C73C8> for event: <KeyEvent blocked=False handled=False key=None modifiers=() native=<PyQt 4.QtGui.QKeyEvent object at 0x0000000007230BF8> source=<Vispy canvas (PyQt4 (qt) backend) at 0x72a10f0L> sources=[<Vispy canvas (PyQt4 (qt) backend) at 0x72a10f 0L>] text=² type=key_press> ```
Yep, I've seen that before, too. Haven't gotten around to fixing it, feel free if you have time. Yep, I've seen that before, too. Haven't gotten around to fixing it, feel free if you have time.
2014-09-08T14:59:32
vispy/vispy
622
vispy__vispy-622
[ "621" ]
2ef72931788932fc2d92c862e5152f59669a8bf9
diff --git a/vispy/visuals/shaders/compiler.py b/vispy/visuals/shaders/compiler.py --- a/vispy/visuals/shaders/compiler.py +++ b/vispy/visuals/shaders/compiler.py @@ -11,27 +11,27 @@ class Compiler(object): """ - Compiler is used to convert Function and Variable instances into + Compiler is used to convert Function and Variable instances into ready-to-use GLSL code. This class handles name mangling to ensure that there are no name collisions amongst global objects. The final name of each object may be retrieved using ``Compiler.__getitem__(obj)``. - + Accepts multiple root Functions as keyword arguments. ``compile()`` then returns a dict of GLSL strings with the same keys. - + Example:: - + # initialize with two main functions compiler = Compiler(vert=v_func, frag=f_func) - + # compile and extract shaders code = compiler.compile() v_code = code['vert'] f_code = code['frag'] - + # look up name of some object name = compiler[obj] - + """ def __init__(self, **shaders): # cache of compilation results for each function and variable @@ -40,38 +40,38 @@ def __init__(self, **shaders): def __getitem__(self, item): """ - Return the name of the specified object, if it has been assigned one. + Return the name of the specified object, if it has been assigned one. """ return self._object_names[item] def compile(self, pretty=True): - """ Compile all code and return a dict {name: code} where the keys + """ Compile all code and return a dict {name: code} where the keys are determined by the keyword arguments passed to __init__(). - + Parameters ---------- pretty : bool If True, use a slower method to mangle object names. This produces GLSL that is more readable. - If False, then the output is mostly unreadable GLSL, but is about + If False, then the output is mostly unreadable GLSL, but is about 10x faster to compile. - + """ # Authoritative mapping of {obj: name} self._object_names = {} - + # # 1. collect list of dependencies for each shader # - + # maps {shader_name: [deps]} self._shader_deps = {} - + for shader_name, shader in self.shaders.items(): this_shader_deps = [] self._shader_deps[shader_name] = this_shader_deps dep_set = set() - + for dep in shader.dependencies(sort=True): # visit each object no more than once per shader if dep.name is None or dep in dep_set: @@ -86,21 +86,20 @@ def compile(self, pretty=True): self._rename_objects_pretty() else: self._rename_objects_fast() - + # # 3. Now we have a complete namespace; concatenate all definitions # together in topological order. # compiled = {} obj_names = self._object_names - + for shader_name, shader in self.shaders.items(): - code = ['// Generated code by function composition', - '#version 120', ''] + code = [] for dep in self._shader_deps[shader_name]: dep_code = dep.definition(obj_names) if dep_code is not None: - # strip out version pragma if present; + # strip out version pragma if present; regex = r'#version (\d+)' m = re.search(regex, dep_code) if m is not None: @@ -110,17 +109,17 @@ def compile(self, pretty=True): "120 is supported.") dep_code = re.sub(regex, '', dep_code) code.append(dep_code) - + compiled[shader_name] = '\n'.join(code) - + self.code = compiled return compiled def _rename_objects_fast(self): - """ Rename all objects quickly to guaranteed-unique names using the + """ Rename all objects quickly to guaranteed-unique names using the id() of each object. - - This produces mostly unreadable GLSL, but is about 10x faster to + + This produces mostly unreadable GLSL, but is about 10x faster to compile. """ for shader_name, deps in self._shader_deps.items(): @@ -130,18 +129,18 @@ def _rename_objects_fast(self): ext = '_%x' % id(dep) name = name[:32-len(ext)] + ext self._object_names[dep] = name - + def _rename_objects_pretty(self): """ Rename all objects like "name_1" to avoid conflicts. Objects are - only renamed if necessary. - + only renamed if necessary. + This method produces more readable GLSL, but is rather slow. """ # # 1. For each object, add its static names to the global namespace # and make a list of the shaders used by the object. # - + # {name: obj} mapping for finding unique names # initialize with reserved keywords. self._global_ns = dict([(kwd, None) for kwd in gloo.util.KEYWORDS]) @@ -150,15 +149,15 @@ def _rename_objects_pretty(self): # for each object, keep a list of shaders the object appears in obj_shaders = {} - + for shader_name, deps in self._shader_deps.items(): for dep in deps: # Add static names to namespace for name in dep.static_names(): self._global_ns[name] = None - + obj_shaders.setdefault(dep, []).append(shader_name) - + # # 2. Assign new object names # @@ -178,15 +177,15 @@ def _rename_objects_pretty(self): if self._name_available(obj, new_name, shaders): self._assign_name(obj, new_name, shaders) break - + def _is_global(self, obj): - """ Return True if *obj* should be declared in the global namespace. - + """ Return True if *obj* should be declared in the global namespace. + Some objects need to be declared only in per-shader namespaces: functions, static variables, and const variables may all be given different definitions in each shader. """ - # todo: right now we assume all Variables are global, and all + # todo: right now we assume all Variables are global, and all # Functions are local. Is this actually correct? Are there any # global functions? Are there any local variables? from .function import Variable
Need to remove #version directive in shader composition system for the WebGL backend The shader composition system currently does not work in the WebGL backend, because `#version` is invalid in WebGL. It works if I remove [this](https://github.com/vispy/vispy/blob/master/vispy/visuals/shaders/compiler.py#L98-L99), but I guess it may break things on the desktop! What's the best way to tackle this @almarklein @lcampagn ?
I assume we can detect whether or not the GL backend is ES? If so, it should be sufficient to disable that line conditionally. Yes, I think we can remove it, because it's added by GLIR in the process of tweaking the GLSL for the implementation in use.
2014-11-15T11:29:04
vispy/vispy
626
vispy__vispy-626
[ "162" ]
ea4ed0723392bd106cc69ea3b4bd137ba2828db4
diff --git a/vispy/visuals/glsl/__init__.py b/vispy/visuals/glsl/__init__.py new file mode 100644 --- /dev/null +++ b/vispy/visuals/glsl/__init__.py @@ -0,0 +1 @@ +"""Repository of common GLSL functions.""" diff --git a/vispy/visuals/glsl/antialiasing.py b/vispy/visuals/glsl/antialiasing.py new file mode 100644 --- /dev/null +++ b/vispy/visuals/glsl/antialiasing.py @@ -0,0 +1,153 @@ +# Copyright (c) 2014, Nicolas P. Rougier. All Rights Reserved. +# Distributed under the (new) BSD License. + +"""Antialiasing GLSL functions.""" + + +# ----------------------------------------------------------------------------- +# Stroke +# ----------------------------------------------------------------------------- + +"""Compute antialiased fragment color for a stroke line. + +Inputs +------ + +distance (float): Signed distance to border (in pixels). + + +Template variables +------------------ + +linewidth (float): Stroke line width (in pixels). + +antialias (float): Stroke antialiased area (in pixels). + +stroke (vec4): Stroke color. + + +Outputs +------- +color (vec4): The final color. + + +""" +ANTIALIAS_STROKE = """ +vec4 stroke(float distance) +{ + vec4 frag_color; + float t = $linewidth/2.0 - $antialias; + float signed_distance = distance; + float border_distance = abs(signed_distance) - t; + float alpha = border_distance/$antialias; + alpha = exp(-alpha*alpha); + + if( border_distance < 0.0 ) + frag_color = $stroke; + else + frag_color = vec4($stroke.rgb, $stroke.a * alpha); + + return frag_color; +} +""" + + +# ----------------------------------------------------------------------------- +# Stroke +# ----------------------------------------------------------------------------- + +"""Compute antialiased fragment color for an outlined shape. + +Inputs +------ + +distance (float): Signed distance to border (in pixels). + + +Template variables +------------------ + +linewidth (float): Stroke line width (in pixels). + +antialias (float): Stroke antialiased area (in pixels). + +stroke (vec4): Stroke color. + +fill (vec4): Fill color. + + +Outputs +------- +color (vec4): The final color. + + +""" +ANTIALIAS_OUTLINE = """ +vec4 outline(float distance) +{ + vec4 frag_color; + float t = $linewidth/2.0 - $antialias; + float signed_distance = distance; + float border_distance = abs(signed_distance) - t; + float alpha = border_distance/$antialias; + alpha = exp(-alpha*alpha); + + if( border_distance < 0.0 ) + frag_color = $stroke; + else if( signed_distance < 0.0 ) + frag_color = mix($fill, $stroke, sqrt(alpha)); + else + frag_color = vec4($stroke.rgb, $stroke.a * alpha); + return frag_color; +} +""" + + +# ----------------------------------------------------------------------------- +# Filled +# ----------------------------------------------------------------------------- + +"""Compute antialiased fragment color for a filled shape. + +Inputs +------ + +distance (float): Signed distance to border (in pixels). + + +Template variables +------------------ + +linewidth (float): Stroke line width (in pixels). + +antialias (float): Stroke antialiased area (in pixels). + +fill (vec4): Fill color. + + +Outputs +------- +color (vec4): The final color. + + +""" +ANTIALIAS_FILLED = """ +vec4 filled(float distance) +{ + vec4 frag_color; + float t = $linewidth/2.0 - $antialias; + float signed_distance = distance; + float border_distance = abs(signed_distance) - t; + float alpha = border_distance/$antialias; + alpha = exp(-alpha*alpha); + + if( border_distance < 0.0 ) + frag_color = $fill; + else if( signed_distance < 0.0 ) + frag_color = $fill; + else + frag_color = vec4($fill.rgb, alpha * $fill.a); + + return frag_color; +} +""" diff --git a/vispy/visuals/glsl/color.py b/vispy/visuals/glsl/color.py new file mode 100644 --- /dev/null +++ b/vispy/visuals/glsl/color.py @@ -0,0 +1,40 @@ +"""Color-related GLSL functions.""" + + +# ----------------------------------------------------------------------------- +# Colormaps +# ----------------------------------------------------------------------------- + +"""Texture lookup for a discrete color map stored in a 1*ncolors 2D texture. + +The `get_color()` function returns a RGB color from an index integer +referring to the colormap. + + +Inputs +------ + +index (int): The color index. + + +Template variables +------------------ + +$ncolors (int): The number of colors in the colormap. + +$colormap (2D texture sampler): The sampler for the 2D 1*ncolors colormap + texture. + + +Outputs +------- + +color (vec3): The color. + +""" +COLORMAP_TEXTURE = """ +vec3 get_color(int index) { + float x = (float(index) + .5) / float($ncolors); + return texture2D($colormap, vec2(x, .5)).rgb; +} +"""
Create a repository of common shaders or shader templates The idea is to have a library of common shaders or shader snippets that would save us a lot of typing. For example, instead of writing trivial shaders such as ``` c void main(){ gl_FragColor = vec4(1., 1., 1., 1.); } ``` we could just write something like `vispy.shaderlib.frag_constant(color)`, etc. Idem for simple vertex shaders with just an attribute. There could be more complex snippets too, to sample from a texture in the fragment shader, to lookup a color in a texture colormap, etc. For 3D, we could have common lighting equations, model-view-projection matrices, etc. This could be in `vispy.shaders`, `vispy.shaderlib`, `vispy.shaders.lib`, or something else.
We currently have `vispy.scene.shaders`, which implements the shader function system. That might be the best place to begin accumulating useful functions. Not sure, this is the shader function system, which is distinct from a collection of reusable shaders (I think these should be strings rather than `Function` instances). @rougier puts them in [`glumpy.shaders`](https://github.com/rougier/glumpy/tree/master/glumpy/shaders), maybe we can use something similar (although `shaders` conflicts with `scene.shaders`). `vispy.glsl` would be a reasonable place to house basic / fundamental `glsl` code snippets And would they be `.glsl` files or `.py` files with a bunch of multi-line strings in them? Since we are talking of loads of snippets, I think I vote for the latter. `.py` files would make for convenient organizing methods, so +1 for that
2014-11-16T10:17:13
vispy/vispy
660
vispy__vispy-660
[ "659" ]
114d0b3d553decd66092fe687c9860d02f1b2476
diff --git a/vispy/app/backends/_glfw.py b/vispy/app/backends/_glfw.py --- a/vispy/app/backends/_glfw.py +++ b/vispy/app/backends/_glfw.py @@ -21,6 +21,7 @@ import atexit from time import sleep import gc +import os from ..base import (BaseApplicationBackend, BaseCanvasBackend, BaseTimerBackend) @@ -198,8 +199,12 @@ def _vispy_quit(self): def _vispy_get_native_app(self): global _GLFW_INITIALIZED if not _GLFW_INITIALIZED: - if not glfw.glfwInit(): # only ever call once - raise OSError('Could not init glfw') + cwd = os.getcwd() + try: + if not glfw.glfwInit(): # only ever call once + raise OSError('Could not init glfw') + finally: + os.chdir(cwd) atexit.register(glfw.glfwTerminate) _GLFW_INITIALIZED = True return glfw
GLFW Switches Directories on Initialization Other backends preserve the current working directory, but GLFW switches it (to the root of Python.app on OSX). This is a feature apparently: https://github.com/glfw/glfw/issues/174 Since we can't control how users compile GLFW, I propose saving the directory and restoring it after init to make sure this backend is consistent with others. (IMHO, working directories should not be changed.) Thoughts?
+1
2014-12-04T15:34:56
vispy/vispy
665
vispy__vispy-665
[ "664" ]
350ecd20c9b930ce6f6f17cb6e67bf294d219d83
diff --git a/vispy/app/backends/_glfw.py b/vispy/app/backends/_glfw.py --- a/vispy/app/backends/_glfw.py +++ b/vispy/app/backends/_glfw.py @@ -249,9 +249,9 @@ def __init__(self, *args, **kwargs): % len(monitor)) monitor = monitor[fs] use_size = glfw.glfwGetVideoMode(monitor)[:2] - if use_size != size: - logger.warning('Requested size %s, will be ignored to ' - 'use fullscreen mode %s' % (size, use_size)) + if use_size != tuple(size): + logger.debug('Requested size %s, will be ignored to ' + 'use fullscreen mode %s' % (size, use_size)) size = use_size else: self._fullscreen = False diff --git a/vispy/ext/glfw.py b/vispy/ext/glfw.py --- a/vispy/ext/glfw.py +++ b/vispy/ext/glfw.py @@ -73,7 +73,7 @@ def glfwGetVersion(): if version[0] != 3: version = '.'.join([str(v) for v in version]) - raise OSError('Need GLFW v3, found %s' % version) + raise OSError('Need GLFW library version 3, found version %s' % version) # --- Version ----------------------------------------------------------------- @@ -462,6 +462,7 @@ class GLFWmonitor(Structure): pass glfwGetProcAddress = _glfw.glfwGetProcAddress + # --- Pythonizer -------------------------------------------------------------- # This keeps track of current windows @@ -471,14 +472,13 @@ class GLFWmonitor(Structure): pass # This is to prevent garbage collection on callbacks __c_callbacks__ = {} __py_callbacks__ = {} - +__c_error_callback__ = None def glfwCreateWindow(width=640, height=480, title="GLFW Window", monitor=None, share=None): _glfw.glfwCreateWindow.restype = POINTER(GLFWwindow) window = _glfw.glfwCreateWindow(int(width), int(height), - title.encode('ASCII'), monitor, share) - assert window not in __windows__ + title.encode('utf-8'), monitor, share) __windows__.append(window) __destroyed__.append(False) index = __windows__.index(window) @@ -504,12 +504,12 @@ def glfwCreateWindow(width=640, height=480, title="GLFW Window", def glfwDestroyWindow(window): index = __windows__.index(window) if not __destroyed__[index]: - __destroyed__[index] = True # We do not delete window from the list (or it would impact numbering) __windows__[index] = None _glfw.glfwDestroyWindow(window) del __c_callbacks__[index] del __py_callbacks__[index] + __destroyed__[index] = True def glfwGetWindowPos(window): @@ -572,13 +572,13 @@ def glfwGetMonitorPhysicalSize(monitor): def glfwGetVideoMode(monitor): _glfw.glfwGetVideoMode.restype = POINTER(GLFWvidmode) - c_modes = _glfw.glfwGetVideoModes(monitor) - return (c_modes.width, - c_modes.height, - c_modes.redBits, - c_modes.blueBits, - c_modes.greenBits, - c_modes.refreshRate ) + c_mode = _glfw.glfwGetVideoMode(monitor).contents + return (c_mode.width, + c_mode.height, + c_mode.redBits, + c_mode.blueBits, + c_mode.greenBits, + c_mode.refreshRate ) def GetGammaRamp(monitor): @@ -625,7 +625,6 @@ def %(callback)s(window, callback = None): return old_callback""" % {'callback': callback, 'fun': fun} return code -exec(__callback__('Error')) exec(__callback__('Monitor')) exec(__callback__('WindowPos')) exec(__callback__('WindowSize')) @@ -639,3 +638,10 @@ def %(callback)s(window, callback = None): exec(__callback__('MouseButton')) exec(__callback__('CursorPos')) exec(__callback__('Scroll')) + + +# Error callback does not take window parameter +def glfwSetErrorCallback(callback = None): + global __c_error_callback__ + __c_error_callback__ = errorfun(callback) + _glfw.glfwSetErrorCallback(__c_error_callback__) \ No newline at end of file
GLFW crashes if fullscreen=<int> on OSX On OSX, I get at crash and a cryptic "Bus error: 10" when requesting full screen. I managed to get a callstack manually, it crashes calling `_glfw.glfwGetVideoModes(monitor)` here: ``` Traceback (most recent call last): File "vispy/scene/canvas.py", line 91, in __init__ app.Canvas.__init__(self, *args, **kwargs) File "vispy/app/canvas.py", line 171, in __init__ self.create_native() File "vispy/app/canvas.py", line 185, in create_native self._app.backend_module.CanvasBackend(self, **self._backend_kwargs) File "vispy/app/backends/_glfw.py", line 250, in __init__ use_size = glfw.glfwGetVideoMode(monitor)[:2] ``` Upgrading to the latest PyGLFW from @rougier 's repository prevents the crash, but it's missing some code: ``` File "/Users/alexjc/Development/ProjectTrains/vispy/vispy/ext/glfw.py", line 575, in glfwGetVideoMode return (c_mode.width, AttributeError: 'LP_GLFWvidmode' object has no attribute 'width' ``` What's the status of this dependency? Do you have any recommendations for upgrading it, selectively copying things?
Selectively copying things would probably be easiest. I'm not sure how many of the changes have gone either direction at this point :(
2014-12-06T07:27:44
vispy/vispy
673
vispy__vispy-673
[ "655" ]
902603b1386a17e205c1d715435ebcf64de9d8da
diff --git a/make/make.py b/make/make.py --- a/make/make.py +++ b/make/make.py @@ -79,6 +79,7 @@ def coverage_html(self, arg): from coverage import coverage cov = coverage(auto_data=False, branch=True, data_suffix=None, source=['vispy']) # should match testing/_coverage.py + cov.combine() cov.load() cov.html_report() print('Done, launching browser.') @@ -172,7 +173,7 @@ def website(self, arg): def test(self, arg): """ Run tests: * full - run all tests - * nose - run nose tests (also for each backend) + * unit - run tests (also for each backend) * any backend name (e.g. pyside, pyqt4, glut, sdl2, etc.) - run tests for the given backend * nobackend - run tests that do not require a backend
diff --git a/vispy/app/backends/tests/test_ipynb_util.py b/vispy/app/backends/tests/test_ipynb_util.py --- a/vispy/app/backends/tests/test_ipynb_util.py +++ b/vispy/app/backends/tests/test_ipynb_util.py @@ -2,12 +2,11 @@ # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np -from nose.tools import assert_equal from vispy.app.backends._ipynb_util import (_extract_buffers, _serialize_command, create_glir_message) -from vispy.testing import run_tests_if_main +from vispy.testing import run_tests_if_main, assert_equal def test_extract_buffers(): diff --git a/vispy/app/tests/test_app.py b/vispy/app/tests/test_app.py --- a/vispy/app/tests/test_app.py +++ b/vispy/app/tests/test_app.py @@ -4,12 +4,12 @@ from time import sleep from numpy.testing import assert_array_equal -from nose.tools import assert_equal, assert_true, assert_raises from vispy.app import use_app, Canvas, Timer, MouseEvent, KeyEvent from vispy.app.base import BaseApplicationBackend from vispy.testing import (requires_application, SkipTest, assert_is, - assert_in, run_tests_if_main) + assert_in, run_tests_if_main, + assert_equal, assert_true, assert_raises) from vispy.util import keys, use_log_level from vispy.gloo.program import (Program, VertexBuffer, IndexBuffer) diff --git a/vispy/app/tests/test_backends.py b/vispy/app/tests/test_backends.py --- a/vispy/app/tests/test_backends.py +++ b/vispy/app/tests/test_backends.py @@ -10,11 +10,10 @@ from inspect import getargspec -from nose.tools import assert_raises - import vispy from vispy import keys -from vispy.testing import requires_application, assert_in, run_tests_if_main +from vispy.testing import (requires_application, assert_in, run_tests_if_main, + assert_raises) from vispy.app import use_app, Application from vispy.app.backends import _template diff --git a/vispy/app/tests/test_context.py b/vispy/app/tests/test_context.py --- a/vispy/app/tests/test_context.py +++ b/vispy/app/tests/test_context.py @@ -1,8 +1,8 @@ import os import sys -from nose.tools import assert_equal, assert_raises -from vispy.testing import requires_application, SkipTest, run_tests_if_main +from vispy.testing import (requires_application, SkipTest, run_tests_if_main, + assert_equal, assert_raises) from vispy.app import Canvas, use_app from vispy.gloo import get_gl_configuration, Program from vispy.gloo.gl import check_error diff --git a/vispy/app/tests/test_interactive.py b/vispy/app/tests/test_interactive.py --- a/vispy/app/tests/test_interactive.py +++ b/vispy/app/tests/test_interactive.py @@ -1,6 +1,4 @@ -from nose.tools import assert_equal, assert_true, assert_false -from vispy.testing import assert_in, run_tests_if_main - +from vispy.testing import run_tests_if_main from vispy.app import set_interactive from vispy.ext.ipy_inputhook import inputhook_manager @@ -15,15 +13,15 @@ def test_interactive(): f = MockApp() set_interactive(enabled=True, app=f) - assert_equal('vispy', inputhook_manager._current_gui) - assert_true(f._in_event_loop) - assert_in('vispy', inputhook_manager.apps) - assert_equal(f, inputhook_manager.apps['vispy']) + assert inputhook_manager._current_gui == 'vispy' + assert f._in_event_loop + assert 'vispy' in inputhook_manager.apps + assert f == inputhook_manager.apps['vispy'] set_interactive(enabled=False) - assert_equal(None, inputhook_manager._current_gui) - assert_false(f._in_event_loop) + assert inputhook_manager._current_gui is None + assert not f._in_event_loop run_tests_if_main() diff --git a/vispy/app/tests/test_simultaneous.py b/vispy/app/tests/test_simultaneous.py --- a/vispy/app/tests/test_simultaneous.py +++ b/vispy/app/tests/test_simultaneous.py @@ -2,7 +2,6 @@ import numpy as np from numpy.testing import assert_allclose -from nose.tools import assert_true from time import sleep from vispy.app import use_app, Canvas, Timer @@ -70,8 +69,8 @@ def draw1(event): 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) + assert n_check <= ct[0] <= n_check + 1 + assert n_check <= ct[1] <= n_check + 1 # check timer global timer_ran @@ -85,7 +84,7 @@ def on_timer(_): app.process_events() sleep(0.2) app.process_events() - assert_true(timer_ran) + assert timer_ran if app.backend_name.lower() == 'wx': raise SkipTest('wx fails test #2') # XXX TODO Fix this diff --git a/vispy/color/tests/test_color.py b/vispy/color/tests/test_color.py --- a/vispy/color/tests/test_color.py +++ b/vispy/color/tests/test_color.py @@ -3,7 +3,6 @@ # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np -from nose.tools import assert_equal, assert_raises, assert_true from numpy.testing import assert_array_equal, assert_allclose from vispy.color import (Color, ColorArray, get_color_names, @@ -11,7 +10,8 @@ get_color_dict, get_colormap, get_colormaps) from vispy.visuals.shaders import Function from vispy.util import use_log_level -from vispy.testing import run_tests_if_main +from vispy.testing import (run_tests_if_main, assert_equal, assert_raises, + assert_true) def test_color(): diff --git a/vispy/gloo/gl/tests/test_basics.py b/vispy/gloo/gl/tests/test_basics.py --- a/vispy/gloo/gl/tests/test_basics.py +++ b/vispy/gloo/gl/tests/test_basics.py @@ -7,12 +7,11 @@ import sys -from nose.tools import assert_equal, assert_true # noqa - from vispy.app import Canvas from numpy.testing import assert_almost_equal from vispy.testing import (requires_application, requires_pyopengl, SkipTest, - glut_skip, run_tests_if_main) + glut_skip, run_tests_if_main, assert_equal, + assert_true) from vispy.ext.six import string_types from vispy.util import use_log_level from vispy.gloo import gl diff --git a/vispy/gloo/gl/tests/test_functionality.py b/vispy/gloo/gl/tests/test_functionality.py --- a/vispy/gloo/gl/tests/test_functionality.py +++ b/vispy/gloo/gl/tests/test_functionality.py @@ -12,18 +12,16 @@ blue). The drawing is done for 50% using attribute data, and 50% using a texture. The end result should be fully saturated colors. -Remember: the bottom left is (-1, -1) and the first quadrant. - +Remember: the bottom left is (-1, -1) and the first quadrant. """ import sys import numpy as np -from nose.tools import assert_equal, assert_true from vispy.app import Canvas -from numpy.testing import assert_almost_equal # noqa from vispy.testing import (requires_application, requires_pyopengl, SkipTest, - glut_skip, run_tests_if_main) + glut_skip, run_tests_if_main, assert_equal, + assert_true) from vispy.gloo import gl diff --git a/vispy/gloo/gl/tests/test_names.py b/vispy/gloo/gl/tests/test_names.py --- a/vispy/gloo/gl/tests/test_names.py +++ b/vispy/gloo/gl/tests/test_names.py @@ -2,7 +2,6 @@ backends, and no more than that. """ -from nose.tools import assert_equal from vispy.testing import requires_pyopengl from vispy.gloo import gl @@ -23,14 +22,14 @@ def __getattr__(self, name): def _test_function_names(mod): fnames = set([name for name in dir(mod) if name.startswith('gl')]) - assert_equal(function_names.difference(fnames), set()) - assert_equal(fnames.difference(function_names), set()) + assert function_names.difference(fnames) == set() + assert fnames.difference(function_names) == set() def _test_constant_names(mod): cnames = set([name for name in dir(mod) if name.startswith('GL')]) - assert_equal(constant_names.difference(cnames), set()) - assert_equal(cnames.difference(constant_names), set()) + assert constant_names.difference(cnames) == set() + assert cnames.difference(constant_names) == set() def test_destop(): diff --git a/vispy/gloo/tests/test_context.py b/vispy/gloo/tests/test_context.py --- a/vispy/gloo/tests/test_context.py +++ b/vispy/gloo/tests/test_context.py @@ -2,8 +2,8 @@ import gc -from nose.tools import assert_raises, assert_equal, assert_not_equal -from vispy.testing import assert_in, run_tests_if_main +from vispy.testing import (assert_in, run_tests_if_main, assert_raises, + assert_equal, assert_not_equal) from vispy.gloo import (GLContext, get_default_config) diff --git a/vispy/gloo/tests/test_framebuffer.py b/vispy/gloo/tests/test_framebuffer.py --- a/vispy/gloo/tests/test_framebuffer.py +++ b/vispy/gloo/tests/test_framebuffer.py @@ -1,10 +1,9 @@ # -*- coding: utf-8 -*- -from vispy.testing import run_tests_if_main +from vispy.testing import run_tests_if_main, assert_raises from vispy import gloo from vispy.gloo import FrameBuffer, RenderBuffer -from nose.tools import assert_raises def test_renderbuffer(): diff --git a/vispy/gloo/tests/test_texture.py b/vispy/gloo/tests/test_texture.py --- a/vispy/gloo/tests/test_texture.py +++ b/vispy/gloo/tests/test_texture.py @@ -7,7 +7,7 @@ import numpy as np from vispy.gloo import Texture2D, Texture3D, TextureAtlas -from vispy.testing import requires_pyopengl, run_tests_if_main +from vispy.testing import requires_pyopengl, run_tests_if_main, assert_raises # here we test some things that will be true of all Texture types: Texture = Texture2D @@ -306,149 +306,134 @@ def test_reset_data_type(self): # --------------------------------------------------------------- Texture3D --- -class Texture3DTest(unittest.TestCase): +@requires_pyopengl() +def test_texture_3D(): # Note: put many tests related to (re)sizing here, because Texture # is not really aware of shape. - @requires_pyopengl() - def __init__(self, *args, **kwds): - unittest.TestCase.__init__(self, *args, **kwds) - # Shape extension # --------------------------------- - def test_init(self): - data = np.zeros((10, 10, 10), dtype=np.uint8) - T = Texture3D(data=data) - assert T._shape == (10, 10, 10, 1) - assert 'Texture3D' in repr(T) - assert T.glsl_type == ('uniform', 'sampler3D') + data = np.zeros((10, 10, 10), dtype=np.uint8) + T = Texture3D(data=data) + assert T._shape == (10, 10, 10, 1) + assert 'Texture3D' in repr(T) + assert T.glsl_type == ('uniform', 'sampler3D') # Width & height # --------------------------------- - def test_width_height_depth(self): - data = np.zeros((10, 20, 30), dtype=np.uint8) - T = Texture3D(data=data) - assert T.width == 30 - assert T.height == 20 - assert T.depth == 10 + data = np.zeros((10, 20, 30), dtype=np.uint8) + T = Texture3D(data=data) + assert T.width == 30 + assert T.height == 20 + assert T.depth == 10 # Resize # --------------------------------- - def test_resize(self): - data = np.zeros((10, 10, 10), dtype=np.uint8) - T = Texture3D(data=data) - T.resize((5, 5, 5)) - assert T.shape == (5, 5, 5, 1) - glir_cmd = T._glir.clear()[-1] - assert glir_cmd[0] == 'SIZE' - assert glir_cmd[2] == (5, 5, 5, 1) + data = np.zeros((10, 10, 10), dtype=np.uint8) + T = Texture3D(data=data) + T.resize((5, 5, 5)) + assert T.shape == (5, 5, 5, 1) + glir_cmd = T._glir.clear()[-1] + assert glir_cmd[0] == 'SIZE' + assert glir_cmd[2] == (5, 5, 5, 1) # Resize with bad shape # --------------------------------- - def test_resize_bad_shape(self): - data = np.zeros((10, 10, 10), dtype=np.uint8) - T = Texture3D(data=data) - # with self.assertRaises(ValueError): - # T.resize((5, 5, 5, 5)) - self.assertRaises(ValueError, T.resize, (5, 5, 5, 5)) + data = np.zeros((10, 10, 10), dtype=np.uint8) + T = Texture3D(data=data) + # with self.assertRaises(ValueError): + # T.resize((5, 5, 5, 5)) + assert_raises(ValueError, T.resize, (5, 5, 5, 5)) # Resize not resizeable # --------------------------------- - def test_resize_unresizeable(self): - data = np.zeros((10, 10, 10), dtype=np.uint8) - T = Texture3D(data=data, resizeable=False) - # with self.assertRaises(RuntimeError): - # T.resize((5, 5, 5)) - self.assertRaises(RuntimeError, T.resize, (5, 5, 5)) + data = np.zeros((10, 10, 10), dtype=np.uint8) + T = Texture3D(data=data, resizeable=False) + # with self.assertRaises(RuntimeError): + # T.resize((5, 5, 5)) + assert_raises(RuntimeError, T.resize, (5, 5, 5)) # Set oversized data (-> resize) # --------------------------------- - def test_set_oversized_data(self): - data = np.zeros((10, 10, 10), dtype=np.uint8) - T = Texture3D(data=data) - T.set_data(np.ones((20, 20, 20), np.uint8)) - assert T.shape == (20, 20, 20, 1) + data = np.zeros((10, 10, 10), dtype=np.uint8) + T = Texture3D(data=data) + T.set_data(np.ones((20, 20, 20), np.uint8)) + assert T.shape == (20, 20, 20, 1) # Set undersized data # --------------------------------- - def test_set_undersized_data(self): - data = np.zeros((10, 10, 10), dtype=np.uint8) - T = Texture3D(data=data) - T.set_data(np.ones((5, 5, 5), np.uint8)) - assert T.shape == (5, 5, 5, 1) + data = np.zeros((10, 10, 10), dtype=np.uint8) + T = Texture3D(data=data) + T.set_data(np.ones((5, 5, 5), np.uint8)) + assert T.shape == (5, 5, 5, 1) # Set misplaced data # --------------------------------- - def test_set_misplaced_data(self): - data = np.zeros((10, 10, 10), dtype=np.uint8) - T = Texture3D(data=data) - # with self.assertRaises(ValueError): - # T.set_data(np.ones((5, 5, 5)), offset=(8, 8, 8)) - self.assertRaises(ValueError, T.set_data, - np.ones((5, 5, 5)), offset=(8, 8, 8)) + data = np.zeros((10, 10, 10), dtype=np.uint8) + T = Texture3D(data=data) + # with self.assertRaises(ValueError): + # T.set_data(np.ones((5, 5, 5)), offset=(8, 8, 8)) + assert_raises(ValueError, T.set_data, + np.ones((5, 5, 5)), offset=(8, 8, 8)) # Set misshaped data # --------------------------------- - def test_set_misshaped_data_3D(self): - data = np.zeros((10, 10, 10), dtype=np.uint8) - T = Texture3D(data=data) - # with self.assertRaises(ValueError): - # T.set_data(np.ones((10, 10, 10))) - self.assertRaises(ValueError, T.set_data, np.ones((10,))) + data = np.zeros((10, 10, 10), dtype=np.uint8) + T = Texture3D(data=data) + # with self.assertRaises(ValueError): + # T.set_data(np.ones((10, 10, 10))) + assert_raises(ValueError, T.set_data, np.ones((10,))) # Set whole data (clear pending data) # --------------------------------- - def test_set_whole_data(self): - data = np.zeros((10, 10, 10), dtype=np.uint8) - T = Texture3D(data=data) - T.set_data(np.ones((10, 10, 10), np.uint8)) - assert T.shape == (10, 10, 10, 1) - glir_cmd = T._glir.clear()[-1] - assert glir_cmd[0] == 'DATA' + data = np.zeros((10, 10, 10), dtype=np.uint8) + T = Texture3D(data=data) + T.set_data(np.ones((10, 10, 10), np.uint8)) + assert T.shape == (10, 10, 10, 1) + glir_cmd = T._glir.clear()[-1] + assert glir_cmd[0] == 'DATA' # Test set data with different shape # --------------------------------- - def test_reset_data_shape(self): - shape1 = 10, 10, 10 - shape3 = 10, 10, 10, 3 - - # Init data (explicit shape) - data = np.zeros((10, 10, 10, 1), dtype=np.uint8) - T = Texture3D(data=data) - assert T.shape == (10, 10, 10, 1) - assert T._format == 'luminance' - - # Set data to rgb - T.set_data(np.zeros(shape3, np.uint8)) - assert T.shape == (10, 10, 10, 3) - assert T._format == 'rgb' - - # Set data to grayscale - T.set_data(np.zeros(shape1, np.uint8)) - assert T.shape == (10, 10, 10, 1) - assert T._format == 'luminance' - - # Set size to rgb - T.resize(shape3) - assert T.shape == (10, 10, 10, 3) - assert T._format == 'rgb' - - # Set size to grayscale - T.resize(shape1) - assert T.shape == (10, 10, 10, 1) - assert T._format == 'luminance' + shape1 = 10, 10, 10 + shape3 = 10, 10, 10, 3 + + # Init data (explicit shape) + data = np.zeros((10, 10, 10, 1), dtype=np.uint8) + T = Texture3D(data=data) + assert T.shape == (10, 10, 10, 1) + assert T._format == 'luminance' + + # Set data to rgb + T.set_data(np.zeros(shape3, np.uint8)) + assert T.shape == (10, 10, 10, 3) + assert T._format == 'rgb' + + # Set data to grayscale + T.set_data(np.zeros(shape1, np.uint8)) + assert T.shape == (10, 10, 10, 1) + assert T._format == 'luminance' + + # Set size to rgb + T.resize(shape3) + assert T.shape == (10, 10, 10, 3) + assert T._format == 'rgb' + + # Set size to grayscale + T.resize(shape1) + assert T.shape == (10, 10, 10, 1) + assert T._format == 'luminance' # Test set data with different shape and type # ------------------------------------------- - def test_reset_data_type(self): - data = np.zeros((10, 10, 10), dtype=np.uint8) - T = Texture3D(data=data) - - data = np.zeros((10, 11, 11), dtype=np.float32) - T.set_data(data) - - data = np.zeros((12, 12, 10), dtype=np.int32) - T.set_data(data) + data = np.zeros((10, 10, 10), dtype=np.uint8) + T = Texture3D(data=data) + + data = np.zeros((10, 11, 11), dtype=np.float32) + T.set_data(data) + + data = np.zeros((12, 12, 10), dtype=np.int32) + T.set_data(data) class TextureAtlasTest(unittest.TestCase): diff --git a/vispy/gloo/tests/test_use_gloo.py b/vispy/gloo/tests/test_use_gloo.py --- a/vispy/gloo/tests/test_use_gloo.py +++ b/vispy/gloo/tests/test_use_gloo.py @@ -5,13 +5,14 @@ # ----------------------------------------------------------------------------- import numpy as np from numpy.testing import assert_allclose -from nose.tools import assert_raises, assert_equal from vispy.app import Canvas from vispy.gloo import (Texture2D, Texture3D, Program, FrameBuffer, RenderBuffer, set_viewport, clear) from vispy.gloo.util import draw_texture, _screenshot -from vispy.testing import requires_application, has_pyopengl, run_tests_if_main +from vispy.testing import (requires_application, has_pyopengl, + run_tests_if_main, + assert_raises, assert_equal) @requires_application() diff --git a/vispy/gloo/tests/test_util.py b/vispy/gloo/tests/test_util.py --- a/vispy/gloo/tests/test_util.py +++ b/vispy/gloo/tests/test_util.py @@ -2,8 +2,7 @@ from vispy.gloo import util -from vispy.testing import run_tests_if_main -from nose.tools import assert_raises +from vispy.testing import run_tests_if_main, assert_raises def test_check_enum(): diff --git a/vispy/gloo/tests/test_wrappers.py b/vispy/gloo/tests/test_wrappers.py --- a/vispy/gloo/tests/test_wrappers.py +++ b/vispy/gloo/tests/test_wrappers.py @@ -5,12 +5,12 @@ # ----------------------------------------------------------------------------- import numpy as np from numpy.testing import assert_array_equal, assert_allclose -from nose.tools import assert_true, assert_equal, assert_raises from vispy import gloo from vispy.gloo import gl from vispy.app import Canvas -from vispy.testing import requires_application, run_tests_if_main +from vispy.testing import (requires_application, run_tests_if_main, + assert_true, assert_equal, assert_raises) from vispy.gloo import read_pixels from vispy.gloo.glir import GlirQueue from vispy.gloo import wrappers diff --git a/vispy/io/tests/test_io.py b/vispy/io/tests/test_io.py --- a/vispy/io/tests/test_io.py +++ b/vispy/io/tests/test_io.py @@ -3,13 +3,12 @@ # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np from os import path as op -from nose.tools import assert_equal, assert_raises from numpy.testing import assert_allclose, assert_array_equal from vispy.io import write_mesh, read_mesh, load_data_file from vispy.geometry import _fast_cross_3d from vispy.util import _TempDir -from vispy.testing import run_tests_if_main +from vispy.testing import run_tests_if_main, assert_equal, assert_raises temp_dir = _TempDir() diff --git a/vispy/mpl_plot/tests/test_show_vispy.py b/vispy/mpl_plot/tests/test_show_vispy.py --- a/vispy/mpl_plot/tests/test_show_vispy.py +++ b/vispy/mpl_plot/tests/test_show_vispy.py @@ -3,11 +3,10 @@ # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np -from nose.tools import assert_raises from vispy.io import read_png, load_data_file from vispy.testing import (has_matplotlib, requires_application, - run_tests_if_main) + run_tests_if_main, assert_raises) import vispy.mpl_plot as plt diff --git a/vispy/testing/__init__.py b/vispy/testing/__init__.py --- a/vispy/testing/__init__.py +++ b/vispy/testing/__init__.py @@ -3,9 +3,10 @@ # Distributed under the (new) BSD License. See LICENSE.txt for more info. from ._testing import (SkipTest, requires_application, requires_img_lib, # noqa - assert_is, assert_in, assert_not_in, has_backend, # noqa - glut_skip, requires_pyopengl, requires_scipy, # noqa - has_matplotlib, assert_image_equal, # noqa + has_backend, glut_skip, requires_pyopengl, # noqa + requires_scipy, has_matplotlib, # noqa save_testing_image, TestingCanvas, has_pyopengl, # noqa - run_tests_if_main) # noqa + run_tests_if_main, assert_image_equal, + assert_is, assert_in, assert_not_in, assert_equal, + assert_not_equal, assert_raises, assert_true) # noqa from ._runners import test # noqa diff --git a/vispy/testing/_runners.py b/vispy/testing/_runners.py --- a/vispy/testing/_runners.py +++ b/vispy/testing/_runners.py @@ -31,71 +31,31 @@ def _get_root_dir(): return root_dir, dev -_nose_script = """ -# Code inspired by original nose plugin: -# https://nose.readthedocs.org/en/latest/plugins/cover.html - -import nose -from nose.plugins.base import Plugin - - -class MutedCoverage(Plugin): - '''Make a silent coverage report using Ned Batchelder's coverage module.''' - - def configure(self, options, conf): - Plugin.configure(self, options, conf) - self.enabled = True - try: - from coverage import coverage - except ImportError: - self.enabled = False - self.cov = None - print('Module "coverage" not installed, code coverage will not ' - 'be available') - else: - self.enabled = True - self.cov = coverage(auto_data=False, branch=True, data_suffix=None, - source=['vispy']) - - def begin(self): - self.cov.load() - self.cov.start() - - def report(self, stream): - self.cov.stop() - self.cov.combine() - self.cov.save() - - +_unit_script = """ +import pytest try: import faulthandler faulthandler.enable() except Exception: pass -nose.main(argv=%r%s) +raise SystemExit(pytest.main(%r)) """ -def _nose(mode, extra_arg_string): - """Run nosetests using a particular mode""" - cwd = os.getcwd() # this must be done before nose import +def _unit(mode, extra_arg_string): + """Run unit tests using a particular mode""" + cwd = os.getcwd() try: - import nose # noqa, analysis:ignore + import pytest # noqa, analysis:ignore except ImportError: - print('Skipping nosetests, nose not installed') + print('Skipping pytest, pytest not installed') raise SkipTest() if mode == 'nobackend': msg = 'Running tests with no backend' - extra_arg_string = '-a !vispy_app_test ' + extra_arg_string - extra_arg_string = '-e experimental -e wiki ' + extra_arg_string + extra_arg_string = '-m "not vispy_app_test" ' + extra_arg_string coverage = True - elif mode == 'singlefile': - fname = extra_arg_string.split(' ')[0] - assert op.isfile(fname) - msg = 'Running tests for individual file' - coverage = False else: with use_log_level('warning', print_msg=False): has, why_not = has_backend(mode, out=['why_not']) @@ -105,30 +65,34 @@ def _nose(mode, extra_arg_string): print(_line_sep + '\n' + msg + '\n' + _line_sep + '\n') raise SkipTest(msg) msg = 'Running tests with %s backend' % mode - extra_arg_string = '-a vispy_app_test ' + extra_arg_string + extra_arg_string = '-m vispy_app_test ' + extra_arg_string coverage = True - coverage = ', addplugins=[MutedCoverage()]' if coverage else '' - args = ['nosetests'] + extra_arg_string.strip().split(' ') + if coverage: + extra_arg_string += (' --cov vispy --cov-report=term-missing ' + '--no-cov-on-fail ') # make a call to "python" so that it inherits whatever the system # thinks is "python" (e.g., virtualenvs) - cmd = [sys.executable, '-c', _nose_script % (args, coverage)] + cmd = [sys.executable, '-c', _unit_script % extra_arg_string] env = deepcopy(os.environ) - if mode in ('singlefile',): - env_str = '' - else: - # We want to set this for all app backends plus "nobackend" to - # help ensure that app tests are appropriately decorated - env.update(dict(_VISPY_TESTING_APP=mode)) - env_str = '_VISPY_TESTING_APP=%s ' % mode + + # We want to set this for all app backends plus "nobackend" to + # help ensure that app tests are appropriately decorated + env.update(dict(_VISPY_TESTING_APP=mode)) + env_str = '_VISPY_TESTING_APP=%s ' % mode if len(msg) > 0: msg = ('%s\n%s:\n%s%s' - % (_line_sep, msg, env_str, ' '.join(args))) + % (_line_sep, msg, env_str, extra_arg_string)) print(msg) sys.stdout.flush() return_code = run_subprocess(cmd, return_code=True, cwd=cwd, env=env, stdout=None, stderr=None)[2] if return_code: - raise RuntimeError('Nose failure (%s)' % return_code) + raise RuntimeError('unit failure (%s)' % return_code) + else: + out_name = '.coverage.%s' % mode + if op.isfile(out_name): + os.remove(out_name) + os.rename('.coverage', out_name) def _flake(): @@ -304,34 +268,33 @@ def test(label='full', extra_arg_string=''): Parameters ---------- label : str - Can be one of 'full', 'nose', 'nobackend', 'extra', 'lineendings', + Can be one of 'full', 'unit', 'nobackend', 'extra', 'lineendings', 'flake', or any backend name (e.g., 'qt'). extra_arg_string : str - Extra arguments to sent to ``nose``, e.g. ``'-x --verbosity=2'``. + Extra arguments to sent to ``pytest``. """ from vispy.app.backends import BACKEND_NAMES as backend_names label = label.lower() - if op.isfile('.coverage'): - os.remove('.coverage') - known_types = ['full', 'nose', 'lineendings', 'extra', 'flake', - 'nobackend', 'examples'] + backend_names - if label not in known_types: - raise ValueError('label must be one of %s, or a backend name %s' - % (known_types, backend_names)) + label = 'pytest' if label == 'nose' else label + known_types = ['full', 'unit', 'lineendings', 'extra', 'flake', + 'nobackend', 'examples'] + if label not in known_types + backend_names: + raise ValueError('label must be one of %s, or a backend name %s, ' + 'not \'%s\'' % (known_types, backend_names, label)) work_dir = _get_root_dir()[0] orig_dir = os.getcwd() # figure out what we actually need to run runs = [] - if label in ('full', 'nose'): + if label in ('full', 'unit'): for backend in backend_names: - runs.append([partial(_nose, backend, extra_arg_string), + runs.append([partial(_unit, backend, extra_arg_string), backend]) elif label in backend_names: - runs.append([partial(_nose, label, extra_arg_string), label]) + runs.append([partial(_unit, label, extra_arg_string), label]) if label in ('full', 'examples'): runs.append([_examples, 'examples']) - if label in ('full', 'nose', 'nobackend'): - runs.append([partial(_nose, 'nobackend', extra_arg_string), + if label in ('full', 'unit', 'nobackend'): + runs.append([partial(_unit, 'nobackend', extra_arg_string), 'nobackend']) if label in ('full', 'extra', 'lineendings'): runs.append([_check_line_endings, 'lineendings']) diff --git a/vispy/testing/_testing.py b/vispy/testing/_testing.py --- a/vispy/testing/_testing.py +++ b/vispy/testing/_testing.py @@ -11,14 +11,6 @@ import os import inspect import base64 -try: - from nose.tools import nottest, assert_equal, assert_true -except ImportError: - assert_equal = assert_true = None - - class nottest(object): - def __init__(self, *args): - pass # Avoid "object() takes no parameters" from distutils.version import LooseVersion @@ -28,7 +20,7 @@ def __init__(self, *args): from ..util import use_log_level, run_subprocess, get_testing_file ############################################################################### -# Adapted from Python's unittest2 (which is wrapped by nose) +# Adapted from Python's unittest2 # http://docs.python.org/2/license.html try: @@ -72,26 +64,65 @@ def _format_msg(msg, std_msg): return msg +def nottest(func): + """Decorator to mark a function or method as *not* a test + """ + func.__test__ = False + return func + + +def assert_raises(exp, func, *args, **kwargs): + """Backport""" + try: + func(*args, **kwargs) + except exp: + return + std_msg = '%s not raised' % (_safe_rep(exp)) + raise AssertionError(_format_msg(None, std_msg)) + + def assert_in(member, container, msg=None): - """Backport for old nose.tools""" + """Backport""" if member in container: return std_msg = '%s not found in %s' % (_safe_rep(member), _safe_rep(container)) - msg = _format_msg(msg, std_msg) - raise AssertionError(msg) + raise AssertionError(_format_msg(msg, std_msg)) + + +def assert_true(x, msg=None): + """Backport""" + if x: + return + std_msg = '%s is not True' % (_safe_rep(x),) + raise AssertionError(_format_msg(msg, std_msg)) + + +def assert_equal(x, y, msg=None): + """Backport""" + if x == y: + return + std_msg = '%s not equal to %s' % (_safe_rep(x), _safe_rep(y)) + raise AssertionError(_format_msg(msg, std_msg)) + + +def assert_not_equal(x, y, msg=None): + """Backport""" + if x != y: + return + std_msg = '%s equal to %s' % (_safe_rep(x), _safe_rep(y)) + raise AssertionError(_format_msg(msg, std_msg)) def assert_not_in(member, container, msg=None): - """Backport for old nose.tools""" + """Backport""" if member not in container: return std_msg = '%s found in %s' % (_safe_rep(member), _safe_rep(container)) - msg = _format_msg(msg, std_msg) - raise AssertionError(msg) + raise AssertionError(_format_msg(msg, std_msg)) def assert_is(expr1, expr2, msg=None): - """Backport for old nose.tools""" + """Backport""" if expr1 is not expr2: std_msg = '%s is not %s' % (_safe_rep(expr1), _safe_rep(expr2)) raise AssertionError(_format_msg(msg, std_msg)) @@ -165,21 +196,24 @@ def has_application(backend=None, has=(), capable=()): return good, msg +def composed(*decs): + def deco(f): + for dec in reversed(decs): + f = dec(f) + return f + return deco + + def requires_application(backend=None, has=(), capable=()): """Return a decorator for tests that require an application""" good, msg = has_application(backend, has, capable) - - def skip_decorator(f): - import nose - f.vispy_app_test = True # set attribute for easy run or not - - def skipper(*args, **kwargs): - if not good: - raise SkipTest("Skipping test: %s: %s" % (f.__name__, msg)) - else: - return f(*args, **kwargs) - return nose.tools.make_decorator(f)(skipper) - return skip_decorator + dec_backend = np.testing.dec.skipif(not good, "Skipping test: %s" % msg) + try: + import pytest + except Exception: + return dec_backend + dec_app = pytest.mark.vispy_app_test + return composed(dec_app, dec_backend) def glut_skip(): @@ -354,30 +388,23 @@ def save_testing_image(image, location): @nottest -def run_tests_if_main(nose=False): +def run_tests_if_main(): """Run tests in a given file if it is run as a script""" local_vars = inspect.currentframe().f_back.f_locals if not local_vars.get('__name__', '') == '__main__': return # we are in a "__main__" fname = local_vars['__file__'] - if nose: - # Run using nose. More similar to normal test - if not os.path.isfile(fname): - raise IOError('Could not find file "%s"' % fname) - from ._runners import _nose - _nose('singlefile', fname + ' --verbosity=2') - else: - # Run ourselves. post-mortem debugging! - try: - import faulthandler - faulthandler.enable() - except Exception: - pass - import __main__ - print('==== Running tests in script\n==== %s' % fname) - run_tests_in_object(__main__) - print('==== Tests pass') + # Run ourselves. post-mortem debugging! + try: + import faulthandler + faulthandler.enable() + except Exception: + pass + import __main__ + print('==== Running tests in script\n==== %s' % fname) + run_tests_in_object(__main__) + print('==== Tests pass') def run_tests_in_object(ob): diff --git a/vispy/testing/tests/test_testing.py b/vispy/testing/tests/test_testing.py --- a/vispy/testing/tests/test_testing.py +++ b/vispy/testing/tests/test_testing.py @@ -3,9 +3,8 @@ # Copyright (c) 2014, Vispy Development Team. All Rights Reserved. # Distributed under the (new) BSD License. See LICENSE.txt for more info. # ----------------------------------------------------------------------------- -from nose.tools import assert_raises from vispy.testing import (assert_in, assert_not_in, assert_is, - run_tests_if_main) + run_tests_if_main, assert_raises) def test_testing(): diff --git a/vispy/util/dpi/tests/test_dpi.py b/vispy/util/dpi/tests/test_dpi.py --- a/vispy/util/dpi/tests/test_dpi.py +++ b/vispy/util/dpi/tests/test_dpi.py @@ -2,8 +2,6 @@ # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. -from nose.tools import assert_true - from vispy.util.dpi import get_dpi from vispy.testing import run_tests_if_main @@ -11,8 +9,8 @@ def test_dpi(): """Test dpi support""" dpi = get_dpi() - assert_true(dpi > 0.) - assert_true(isinstance(dpi, float)) + assert dpi > 0. + assert isinstance(dpi, float) run_tests_if_main() diff --git a/vispy/util/tests/test_config.py b/vispy/util/tests/test_config.py --- a/vispy/util/tests/test_config.py +++ b/vispy/util/tests/test_config.py @@ -1,13 +1,13 @@ # -*- coding: utf-8 -*- # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. -from nose.tools import assert_raises, assert_equal, assert_true from os import path as op import os from vispy.util import (config, sys_info, _TempDir, set_data_dir, save_config, load_data_file) -from vispy.testing import assert_in, requires_application, run_tests_if_main +from vispy.testing import (assert_in, requires_application, run_tests_if_main, + assert_raises, assert_equal, assert_true) temp_dir = _TempDir() diff --git a/vispy/util/tests/test_emitter_group.py b/vispy/util/tests/test_emitter_group.py --- a/vispy/util/tests/test_emitter_group.py +++ b/vispy/util/tests/test_emitter_group.py @@ -3,11 +3,10 @@ # Distributed under the (new) BSD License. See LICENSE.txt for more info. import unittest import copy -from nose.tools import assert_true, assert_raises from vispy.util.event import Event, EventEmitter, EmitterGroup from vispy.util import use_log_level -from vispy.testing import run_tests_if_main +from vispy.testing import run_tests_if_main, assert_true, assert_raises class BasicEvent(Event): diff --git a/vispy/util/tests/test_event_emitter.py b/vispy/util/tests/test_event_emitter.py --- a/vispy/util/tests/test_event_emitter.py +++ b/vispy/util/tests/test_event_emitter.py @@ -1,13 +1,12 @@ # -*- coding: utf-8 -*- # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. -from nose.tools import assert_raises, assert_equal import unittest import copy import functools from vispy.util.event import Event, EventEmitter -from vispy.testing import run_tests_if_main +from vispy.testing import run_tests_if_main, assert_raises, assert_equal class BasicEvent(Event): diff --git a/vispy/util/tests/test_import.py b/vispy/util/tests/test_import.py --- a/vispy/util/tests/test_import.py +++ b/vispy/util/tests/test_import.py @@ -9,9 +9,8 @@ import sys import os -from nose.tools import assert_equal from vispy.testing import (assert_in, assert_not_in, requires_pyopengl, - run_tests_if_main) + run_tests_if_main, assert_equal) from vispy.util import run_subprocess import vispy diff --git a/vispy/util/tests/test_key.py b/vispy/util/tests/test_key.py --- a/vispy/util/tests/test_key.py +++ b/vispy/util/tests/test_key.py @@ -1,10 +1,10 @@ # -*- coding: utf-8 -*- # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. -from nose.tools import assert_raises, assert_true, assert_equal from vispy.util.keys import Key, ENTER -from vispy.testing import run_tests_if_main +from vispy.testing import (run_tests_if_main, assert_raises, assert_true, + assert_equal) def test_key(): diff --git a/vispy/util/tests/test_logging.py b/vispy/util/tests/test_logging.py --- a/vispy/util/tests/test_logging.py +++ b/vispy/util/tests/test_logging.py @@ -1,11 +1,11 @@ # -*- coding: utf-8 -*- # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. -from nose.tools import assert_equal import logging from vispy.util import logger, use_log_level -from vispy.testing import assert_in, assert_not_in, run_tests_if_main +from vispy.testing import (assert_in, assert_not_in, run_tests_if_main, + assert_equal) def test_logging(): diff --git a/vispy/util/tests/test_run.py b/vispy/util/tests/test_run.py --- a/vispy/util/tests/test_run.py +++ b/vispy/util/tests/test_run.py @@ -1,10 +1,8 @@ # -*- coding: utf-8 -*- # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. -from nose.tools import assert_raises - from vispy.util import run_subprocess -from vispy.testing import run_tests_if_main +from vispy.testing import run_tests_if_main, assert_raises def test_run(): diff --git a/vispy/util/tests/test_transforms.py b/vispy/util/tests/test_transforms.py --- a/vispy/util/tests/test_transforms.py +++ b/vispy/util/tests/test_transforms.py @@ -2,13 +2,12 @@ # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. import numpy as np -from nose.tools import assert_equal from numpy.testing import assert_allclose from vispy.util.transforms import (translate, scale, xrotate, yrotate, zrotate, rotate, ortho, frustum, perspective) -from vispy.testing import run_tests_if_main +from vispy.testing import run_tests_if_main, assert_equal def test_transforms(): diff --git a/vispy/util/tests/test_vispy.py b/vispy/util/tests/test_vispy.py --- a/vispy/util/tests/test_vispy.py +++ b/vispy/util/tests/test_vispy.py @@ -5,10 +5,9 @@ including configuration options. """ -from nose.tools import assert_raises, assert_equal, assert_not_equal - import vispy.app -from vispy.testing import requires_application, run_tests_if_main +from vispy.testing import (requires_application, run_tests_if_main, + assert_raises, assert_equal, assert_not_equal) @requires_application('pyside') diff --git a/vispy/visuals/shaders/tests/test_function.py b/vispy/visuals/shaders/tests/test_function.py --- a/vispy/visuals/shaders/tests/test_function.py +++ b/vispy/visuals/shaders/tests/test_function.py @@ -7,9 +7,8 @@ # Users normally don't need these, but I want to test them from vispy.visuals.shaders.function import FunctionCall, TextExpression -from nose.tools import assert_raises, assert_equal, assert_not_equal # noqa from vispy.testing import (assert_in, assert_not_in, assert_is, - run_tests_if_main) + run_tests_if_main, assert_raises, assert_equal) ## Define some snippets
Let's use py.test You do `from pytest import raises, skip` and that's all you need (you may not even need skip). You can just make regular assertions, and pytest will do some voodoo to give a sensible error message when it fails. cc #637
If we can get `py.test` to do all the stuff we currently do with `nose`, I'm fine with it. I could try to take this on to learn a new testing platform, if nobody else is keen on working on it. If you do, have a look at imageio for an example. It also has a make.py thing going on, a `run_if_main()` function like ours, and also travis.yml. I have in my mental queue to also set up OSX and Windows testing, I might tackle these at the same time.
2014-12-09T22:50:45
vispy/vispy
698
vispy__vispy-698
[ "615" ]
9be19879e82ec283f4e445b44b8a01a638010711
diff --git a/vispy/app/backends/_ipynb_webgl.py b/vispy/app/backends/_ipynb_webgl.py --- a/vispy/app/backends/_ipynb_webgl.py +++ b/vispy/app/backends/_ipynb_webgl.py @@ -14,6 +14,7 @@ from ...util import logger, keys from ...ext import six from vispy.gloo.glir import BaseGlirParser +from vispy.app import Timer # Import for displaying Javascript on notebook import os.path as op @@ -60,7 +61,7 @@ # ------------------------------------------------------------- application --- -def _prepare_js(): +def _prepare_js(force=False): pkgdir = op.dirname(__file__) jsdir = op.join(pkgdir, '../../html/static/js/') # Make sure the JS files are installed to user directory (new argument @@ -69,8 +70,7 @@ def _prepare_js(): kwargs = {'user': True} else: kwargs = {} - install_nbextension([op.join(jsdir, 'vispy.min.js'), - op.join(jsdir, 'jquery.mousewheel.min.js')], + install_nbextension(op.join(jsdir, 'vispy.min.js'), overwrite=force, **kwargs) backend_path = op.join(jsdir, 'webgl-backend.js') with open(backend_path, 'r') as f: @@ -139,7 +139,7 @@ def __init__(self, *args, **kwargs): self._create_widget(size=size) def _create_widget(self, size=None): - self._widget = VispyWidget(self._gen_event, size=size) + self._widget = VispyWidget(self, size=size) # Set glir parser on context and context.shared context = self._vispy_canvas.context context.shared.parser = WebGLGlirParser(self._widget) @@ -312,18 +312,32 @@ def _vispy_stop(self): # ---------------------------------------------------------- IPython Widget --- +def _stop_timers(canvas): + """Stop all timers in a canvas.""" + for attr in dir(canvas): + try: + attr_obj = getattr(canvas, attr) + except NotImplementedError: + # This try/except is needed because canvas.position raises + # an error (it is not implemented in this backend). + attr_obj = None + if isinstance(attr_obj, Timer): + attr_obj.stop() + + class VispyWidget(DOMWidget): _view_name = Unicode("VispyView", sync=True) width = Int(sync=True) height = Int(sync=True) - def __init__(self, gen_event, **kwargs): + def __init__(self, canvas_backend, **kwargs): super(VispyWidget, self).__init__(**kwargs) w, h = kwargs.get('size', (500, 200)) self.width = w self.height = h - self.gen_event = gen_event + self.canvas_backend = canvas_backend + self.gen_event = canvas_backend._gen_event self.on_msg(self.events_received) def events_received(self, _, msg): @@ -331,6 +345,10 @@ def events_received(self, _, msg): events = msg['contents'] for ev in events: self.gen_event(ev) + elif msg['msg_type'] == 'status': + if msg['contents'] == 'removed': + # Stop all timers associated to the widget. + _stop_timers(self.canvas_backend._vispy_canvas) def send_glir_commands(self, commands): # TODO: check whether binary websocket is available (ipython >= 3)
Implement a server-side GLIR cache This is backend-independent. The GL context needs to store a list of (almost) all GLIR commands emitted since initialization. Unnecessary GLIR commands (old commands superseded by new commands) are automatically discarded (pruning), so that this list should never be very long. - [ ] implement the cache (easy) - [ ] dynamically prune old GLIR commands that are superseded by new ones: `DRAW`, `UNIFORM`, `FUNC` (slightly less straightforward) - completely get rid of `on_initialize()` (can be done in another PR) - fix the `ipynb_webgl` backend so that the latest state is automatically reinitialized when the context is lost (can be done in another PR)
Can we enumerate situations where the cache will not be able to completely reconstruct a dropped context? I only have one so far: shaders that modify their textures. Anything else? Sorry for chiming in so late. But I don't like the idea of such a cache so much. I understand that it has some advantages, but this cache can potentially take a whole lot of memory ... Simple example that will fill bring your system into swapping in seconds: texture that gets random regions updated at each frame. The idea was to intelligently merge requests like that. There also might not be a better solution.. If this is really all brought about by the IPython NB issue, an alternative solution is to tell people they can only (successfully) re-run a cell with a `.show()` if the `Canvas` instance is created in that cell. This seems like a much simpler solution, even if it does restrict the IPython use cases. > The idea was to intelligently merge requests like that. That's very complex to do when random regions are updated. You'd have to keep track of smallest contiguous data etc. Can we get a summary of what the problem is exactly? I read it in the other issue, but it's not entirely clear to me. This is not only about ipynb issue, as Luke pointed out. Limiting the ipynb framework is not an option for me, I really need this backend to work properly for my project. @almarklein Only the last state will be saved, so there's really no way this could end up taking a lot of space. We can also add a hard limit (something like no more than 100 commands or something) if it proves to be a concern. But let me add that the current constant recompilation issue is much more dramatic in this respect compared to this potential future issue. ;) > That's very complex to do when random regions are updated. You'd have to keep track of smallest contiguous data etc. I don't think we should go there: we could just keep the last `DATA` call. We don't need this cached state to be perfectly representative. If there are very rare cases where this doesn't give exactly the expected result, that's no big deal. We'll tackle the problem when we'll see it. And at least the backend will not just crash... Alternatively we could have an user option specifying how many `DRAW` calls should be saved in the cache. Is it really that hard? For each buffer, we cache any creation commands and a single data command. Whenever a new data command is issued, just update the array cached with the original command. Ah, that could work yes. Btw if we have an agreement I volunteer to implement this. As a matter of fact, I did implement such "caching" mechanism by coaslescing updates into a single continuous block of memory to be uploaded to GPU. But this requires CPU storage. So basically I guess this cache idea means taking your implementation of GPUBuffer with CPU-GPU synchronization and adapt it to the new GLIR architecture... > Is it really that hard? For each buffer, we cache any creation commands and a single data command. But remember that you can update _part_ of a texture/buffer. So you cannot simply ignore all DATA commands but the last. Even if we do manage to get this right, it means that we effectively all data on the CPU, which is something that we tried to avoid in the past... I'm just wondering whether there is another solution... You can avoid it to some extent but it will be a bit more tricky. The main idea is to compute the largest contiguous block of any update operation: 1. If it is included in the current recorded update, just apply the update on the saved block (no extra CPU). 2. If it is larger (start_new < start_old or end_new > end_old or both), the new block to be uploaded is a combination of old and new. This part might be tricky. Yes, but even then, you are storing on the CPU _at least_ as much memory as there is on the GPU. The original problem was that in the ipython notebook, calling `canvas.show()` creates a new canvas. This seems weird, I would expect `canvas.show()` on a canvas that is already shown to be a no-op. I'd much rather fix _that_ instead. @almarklein that's not how the IPython notebook works, unfortunately. There's no way around that. I propose we go ahead with this cache, with an option to enable it or disable it. When using an ipynb backend, it will be enabled by default. When using a desktop backend, it will be disabled by default. It could also be enabled or disabled depending on the user's choice, and it would be documented. In particular, it would let users save a WYSIWYG version of a complex visualization, so it would not only be used for the ipynb backend. > that's not how the IPython notebook works, unfortunately. There's no way around that. I agree that the best overall solution would be to ensure GL contexts can't just be randomly dropped. Can you clarify why this is not possible? It seems like you have some custom javascript code that manages the webgl widget; why is it not possible to ensure this widget is safely stored before a cell is closed? This also seems like a simple enough problem that the ipython folks would consider fixing it, and possibly even simple enough that vispy could patch an existing ipython at runtime.. It's not a problem in IPython, it's not a bug either. It's just the way IPython works. :) When you have an IPython widget, it represents one view of a model. These views can be easily created and closed. There can be multiple views of a model. Models can also be deleted. So the normal workflow in the IPython notebook is that widgets can be created and deleted lightly and easily. It is expected that the state will be saved in the model (Python-side); here, what would make the most sense would be to keep a cache of the GLIR commands, as you pointed out yourself. The other solution is to force using `on_initialize()`, but I agree it is a less ideal solution than the cache. The cache seems really elegant to me (and probably much simpler than "patching" IPython). Can you please precise why you don't like it? In any case I hope we can find an agreement soon because this is rather urgent to me. If we don't, I'd have to use a separate branch or a fork to go on with my project. On most other backends, the behavior is that you can hide and show the window without the GL context disappearing. This behavior of context dropping is unique to the webgl backend, and as you can see requires a lot of effort to address in gloo or elsewhere (and even the proposed cache solution is not perfect; it is impossible to completely reconstruct the GL state in all cases). So the best approach is just to ensure, on the client side, that the webgl context is tied to the canvas itself, rather than to the cell that appears when you call `show()`. It's fine if the widget appears in the `show()` cell, but it really should not be destroyed when the cell is closed; just hidden. Would it be possible to create a hidden webgl widget with the Canvas, and then simply display it within the `show()` cell? AFAIK that's impossible. The WebGL context is tied to the `<canvas>`. The user is free to close the canvas at any time, then both the `<canvas>` and the associated WebGL context are gone forever. There's really no way around that. Even if the cache solution is not perfect, it will have the advantage of working... Somewhere in ipython is a callback that gets invoked when the user closes or re-executes the cell, and this callback is responsible for destroying the contents of the cell. If we can hook into that callback, then it should be possible to remove the webgl canvas from the cell before it is destroyed, and subsequently to re-insert it to the new cell when it becomes available. Here's another way of stating the problem: the model/view architecture cannot accurately represent a vispy canvas because we do so much work on the GPU--a large part of our model is actually stored inside the view itself. In that respect it does not make much sense to support the destruction and creation of multiple views on the model. So the options are: - Store all of the model on the CPU, outside the view (the cache approach). - Make the webgl context conceptually part of the model, rather than part of the view (by preventing ipython from destroying it with the cell). I'd be surprised if that could work. And even if it could, it looks like an ugly hack... The proper way to integrate Vispy in the notebook is to have state consistency between the client and the server: that's how the whole widget model works in IPython. Given that we do the rendering in the client, we've got to have a sort of copy of the GL context in the server. That's not necessarily easy; however, the recent GLIR changes make this much easier than before. The more I think about it, the more I'm convinced that's the right way to do it. We'd appreciate the perspective of an IPython dev (@minrk @Carreau @takluyver @jdfreder) at this point. To sum up the situation: We have a WebGL widget in the notebook. A client-side OpenGL context is tied to the `<canvas>` in the cell's widget area. This widget is displayed when our `canvas.show()` function is called; this function just calls `display_html()`. When the user re-executes the cell, or when the cell is deleted, or when the user closes the widget, the canvas is destroyed, and the GL context is lost. It is therefore impossible to recreate the canvas in the state it was. (I just see Luke's latest message above which completes this summary) As a reminder, yet another alternative is to implement a mandatory initialization logic in Vispy, which we are not currently doing. The idea is that as soon as the context is lost for some reason, we recreate the widget from scratch to its initial state. I hope we can fix this in IPython. I think the cache option is not elegant at all; it's nearly impossible to make it work in all cases, and has the side effect of consuming significant amounts of memory. The on_initialize option seems a much easier solution in that respect. But on showing/closing the canvas: programatically, we can simply add `if self._visible: return` somewhere in `Canvas.show()`, so I see no problem there. This leaves us with the problem of closing the widget. Well, if you close a Qt canvas, we cannot re-use it either. So there seems to be no problem either. Or am I missing a point? > I hope we can fix this in IPython Again, there's nothing to "fix" in IPython... > it's nearly impossible to make it work in all cases It is no problem at all if the result is not 100% accurate in 100% of the cases. > and has the side effect of consuming significant amounts of memory It will consume peanuts. We'll just have a copy of the buffers on the CPU, as before, and only when using the IPython notebook. Nothing will change on the desktop backend since it can be disabled by default there! > The on_initialize option seems a much easier solution in that respect. Well, I'd be happy if we could agree on this! If you prefer this option rather than the cache, then let's go with that. @lcampagn @Eric89GXL ? The problem I see is with the visuals. > But on showing/closing the canvas: programatically, we can simply add if self._visible: return somewhere in Canvas.show(), so I see no problem there ?? > Well, if you close a Qt canvas, we cannot re-use it either. So there seems to be no problem either. Or am I missing a point? In most cases on the desktop, the application closes when you close the canvas. This is not the case in IPython. Would you accept a PR with the GLIR cache option if it's strictly restricted to the IPython backend? There might be a way to confine the implementation to `_ipynb_webgl.py` (see [this](https://github.com/vispy/vispy/blob/master/vispy/app/backends/_ipynb_webgl.py#L108)) > The on_initialize option seems a much easier solution in that respect. Unless I've misunderstood it, the `on_initialize` approach is essentially the same as the cache approach except that, instead of handling caching and context reset at the glir stage, we would push that responsibility out to the canvases, visuals, and users. The memory overhead would be the same, but the solution would be a much larger mess because the problem becomes a part of the public-facing API, rather than being handled internally at the glir stage (or better yet, at the ipython stage where the problem originates). > But on showing/closing the canvas: programatically, we can simply add if self._visible: return somewhere in Canvas.show() The problem is that when you re-execute a cell in ipython, it is immediately removed and re-created. The context is dropped before we even get to show(). > The problem is that when you re-execute a cell in ipython, it is immediately removed and re-created. The context is dropped before we even get to show(). Ok, so what about a context is shown by default when it is instantiated? No need to do `c.show()`. Re-executing that cell will recreate the actual canvas. All should work nicely. > Ok, so what about a context is shown by default when it is instantiated? No need to do c.show(). Re-executing that cell will recreate the actual canvas. All should work nicely. We already ruled out this option. There are many situations where it'll fail, for example if you initialize gloo objects in a different cell. If I manage to confine the implementation to the backend I think I'll just go ahead with the cache: it won't impact the other backends at all so there's no reason why you couldn't live with that! :) > When the user re-executes the cell, or when the cell is deleted, or when the user closes the widget, the canvas is destroyed, and the GL context is lost. I'm not familiar with GL. What information is there in the 'context' that the frontend modifies after it is displayed? I am in favor of the ipython-only cache since @rossant is in a hurry, I am rather strongly opposed to the `on_initialize` approach, and it is not yet clear whether it will be possible to prevent context loss in ipython. When we have more time to look into it, perhaps we can switch to the latter solution. > I'm not familiar with GL. What information is there in the 'context' that the frontend modifies after it is displayed? The context contains information about all data being drawn (vertices, textures, etc.), the program code that is being executed on the GPU, and all of the global state variables required by GL that set up the viewport and rendering modes. There are a few cases where this data can exist on the GPU in a state that was never present on the CPU (for example, if you upload a full texture, and then later upload new data to a sub-region of that texture, then the complete texture only ever exists on the GPU). More importantly, there are many cases where the user-specified data is sent directly to the GPU without any local storage within vispy. If the context is dropped, then all of this data / code / state must be sent again to the GPU, hence the need for some kind of cache that would handle this (or some way to prevent context loss in the first place). OK, so you can recreate the state perfectly, but it might be slow? I don't think that's something IPython can immediately help with, although if we can do things that make life easier, we'd be interested to know about that. > We already ruled out this option. There are many situations where it'll fail, for example if you initialize gloo objects in a different cell. That should still work as expected. (Come to think of it, I think we need to disable the `gloo.Context` when a canvas is closed), but if the context mechanism works as it should, gloo objects are created in the current context, or are bound to the next context that _will_ be created. > OK, so you can recreate the state perfectly, but it might be slow? I don't think that's something IPython can immediately help with, although if we can do things that make life easier, we'd be interested to know about that. With a bit of work, we can recreate the state accurately in most cases. I don't think it would be particularly slow. That's the solution I'd prefer, but I have yet to convince the other devs. :) They'd rather solve the context loss problem in IPython directly. But AFAIK there's no way around that: when you close a widget, the HTML elements are completely deleted, right? What they have in mind is a solution where we'd save somehow the GL context in the browser when the canvas is deleted, and put it back once it's recreated. I think it would be very hard and clunky to do that in IPython, and it might actually be something that is impossible with WebGL anyway. The HTML elements are deleted, but it may be possible to attach it to the model. If you display the same widget twice, do the views share a GL context, or do they have one each? They have one each: there is no context sharing in WebGL (contrary to desktop OpenGL). That being said, in the way things are currently implemented, the contexts are _effectively_ identical (in other ways, there is some sort of CPU-based context sharing rather than GPU-based). It might be because comm messages are received by both widgets in the notebook? In our architecture, comm messages go to the model; if you have multiple views, they should stay in sync. But if you can't share a context, I'm not sure it makes sense to store it in the model. @takluyver, where we hope the IPython devs can help is in deciding how we can keep the context from disappearing when the cell is cleared. Basically we have two statements: ``` # cell 1 canvas = vispy.app.Canvas() ``` ``` # cell 2 canvas.show() ``` The second cell is the one that creates the `<canvas>` HTML element, and thus contains the WebGL context. If that cell is re-executed, then the `<canvas>` disappears and the GL context goes with it. So: would it be possible to create a hidden `<canvas>` in the first cell that is subsequently shown in the second cell? And more importantly, would it be possible to add a callback that allows us to detect when the second cell is about to be destroyed so that we can preserve the `<canvas>`? If you can create a hidden canvas with an attached GL context, and then display it later, why can you not then display it a second time, so you have two views with the same context? If that were possible, it would make sense to construct the GL context along with the model. I'll have to make some tests with WebGL but I'm pretty sure that it's not possible. The context is tied to an individual canvas. Le vendredi 14 novembre 2014, Thomas Kluyver [email protected] a écrit : > If you can create a hidden canvas with an attached GL context, and then > display it later, why can you not then display it a second time, so you > have two views with the same context? If that were possible, it would make > sense to construct the GL context along with the model. > > — > Reply to this email directly or view it on GitHub > https://github.com/vispy/vispy/issues/615#issuecomment-62986600. Remember when you proposed to just recreate the canvas in order to work around the problem, and I said it didn't work? Well, apparently it's a bug with glir/context that occurs even outside the notebook. In interactive mode (ipython notebook, console, or python terminal), create and show a canvas once, it works, recreate it and reshow it, it is empty. If this bug is fixed, there might be an easy fix to the notebook problem. It looks like the relevant GLIR commands (that create the program, the buffers, etc.) do not get emitted at all the second time the canvas is created. For the Qt backend, there is a line in app/backends/_qt.py ~L323 that shuts down the GL context when the window is closed (the line should not be there, but that can be discussed elsewhere). If I remove that line, then I am able to close and reopen a canvas window without trouble. The ipython_webgl backend has not implemented `_vispy_close()` at all, so I do not think this is the problem. No, the problem is still there in the Qt backend if I remove that line. Note that the problem happens when I _recreate_ a new Canvas instance and show it again. How do you "recreate" a canvas? Can you post your python session? This is what I did: ``` >>> import vispy.scene as vs >>> c = vs.SceneCanvas(show=True) >>> r = vs.visuals.Rectangle(pos=(10, 10), height=100, width=100, color=(1, 0, 0, 1), parent=c.scene) [ now close the window] >>> c.show() ``` Ah, I do not use the scene stuff. My script `_test.py`: ``` python import numpy as np from vispy import app from vispy import gloo VS = ''' attribute vec2 a_position; void main() { gl_Position = vec4(a_position, 0., 1.); gl_PointSize = 3.; } ''' FS = ''' void main() { gl_FragColor = vec4(1., 0., 0., 1.); } ''' class MyCanvas(app.Canvas): def __init__(self): super(MyCanvas, self).__init__(keys='interactive') self.program = gloo.Program(VS, FS) self.program['a_position'] = .25 * np.random.randn(100000, 2).astype(np.float32) def on_draw(self, event): gloo.clear('black') gloo.set_viewport((0, 0,) + self.size) self.program.draw('points') def _show(): c = MyCanvas() c.show() ``` then ``` python -i _test.py >>> _show() # OK, close the window >>> _show() # empty ``` There's a mystery. Maybe this needs to be resolved as a separate issue before we continue here. I agree. If this is solved, I think the ipynb issue can be partly solved very easily, and we can put back the whole cache discussion to later. The temporary solution (that should be good enough) would be to just recreate the canvas from scratch when the context is lost. Let me add a new issue. Sorry for the slow response. +1 for avoiding the cache if possible, so if we can just re-show the canvas by fixing the bug, that is a _much_ simpler solution and probably prone to far fewer problems.
2015-01-15T13:38:02
vispy/vispy
712
vispy__vispy-712
[ "688" ]
608be1b4548028f8a96a292ffb8abe354ca80c53
diff --git a/vispy/__init__.py b/vispy/__init__.py --- a/vispy/__init__.py +++ b/vispy/__init__.py @@ -22,7 +22,7 @@ __all__ = ['use', 'sys_info', 'set_log_level', 'test'] # Definition of the version number -version_info = 0, 3, 0, '' # major, minor, patch, extra +version_info = 0, 4, 0, 'dev' # major, minor, patch, extra # Nice string for the version (mimic how IPython composes its version str) __version__ = '-'.join(map(str, version_info)).replace('-', '.', 2).strip('-')
Bump VisPy version? Should we bump the version to 0.4.0-dev or something? Currently it is 0.3.0, which doesn't seem right.
Yeah, it should be bumped, +1 for 0.4.0.dev. I prefer .dev to -dev to be compliant with PEP440: https://www.python.org/dev/peps/pep-0440/#public-version-identifiers Eric On Wed, Dec 31, 2014 at 6:21 AM, Cyrille Rossant [email protected] wrote: > Should we bump the version to 0.4.0-dev or something? Currently it is > 0.3.0, which doesn't seem right. > > — > Reply to this email directly or view it on GitHub > https://github.com/vispy/vispy/issues/688. I think that should be `0.3.0.dev`? We already released 0.3.0, so I think the .dev should be appended to the next intended release, either 0.3.1.dev or 0.4.0.dev, whichever we are aiming for. At least I thought the dev label went on the next intended version, and not the last released version... Eric On Fri, Jan 2, 2015 at 2:15 PM, Almar Klein [email protected] wrote: > I think that should be 0.3.0.dev? > > — > Reply to this email directly or view it on GitHub > https://github.com/vispy/vispy/issues/688#issuecomment-68567751. I suppose we should test whether `3.0.dev > 3.0` or `4.0.dev < 4.0` with whatever function is intended for this. In string comparisons it's certainly the first... @Eric89GXL you're right, the standard practice is to use the next planned version and to append `dev`. So it should be either `0.3.1.dev` or `0.4.0.dev` (or idem with a hypen if we want to stick to http://semver.org/ instead of PEP440). So the question is whether we want to make a maintenance release soon or not. Have there been significant improvements since 0.3.0? I believe the scene graph is faster? Also there's the experimental WebGL backend... String comparison is not a valid way of comparing version numbers. For example: ``` >>> '2.0'<'10.0' False ``` I know, but people do it. It's why many packages move from e.g. `3.9` to `4.0` even when it's not a real major version bumb. It's not our fault if people do stupid things. :) I see no reason not to use the standard convention in the computer science world. No, I agree. Let's used what's most common. I was not aware that `0.3.dev` was considered `< 0.3`. My vote is for 0.4.dev, shooting for a release after the sprint, but Cyrille if you're enthusiastic about a 3.1 maintenance release before then I'm fine with that. Eric On Sat, Jan 3, 2015 at 2:28 AM, Almar Klein [email protected] wrote: > No, I agree. Let's used what's most common. I was not aware that 0.3.dev > was considered < 0.3. > > — > Reply to this email directly or view it on GitHub > https://github.com/vispy/vispy/issues/688#issuecomment-68590202. @Eric89GXL If someone else wants a 0.3.1 release, let's do it, otherwise let's forget it. :) In the future I think it might be good to make a couple of maintenance releases between two big releases.
2015-01-23T15:06:56
vispy/vispy
713
vispy__vispy-713
[ "416" ]
53c6e1774ac53120fa5614fd2e2dfd26eecda18c
diff --git a/vispy/visuals/glsl/color.py b/vispy/visuals/glsl/color.py --- a/vispy/visuals/glsl/color.py +++ b/vispy/visuals/glsl/color.py @@ -38,3 +38,33 @@ return texture2D($colormap, vec2(x, .5)).rgb; } """ + + +# ----------------------------------------------------------------------------- +# Color space transformations +# ----------------------------------------------------------------------------- + +# From http://lolengine.net/blog/2013/07/27/rgb-to-hsv-in-glsl +# TODO: unit tests +HSV_TO_RGB = """ +vec3 hsv_to_rgb(vec3 c) +{ + vec4 K = vec4(1.0, 2.0 / 3.0, 1.0 / 3.0, 3.0); + vec3 p = abs(fract(c.xxx + K.xyz) * 6.0 - K.www); + return c.z * mix(K.xxx, clamp(p - K.xxx, 0.0, 1.0), c.y); +} +""" + + +RGB_TO_HSV = """ +vec3 rgb_to_hsv(vec3 c) +{ + vec4 K = vec4(0.0, -1.0 / 3.0, 2.0 / 3.0, -1.0); + vec4 p = mix(vec4(c.bg, K.wz), vec4(c.gb, K.xy), step(c.b, c.g)); + vec4 q = mix(vec4(p.xyw, c.r), vec4(c.r, p.yzx), step(p.x, c.r)); + + float d = q.x - min(q.w, q.y); + float e = 1.0e-10; + return vec3(abs(q.z + (q.w - q.y) / (6.0 * d + e)), d / (q.x + e), q.x); +} +"""
Implement reusable GLSL functions for color space transformations At least RGB <-> HSV. Put them in `vispy.visuals.glsl`.
See http://www.chilliant.com/rgb2hsv.html
2015-01-23T15:43:44
vispy/vispy
743
vispy__vispy-743
[ "692" ]
11cf76ad5975c14bcfcd77f7aa46597ba8f42c49
diff --git a/vispy/color/color_array.py b/vispy/color/color_array.py --- a/vispy/color/color_array.py +++ b/vispy/color/color_array.py @@ -91,6 +91,9 @@ class ColorArray(object): If array-like, it must be an Nx3 or Nx4 array-like object. Can also be a list of colors, such as ``['red', '#00ff00', ColorArray('blue')]``. + color_space : 'rgb' | 'hsv' + 'rgb' (default) : color tuples are interpreted as (r, g, b) components. + 'hsv' : color tuples are interpreted as (h, s, v) components. alpha : float | None If no alpha is not supplied in ``color`` entry and ``alpha`` is None, then this will default to 1.0 (opaque). If float, it will override @@ -108,6 +111,9 @@ class ColorArray(object): >>> b = ColorArray('#0000ff') # hex color >>> w = ColorArray() # defaults to black >>> w.rgb = r.rgb + g.rgb + b.rgb + >>>hsv_color = ColorArray(color_space="hsv", color=(0, 0, 0.5)) + >>>hsv_color + <ColorArray: 1 color ((0.5, 0.5, 0.5, 1.0))> >>> w == ColorArray('white') True >>> w.alpha = 0 @@ -124,9 +130,24 @@ class ColorArray(object): Under the hood, this class stores data in RGBA format suitable for use on the GPU. """ - def __init__(self, color='black', alpha=None, clip=False): - """Parse input type, and set attribute""" + def __init__(self, color=None, alpha=None, + clip=False, color_space='rgb'): + + # if color is RGB, then set the default color to black + if color_space == 'rgb': + # by default, if the color is None, we pick black + color = 'black' if color is None else color + elif color_space == 'hsv': + color = (0, 0, 0) if color is None else color + # if the color space is hsv, convert hsv to rgb + color = _hsv_to_rgb(color) + else: + raise ValueError('color_space should be either "rgb" or' + '"hsv", it is ' + color_space) + + # Parse input type, and set attribute""" rgba = _user_to_rgba(color, clip=clip) + if alpha is not None: rgba[:, 3] = alpha self._rgba = None
diff --git a/vispy/color/tests/test_color.py b/vispy/color/tests/test_color.py --- a/vispy/color/tests/test_color.py +++ b/vispy/color/tests/test_color.py @@ -51,6 +51,16 @@ def test_color_array(): assert_array_equal(x.rgba, .5 * np.ones((3, 4))) assert_raises(ValueError, x.__setitem__, (0, 1), 0) + # test hsv color space colors + x = ColorArray(color_space="hsv", color=[(0, 0, 1), + (0, 0, 0.5), (0, 0, 0)]) + assert_array_equal(x.rgba[0], [1, 1, 1, 1]) + assert_array_equal(x.rgba[1], [0.5, 0.5, 0.5, 1]) + assert_array_equal(x.rgba[2], [0, 0, 0, 1]) + + x = ColorArray(color_space="hsv") + assert_array_equal(x.rgba[0], [0, 0, 0, 1]) + def test_color_interpretation(): """Test basic color interpretation API"""
Add hsv option in ColorArray's constructor ``` python ColorArray(hsv=mynx3array) ```
how should this interact with the `color` parameter of the constructor? Looking at the constructor, here's what it's like: ``` def __init__(self, color='black', alpha=None, clip=False): ``` So, well, if we add another `hsv` parameter, then what happens to the `color` parameter? do we check if both are set and then throw an Exception? > So, well, if we add another hsv parameter, then what happens to the color parameter? do we check if both are set and then throw an Exception? That's what I would do indeed. @Eric89GXL WDYT? So, in that case, the default value of `color='black'` would have to be changed, correct? it would have to be `color=None`. This is because if someone opts to set the HSV value (`hsv=<value>`), then the default `color` parameter would still be around and would result in an exception. This is clearly wrong. Is there code that depends on the fact that `color` is black by default? Might be better to do color=None, check hsv, possibly raise the exception, and then set color='black' if both color and hsv are unset +1 this would maintain backwards compatibility and extend functionality Or how about `hsv=True` and `color` remains a colour (just in a different colourspace)? I like that, or `units='rgb' | 'hsv'`, would allow for other types as well without param explosion > I like that, or units='rgb' | 'hsv', would allow for other types as well without param explosion +1, but is `units` the right term? maybe color_space or space or..? +1 for `color_space` There are the times I wish python had sum types. `color_space` could have been one :)
2015-03-15T17:47:31
vispy/vispy
751
vispy__vispy-751
[ "750" ]
7ea5156aa78460fdd4e7acd83fafd6d1f2867ad2
diff --git a/vispy/visuals/image.py b/vispy/visuals/image.py --- a/vispy/visuals/image.py +++ b/vispy/visuals/image.py @@ -28,8 +28,8 @@ class ImageVisual(ModularMesh): * 'subdivide': ImageVisual is represented as a grid of triangles with texture coordinates linearly mapped. - * 'impostor': ImageVisual is represented as a quad covering the - entire view, with texture coordinates determined by the + * 'impostor': ImageVisual is represented as a quad covering the + entire view, with texture coordinates determined by the transform. This produces the best transformation results, but may be slow. @@ -55,6 +55,9 @@ def __init__(self, data, method='subdivide', grid=(10, 10), **kwargs): def set_data(self, image=None, **kwds): if image is not None: + image = np.array(image, copy=False) + if image.dtype == np.float64: + image = image.astype(np.float32) self._data = image self._texture = None super(ImageVisual, self).set_data(**kwds)
vispy.plot.image fails on float64 textures
2015-03-17T05:29:10
vispy/vispy
772
vispy__vispy-772
[ "345" ]
ae769d573d66be76a3f2152ad18b47410ef81bbe
diff --git a/vispy/gloo/glir.py b/vispy/gloo/glir.py --- a/vispy/gloo/glir.py +++ b/vispy/gloo/glir.py @@ -430,6 +430,7 @@ class GlirProgram(GlirObject): 'vec2': (2, gl.GL_FLOAT, np.float32), 'vec3': (3, gl.GL_FLOAT, np.float32), 'vec4': (4, gl.GL_FLOAT, np.float32), + 'int': (1, gl.GL_INT, np.int32), } def create(self): @@ -475,8 +476,8 @@ def set_shaders(self, vert, frag): vert_handle = gl.glCreateShader(gl.GL_VERTEX_SHADER) frag_handle = gl.glCreateShader(gl.GL_FRAGMENT_SHADER) # For both vertex and fragment shader: set source, compile, check - for code, handle, type in [(vert, vert_handle, 'vertex'), - (frag, frag_handle, 'fragment')]: + for code, handle, type_ in [(vert, vert_handle, 'vertex'), + (frag, frag_handle, 'fragment')]: gl.glShaderSource(handle, code) gl.glCompileShader(handle) status = gl.glGetShaderParameter(handle, gl.GL_COMPILE_STATUS) @@ -484,7 +485,7 @@ def set_shaders(self, vert, frag): errors = gl.glGetShaderInfoLog(handle) errormsg = self._get_error(code, errors, 4) raise RuntimeError("Shader compilation error in %s:\n%s" % - (type + ' shader', errormsg)) + (type_ + ' shader', errormsg)) # Attach shaders gl.glAttachShader(self._handle, vert_handle) gl.glAttachShader(self._handle, frag_handle) @@ -613,39 +614,48 @@ def set_texture(self, name, value): unit = self._samplers[name][-1] # Use existing unit self._samplers[name] = tex._target, tex.handle, unit gl.glUniform1i(handle, unit) - - def set_uniform(self, name, type, value): + + def set_uniform(self, name, type_, value): """ Set a uniform value. Value is assumed to have been checked. """ if not self._linked: raise RuntimeError('Cannot set uniform when program has no code') # Get handle for the uniform, first try cache handle = self._handles.get(name, -1) + count = 1 if handle < 0: if name in self._known_invalid: return handle = gl.glGetUniformLocation(self._handle, name) self._unset_variables.discard(name) # Mark as set + # if we set a uniform_array, mark all as set + if not type_.startswith('mat'): + count = value.nbytes // (4 * self.ATYPEINFO[type_][0]) + if count > 1: + for ii in range(count): + if '%s[%s]' % (name, ii) in self._unset_variables: + self._unset_variables.discard('%s[%s]' % (name, ii)) + self._handles[name] = handle # Store in cache if handle < 0: self._known_invalid.add(name) logger.warning('Variable %s is not an active uniform' % name) return # Look up function to call - funcname = self.UTYPEMAP[type] + funcname = self.UTYPEMAP[type_] func = getattr(gl, funcname) # Program needs to be active in order to set uniforms self.activate() # Triage depending on type - if type.startswith('mat'): + if type_.startswith('mat'): # Value is matrix, these gl funcs have alternative signature transpose = False # OpenGL ES 2.0 does not support transpose func(handle, 1, transpose, value) else: # Regular uniform - func(handle, 1, value) + func(handle, count, value) - def set_attribute(self, name, type, value): + def set_attribute(self, name, type_, value): """ Set an attribute value. Value is assumed to have been checked. """ if not self._linked: @@ -669,14 +679,14 @@ def set_attribute(self, name, type, value): # Triage depending on VBO or tuple data if value[0] == 0: # Look up function call - funcname = self.ATYPEMAP[type] + funcname = self.ATYPEMAP[type_] func = getattr(gl, funcname) # Set data self._attributes[name] = 0, handle, func, value[1:] else: # Get meta data vbo_id, stride, offset = value - size, gtype, dtype = self.ATYPEINFO[type] + size, gtype, dtype = self.ATYPEINFO[type_] # Get associated VBO vbo = self._parser.get_object(vbo_id) if vbo is None: diff --git a/vispy/gloo/program.py b/vispy/gloo/program.py --- a/vispy/gloo/program.py +++ b/vispy/gloo/program.py @@ -126,7 +126,7 @@ def __init__(self, vert=None, frag=None, count=0): self._buffer = None # Set to None in draw() if self._count > 0: dtype = [] - for kind, type_, name in self._code_variables.values(): + for kind, type_, name, size in self._code_variables.values(): if kind == 'attribute': dt, numel = self._gtypes[type_] dtype.append((name, dt, numel)) @@ -171,11 +171,12 @@ def variables(self): ------- variables : list Each variable is represented as a tuple (kind, type, name), - where `kind` is 'attribute', 'uniform', 'varying' or 'const'. + where `kind` is 'attribute', 'uniform', 'uniform_array', + 'varying' or 'const'. """ # Note that internally the variables are stored as a dict # that maps names -> tuples, for easy looking up by name. - return list(self._code_variables.values()) + return [x[:3] for x in self._code_variables.values()] def _parse_variables_from_code(self): """ Parse uniforms, attributes and varyings from the source code. @@ -201,17 +202,17 @@ def _parse_variables_from_code(self): regex = re.compile(var_regexp.replace('VARIABLE', kind), flags=re.MULTILINE) for m in re.finditer(regex, code): - size = -1 gtype = m.group('type') - if m.group('size'): - size = int(m.group('size')) + size = int(m.group('size')) if m.group('size') else -1 + this_kind = kind if size >= 1: + # uniform arrays get added both as individuals and full for i in range(size): name = '%s[%d]' % (m.group('name'), i) - self._code_variables[name] = kind, gtype, name - else: - name = m.group('name') - self._code_variables[name] = kind, gtype, name + self._code_variables[name] = kind, gtype, name, -1 + this_kind = 'uniform_array' + name = m.group('name') + self._code_variables[name] = this_kind, gtype, name, size # Now that our code variables are up-to date, we can process # the variables that were set but yet unknown. @@ -280,7 +281,7 @@ def __setitem__(self, name, data): return if name in self._code_variables: - kind, type_, name = self._code_variables[name] + kind, type_, name, size = self._code_variables[name] if kind == 'uniform': if type_.startswith('sampler'): @@ -314,6 +315,20 @@ def __setitem__(self, name, data): # Store and send GLIR command self._user_variables[name] = data self._glir.command('UNIFORM', self._id, name, type_, data) + + elif kind == 'uniform_array': + # Normal uniform; convert to np array and check size + dtype, numel = self._gtypes[type_] + data = np.atleast_2d(data).astype(dtype) + need_shape = (size, numel) + if data.shape != need_shape: + raise ValueError('Uniform array %r needs shape %s not %s' + % (name, need_shape, data.shape)) + data = data.ravel() + # Store and send GLIR command + self._user_variables[name] = data + self._glir.command('UNIFORM', self._id, name, type_, data) + elif kind == 'attribute': # Is this a constant value per vertex is_constant = False
diff --git a/vispy/gloo/tests/test_program.py b/vispy/gloo/tests/test_program.py --- a/vispy/gloo/tests/test_program.py +++ b/vispy/gloo/tests/test_program.py @@ -88,8 +88,14 @@ def test_uniform(self): # Text array unoforms program = Program("uniform float A[10];", "foo") - assert ('uniform', 'float', 'A[0]') in program.variables - assert len(program.variables) == 10 + assert ('uniform_array', 'float', 'A') in program.variables + assert len(program.variables) == 11 # array plus elements + self.assertRaises(ValueError, program.__setitem__, 'A', + np.ones((9, 1))) + program['A'] = np.ones((10, 1)) + program['A[0]'] = 0 + assert 'A[0]' in program._user_variables + assert 'A[0]' not in program._pending_variables # Init program program = Program("uniform float A;", diff --git a/vispy/gloo/tests/test_use_gloo.py b/vispy/gloo/tests/test_use_gloo.py --- a/vispy/gloo/tests/test_use_gloo.py +++ b/vispy/gloo/tests/test_use_gloo.py @@ -114,4 +114,60 @@ def test_use_texture3D(): assert_allclose(out, expected, atol=1./255.) +@requires_application() +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 = (300, 300) + with Canvas(size=shape) as c: + 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') + 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.) + run_tests_if_main()
Uniform arrays not supported in gloo Here is a minimal example: ``` python import numpy as np from vispy import app from vispy import gloo vertex = """ uniform float u_arr[2]; void main() { gl_Position = vec4(0, 0, 0, 1); } """ voronoi_frag = """ void main() { gl_FragColor = vec4(1., 1., 1., 1.0); } """ class Canvas(app.Canvas): def __init__(self): app.Canvas.__init__(self, close_keys='escape') self.program = gloo.Program(vertex, voronoi_frag) self.program['u_arr'] = (1., 1.) def on_initialize(self, event): gloo.clear('white') if __name__ == "__main__": c = Canvas() c.show() app.run() ``` ping @rougier @almarklein
From a little bit of digging, it sounds like it's not uniformly supported on mobile devices: https://www.opengl.org/discussion_boards/showthread.php/176674-Uniform-arrays-in-OpenGLES So if we're shooting for ES 2.0 compatibility as much as possible, then it might violate that? (Although we are starting to support some things that aren't ES2.0 compatible like 3D textures...) Having ES 2.0 compatibility means that the core functionality of vispy must work on ES 2.0 devices. It does _not_ mean that we should disallow more modern features. We should aim to expand support for desktop GL 3/4 as much as possible. Makes sense. @lcampagn you don't expect this to work with the current version of variable parsing, right? BTW I also hit a problem at one point where if variables are defined on the same line as `uniform vec4 x, y`, then only `x` gets picked up by `Program`. Is it worth rolling this into the same issue? Relevant code is here: https://github.com/vispy/vispy/blob/master/vispy/gloo/shader.py#L197 The regex does appear to pick up the array syntax correctly.. I'm not sure what's supposed to happen past that point. I've added a PR on Almar's PR for gloo (#307) that solved the problem but it did not make it to the final merge. Anyway, a clean parser is available at: https://github.com/vispy/experimental/blob/master/nr_parser/parser.py @rossant it looks like it might actually be coded to work how you did it in the Voronoi example, namely by accessing variables as `program['u_arr[0]'] = 0.0` or whatever. In this sense, uniform array access setting _is_ supported, the API just isn't ideal, right? You'd rather be able to do `program['u_arr'][0] = 0.0` or so? @Eric89GXL indeed, but more importantly, I think we should also support the simple syntax `program['u_arr'] = myarr` by using [`glUniform*v`](https://www.khronos.org/opengles/sdk/docs/man/xhtml/glUniform.xml) functions.
2015-03-25T15:38:16
vispy/vispy
782
vispy__vispy-782
[ "757" ]
400c3b9d682cff5d9753b6d94d4bd2ef6a59a82c
diff --git a/vispy/gloo/context.py b/vispy/gloo/context.py --- a/vispy/gloo/context.py +++ b/vispy/gloo/context.py @@ -212,3 +212,21 @@ def ref(self): return ref else: raise RuntimeError('No reference for available for GLShared') + + +class FakeCanvas(object): + """ Fake canvas to allow using gloo without vispy.app + + Instantiate this class to collect GLIR commands from gloo + interactions. Call flush() in your draw event handler to execute + the commands in the active contect. + """ + + def __init__(self): + self.context = GLContext() + set_current_canvas(self) + + def flush(self): + """ Flush commands. Call this after setting to context to current. + """ + self.context.flush_commands() diff --git a/vispy/gloo/wrappers.py b/vispy/gloo/wrappers.py --- a/vispy/gloo/wrappers.py +++ b/vispy/gloo/wrappers.py @@ -570,7 +570,10 @@ def glir(self): """ The GLIR queue corresponding to the current canvas """ canvas = get_current_canvas() - assert canvas is not None + if canvas is None: + msg = ("If you want to use gloo without vispy.app, " + + "use a gloo.context.FakeCanvas.") + raise RuntimeError('Gloo requires a Canvas to run.\n' + msg) return canvas.context.glir
diff --git a/vispy/gloo/tests/test_context.py b/vispy/gloo/tests/test_context.py --- a/vispy/gloo/tests/test_context.py +++ b/vispy/gloo/tests/test_context.py @@ -5,6 +5,7 @@ from vispy.testing import (assert_in, run_tests_if_main, assert_raises, assert_equal, assert_not_equal) +from vispy import gloo from vispy.gloo import (GLContext, get_default_config) @@ -27,7 +28,7 @@ def __init__(self): def _vispy_set_current(self): self.set_current = True - + def test_context_config(): """ Test GLContext handling of config dict """ @@ -54,7 +55,7 @@ def test_context_config(): # Passing crap should raise assert_raises(KeyError, GLContext, {'foo': 3}) assert_raises(TypeError, GLContext, {'double_buffer': 'not_bool'}) - + def test_context_taking(): """ Test GLContext ownership and taking @@ -88,4 +89,31 @@ def get_canvas(c): assert_raises(RuntimeError, get_canvas, c) +def test_gloo_without_app(): + """ Test gloo without vispy.app (with FakeCanvas) """ + + # Create dummy parser + class DummyParser(gloo.glir.BaseGlirParser): + def __init__(self): + self.commands = [] + + def parse(self, commands): + self.commands.extend(commands) + + p = DummyParser() + + # Create fake canvas and attach our parser + c = gloo.context.FakeCanvas() + c.context.shared.parser = p + + # Do some commands + gloo.clear() + c.flush() + gloo.clear() + c.flush() + + assert len(p.commands) in (2, 3) # there may be a CURRENT command + assert p.commands[-1][1] == 'glClear' + + run_tests_if_main()
gloo cannot be used without a canvas? The discussion on the list seems to indicate this is the case: https://groups.google.com/forum/#!topic/vispy/L1EFzNreMgA @almarklein is there a workaround? Can we tell it somehow not to use features of `Canvas`? It seems like we broke orthogonality a bit with the GLIR code. If there is already a way to do this, then we should fix the `assert` statement with a more informative error saying how to use `gloo` outside the `app` system.
2015-03-25T23:24:06
vispy/vispy
786
vispy__vispy-786
[ "711" ]
b7e57695a3dda42dd2555e9056fdb4ba86b0c092
diff --git a/vispy/gloo/buffer.py b/vispy/gloo/buffer.py --- a/vispy/gloo/buffer.py +++ b/vispy/gloo/buffer.py @@ -430,8 +430,11 @@ def _prepare_data(self, data, convert=False): if not isinstance(data, np.ndarray): raise ValueError('Data must be a ndarray (got %s)' % type(data)) if data.dtype.isbuiltin: - if convert is True and data.dtype is not np.float32: + if convert is True: data = data.astype(np.float32) + if data.dtype in (np.float64, np.int64): + raise TypeError('data must be 32-bit not %s' + % data.dtype) c = data.shape[-1] if data.ndim > 1 else 1 if c in [2, 3, 4]: if not data.flags['C_CONTIGUOUS']: diff --git a/vispy/util/fetching.py b/vispy/util/fetching.py --- a/vispy/util/fetching.py +++ b/vispy/util/fetching.py @@ -270,14 +270,19 @@ def _fetch_file(url, file_name, print_destination=True): temp_file_name = file_name + ".part" local_file = None initial_size = 0 + # Checking file size and displaying it alongside the download url + n_try = 3 + for ii in range(n_try): + try: + data = urllib.request.urlopen(url, timeout=5.) + except Exception as e: + if ii == n_try - 1: + raise RuntimeError('Error while fetching file %s.\n' + 'Dataset fetching aborted (%s)' % (url, e)) try: - # Checking file size and displaying it alongside the download url - u = urllib.request.urlopen(url, timeout=5.) - file_size = int(u.headers['Content-Length'].strip()) + file_size = int(data.headers['Content-Length'].strip()) print('Downloading data from %s (%s)' % (url, sizeof_fmt(file_size))) - # Downloading data (can be extended to resume if need be) local_file = open(temp_file_name, "wb") - data = urllib.request.urlopen(url, timeout=5.) _chunk_read(data, local_file, initial_size=initial_size) # temp file must be closed prior to the move if not local_file.closed:
diff --git a/vispy/gloo/tests/test_buffer.py b/vispy/gloo/tests/test_buffer.py --- a/vispy/gloo/tests/test_buffer.py +++ b/vispy/gloo/tests/test_buffer.py @@ -442,6 +442,9 @@ def test_init_allowed_dtype(self): names = V.dtype.names assert V.dtype[names[0]].base == dtype assert V.dtype[names[0]].shape == (3,) + for dtype in (np.float64, np.int64): + self.assertRaises(TypeError, VertexBuffer, + np.zeros((10, 3), dtype=dtype)) # Tuple/list is also allowed V = VertexBuffer([1, 2, 3]) diff --git a/vispy/testing/__init__.py b/vispy/testing/__init__.py --- a/vispy/testing/__init__.py +++ b/vispy/testing/__init__.py @@ -1,6 +1,44 @@ # -*- coding: utf-8 -*- # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. +""" +Testing +======= +This module provides functions useful for running tests in vispy. + +Tests can be run in a few ways: + + * From Python, you can import ``vispy`` and do ``vispy.test()``. + * From the source root, you can do ``make test`` which wraps to + a call to ``python make test``. + +There are various diffrent testing "modes", including: + + * "full": run all tests. + * any backend name (e.g., "glfw"): run application/GL tests using a + specific backend. + * "nobackend": run tests that do not require a backend. + * "examples": run repo examples to check for errors and warnings. + * "flake": check style errors. + +Examples get automatically tested unless they have a special comment toward +the top ``# vispy: testskip``. Examples that should be tested should be +formatted so that 1) a ``Canvas`` class is defined, or a ``canvas`` class +is instantiated; and 2) the ``app.run()`` call is protected by a check +if ``__name__ == "__main__"``. This makes it so that the event loop is not +started when running examples in the test suite -- the test suite instead +manually updates the canvas (using ``app.process_events()``) for under one +second to ensure that things like timer events are processed. + +For examples on how to test various bits of functionality (e.g., application +functionality, or drawing things with OpenGL), it's best to look at existing +examples in the test suite. + +The code base gets automatically tested by Travis-CI (Linux) and AppVeyor +(Windows) on Python 2.6, 2.7, 3.4. There are multiple testing modes that +use e.g. full dependencies, minimal dependencies, etc. See ``.travis.yml`` +to determine what automatic tests are run. +""" from ._testing import (SkipTest, requires_application, requires_img_lib, # noqa has_backend, requires_pyopengl, # noqa
Instructions for testing VisPy canvas on Travis It would be great to put instructions somewhere detailing how to unit test VisPy visualizations on Travis. Typically, I have a project on GitHub that uses py.test and Travis. One of my tests displays a custom visualization created with VisPy (using `canvas.show(); app.run()`). Running `make test` locally opens a window, which has to be closed manually. On Travis, I'd like at least the GLIR commands to be emitted, even if they are not interpreted by anything. This will test my data baking logic, for example. What are the exact steps to make this work correctly on Travis? (putting the steps in this issue's discussion would be enough at first)
And to go a bit further: are there ways to test user interaction? (like click at (300, 400), drag the mouse button 20 px left, etc.) For visuals testing, take a look at #706. It actually checks the outputs to make sure they are consistent. If your visuals are stable enough to do that, you can use it. It uses a threshold for a correlation (default 0.95), so even if there is a little bit of variability it's considered okay. Also, all of the examples get tested -- at least that they run without errors or warnings -- by `python make test examples`, so that's another layer of testing we do. Button presses are faked natively for each Canvas here, which isn't quite what you want: https://github.com/vispy/vispy/blob/master/vispy/app/tests/test_app.py Instead you'd want to call e.g. `canvas.backend._vispy_mouse_press(...)` directly, which would simulate what happens when `vispy` gets events from the backend. See this for an example: https://github.com/vispy/vispy/blob/master/vispy/app/backends/_qt.py#L326 Thanks! For headless rendering stuff, I assume the `before_script` bit in travis is enough and can be reused as is in another project? Yeah you just need to spin up an `Xvfb` instance to get a functional but slow X server, which I've done for several projects that need it. Is there a way to not install any backend on travis? I get a `RuntimeError: Could not import any of the backends` Are you asking if it's possible to render without having any backends installed? Currently the answer is no -- that's what the EGL push is for, but it's not there yet. If you're asking if we test the no-backend case / support, we do -- there is a `deps=minimal` Travis condition which does not install any backend, and the tests should run fine in this case. Any tests that require a backend should be decorated with `requires_application` to avoid hitting the error you describe. OK so it looks like I have to install a backend in order to test views on travis. Yeah. Is this for a different repo, or for a `vispy` branch you're working on that isn't a PR yet...? No it's another project Pyglet `tip` is probably the easiest, you can get the line from our `.travis.yml` How do I close the canvas after, say, 1 second? (with qt) Right now `canvas.show()` freezes travis obviously... Take a look at our example testing code, it probably does something very close to what you want. What actually gets executed for each example is in `_script`: https://github.com/vispy/vispy/blob/master/vispy/testing/_runners.py#L166 If you change the `for _ in range(5)` to `for _ in range(60)`, it should run for ~1 sec (assuming draws are very fast). In other words, something like this should work: ``` with canvas as c: t0 = time.time() while (time.time() - t0) < 1.: c.update() c.app.process_events() time.sleep(1./60.) ``` Excellent, it worked, thanks! @rossant, want to write up a section on unit testing for the documentation? @lcampagn I don't have much time right now, unfortunately, but that's definitely something doable during the sprint
2015-03-26T08:15:47
vispy/vispy
823
vispy__vispy-823
[ "821" ]
93af9b9ca603d0b83f44955b5a553c4a5ab9614f
diff --git a/examples/basics/scene/console.py b/examples/basics/scene/console.py --- a/examples/basics/scene/console.py +++ b/examples/basics/scene/console.py @@ -18,6 +18,7 @@ grid = canvas.central_widget.add_grid() vb = scene.widgets.ViewBox(border_color='b') +vb.camera = 'panzoom' vb.camera.rect = -1, -1, 2, 2 grid.add_widget(vb, row=0, col=0) text = Text('Starting timer...', color='w', font_size=24, parent=vb.scene) diff --git a/examples/basics/scene/grid.py b/examples/basics/scene/grid.py --- a/examples/basics/scene/grid.py +++ b/examples/basics/scene/grid.py @@ -23,16 +23,19 @@ # Add 3 ViewBoxes to the grid b1 = grid.add_view(row=0, col=0, col_span=2) +b1.camera = 'panzoom' b1.border_color = (0.5, 0.5, 0.5, 1) b1.camera = scene.PanZoomCamera(rect=(-0.5, -5, 11, 10)) b1.border = (1, 0, 0, 1) b2 = grid.add_view(row=1, col=0) +b2.camera = 'panzoom' b2.border_color = (0.5, 0.5, 0.5, 1) b2.camera = scene.PanZoomCamera(rect=(-10, -5, 15, 10)) b2.border = (1, 0, 0, 1) b3 = grid.add_view(row=1, col=1) +b3.camera = 'panzoom' b3.border_color = (0.5, 0.5, 0.5, 1) b3.camera = scene.PanZoomCamera(rect=(-5, -5, 10, 10)) b3.border = (1, 0, 0, 1) diff --git a/examples/basics/scene/grid_large.py b/examples/basics/scene/grid_large.py --- a/examples/basics/scene/grid_large.py +++ b/examples/basics/scene/grid_large.py @@ -26,6 +26,7 @@ lines.append([]) for j in range(10): vb = grid.add_view(row=i, col=j) + vb.camera = 'panzoom' vb.camera.rect = (0, -5), (100, 10) vb.border = (1, 1, 1, 0.4)
Text is misplaced in scene/console example ![cdg3](https://cloud.githubusercontent.com/assets/940580/6873155/a27d28da-d4ae-11e4-9a79-b638389294e5.jpg)
Possibly related problems in scene/markers and scene/grid_large `git bisect` says @almarklein should check this commit: https://github.com/vispy/vispy/commit/597698ad0c8054a02adf8280b5a4780d180ae210 As @nippoo just said, "commit a little, commit often"...
2015-03-27T19:37:30
vispy/vispy
828
vispy__vispy-828
[ "801" ]
e5e32a166623bb8b0b6b8b1ce08187c855b296a6
diff --git a/examples/demo/gloo/galaxy/galaxy.py b/examples/demo/gloo/galaxy/galaxy.py --- a/examples/demo/gloo/galaxy/galaxy.py +++ b/examples/demo/gloo/galaxy/galaxy.py @@ -113,34 +113,8 @@ class Canvas(app.Canvas): def __init__(self): # setup initial width, height - self.width = 800 - self.height = 600 - app.Canvas.__init__(self, keys='interactive') - self.size = self.width, self.height + app.Canvas.__init__(self, keys='interactive', size=(800, 600)) - self._timer = app.Timer('auto', connect=self.update, start=True) - - # create the numpy array corresponding to the shader data - def __create_galaxy_vertex_data(self): - data = np.zeros(len(galaxy), - dtype=[('a_size', np.float32, 1), - ('a_position', np.float32, 2), - ('a_color_index', np.float32, 1), - ('a_brightness', np.float32, 1), - ('a_type', np.float32, 1)]) - - # see shader for parameter explanations - data['a_size'] = galaxy['size'] * max(self.width / 800.0, - self.height / 800.0) - data['a_position'] = galaxy['position'] / 13000.0 - - data['a_color_index'] = (galaxy['temperature'] - t0) / (t1 - t0) - data['a_brightness'] = galaxy['brightness'] - data['a_type'] = galaxy['type'] - - return data - - def on_initialize(self, event): # create a new shader program self.program = gloo.Program(VERT_SHADER, FRAG_SHADER, count=len(galaxy)) @@ -159,8 +133,8 @@ def on_initialize(self, event): self.program['u_colormap'] = colors - self.projection = perspective(45.0, self.width / float(self.height), - 1.0, 1000.0) + w, h = self.size + self.projection = perspective(45.0, w / float(h), 1.0, 1000.0) self.program['u_projection'] = self.projection # start the galaxy to some decent point in the future @@ -173,23 +147,37 @@ def on_initialize(self, event): self.program.bind(self.data_vbo) # setup blending - self.__setup_blending_mode() + gloo.set_state(clear_color=(0.0, 0.0, 0.03, 1.0), + depth_test=False, blend=True, + blend_func=('src_alpha', 'one')) + + self._timer = app.Timer('auto', connect=self.update, start=True) - def __setup_blending_mode(self): - # set the clear color to almost black - gloo.gl.glClearColor(0.0, 0.0, 0.03, 1.0) - gloo.gl.glDisable(gloo.gl.GL_DEPTH_TEST) - # use additive blend mode so that the - # particles overlap and intensify - gloo.gl.glEnable(gloo.gl.GL_BLEND) - gloo.gl.glBlendFunc(gloo.gl.GL_SRC_ALPHA, gloo.gl.GL_ONE) + def __create_galaxy_vertex_data(self): + data = np.zeros(len(galaxy), + dtype=[('a_size', np.float32, 1), + ('a_position', np.float32, 2), + ('a_color_index', np.float32, 1), + ('a_brightness', np.float32, 1), + ('a_type', np.float32, 1)]) + + # see shader for parameter explanations + pw, ph = self.physical_size + data['a_size'] = galaxy['size'] * max(pw / 800.0, ph / 800.0) + data['a_position'] = galaxy['position'] / 13000.0 + + data['a_color_index'] = (galaxy['temperature'] - t0) / (t1 - t0) + data['a_brightness'] = galaxy['brightness'] + data['a_type'] = galaxy['type'] + + return data def on_resize(self, event): - self.width, self.height = event.size # setup the new viewport - gloo.set_viewport(0, 0, self.width, self.height) + gloo.set_viewport(0, 0, *event.physical_size) # recompute the projection matrix - self.projection = perspective(45.0, self.width / float(self.height), + w, h = event.size + self.projection = perspective(45.0, w / float(h), 1.0, 1000.0) self.program['u_projection'] = self.projection diff --git a/examples/demo/gloo/shadertoy.py b/examples/demo/gloo/shadertoy.py --- a/examples/demo/gloo/shadertoy.py +++ b/examples/demo/gloo/shadertoy.py @@ -13,6 +13,10 @@ """ +# NOTE: This example throws warnings about variables not being used; +# this is normal because only some shadertoy examples make use of all +# variables, and the GPU may compile some of them away. + import sys from datetime import datetime, time import numpy as np @@ -43,7 +47,7 @@ uniform sampler2D iChannel2; // input channel. XX = 2D/Cube uniform sampler2D iChannel3; // input channel. XX = 2D/Cube uniform vec3 iChannelResolution[4]; // channel resolution (in pixels) -uniform float iChannelTime[4]; // channel playback time (in seconds) +uniform float iChannelTime[4]; // channel playback time (in sec) %s """ @@ -79,6 +83,7 @@ def __init__(self, shadertoy=None): self.program["position"] = [(-1, -1), (-1, 1), (1, 1), (-1, -1), (1, 1), (1, -1)] + self.program['iMouse'] = 0, 0, 0, 0 self.program['iSampleRate'] = 44100. for i in range(4): @@ -114,7 +119,7 @@ def on_mouse_move(self, event): def on_timer(self, event): self.program['iGlobalTime'] = event.elapsed - self.program['iDate'] = get_idate() # used in some shadertoy examples + self.program['iDate'] = get_idate() # used in some shadertoy exs self.update() def on_resize(self, event): diff --git a/examples/tutorial/app/app_events.py b/examples/tutorial/app/app_events.py --- a/examples/tutorial/app/app_events.py +++ b/examples/tutorial/app/app_events.py @@ -16,9 +16,6 @@ def __init__(self, *args, **kwargs): app.Canvas.__init__(self, *args, **kwargs) self.title = 'App demo' - def on_initialize(self, event): - print('initializing!') - def on_close(self, event): print('closing!')
diff --git a/examples/benchmark/scene_test_1.py b/examples/benchmark/scene_test_1.py --- a/examples/benchmark/scene_test_1.py +++ b/examples/benchmark/scene_test_1.py @@ -96,15 +96,12 @@ def __init__(self, **kwargs): self.width, self.height = self.size gloo.set_viewport(0, 0, self.physical_size[0], self.physical_size[1]) + gloo.set_state(clear_color='black', blend=True, + blend_func=('src_alpha', 'one_minus_src_alpha')) self._tr = TransformSystem(self) - self.show() - def on_initialize(self, event): - gloo.set_state(clear_color='black', blend=True, - blend_func=('src_alpha', 'one_minus_src_alpha')) - def on_resize(self, event): self.width, self.height = event.size gloo.set_viewport(0, 0, event.physical_size[0], event.physical_size[1]) @@ -276,7 +273,7 @@ def __init__(self, data): self._y_transform = y_transform colormap = Function(DISCRETE_CMAP) - cmap = np.random.uniform(size=(1, nsignals, 3), + cmap = np.random.uniform(size=(1, nsignals, 3), low=.5, high=.9).astype(np.float32) tex = gloo.Texture2D((cmap * 255).astype(np.uint8)) colormap['colormap'] = Variable('uniform sampler2D u_colormap', tex) @@ -324,21 +321,21 @@ class Signals(SignalsVisual, scene.visuals.Node): v_index = a_index; } """ - + def draw(self, transform_system): self._program.vert['transform'] = transform_system.get_full_transform() self._program.draw('line_strip') - + if __name__ == '__main__': data = np.random.normal(size=(128, 1000)).astype(np.float32) - - pzcanvas = PanZoomCanvas(position=(400, 300), size=(800, 600), + + pzcanvas = PanZoomCanvas(position=(400, 300), size=(800, 600), title="PanZoomCanvas") visual = SignalsVisual(data) pzcanvas.add_visual('signal', visual) - - scanvas = scene.SceneCanvas(show=True, keys='interactive', + + scanvas = scene.SceneCanvas(show=True, keys='interactive', title="SceneCanvas") svisual = Signals(data) view = scanvas.central_widget.add_view()
examples/demo/gloo/shadertoy.py throws up a load of warnings ``` WARNING: Variable iSampleRate is not an active uniform WARNING: Variable iChannelTime[0] is not an active uniform WARNING: Variable iChannelTime[1] is not an active uniform WARNING: Variable iChannelTime[2] is not an active uniform WARNING: Variable iChannelTime[3] is not an active uniform WARNING: Variable iChannelResolution[0] is not an active uniform WARNING: Variable iDate is not an active uniform WARNING: Program has unset variables: {'iMouse'} ``` This also isn't tested by Travis for some reason or another. Probably because of the above warnings.
These warnings are normal actually. This example accepts any shadertoy code which may or may not implement all uniforms. I guess these warnings could be made more discrete (they are useful for debugging, not for the normal user). Hm. I don't think we should be throwing warnings in our default demos. Why isn't this tested by Travis, anyway?
2015-03-27T22:13:27
vispy/vispy
835
vispy__vispy-835
[ "715" ]
4af337a27e2f3df5e4807e07fdd8889364eb1543
diff --git a/vispy/ext/gdi32plus.py b/vispy/ext/gdi32plus.py --- a/vispy/ext/gdi32plus.py +++ b/vispy/ext/gdi32plus.py @@ -162,7 +162,10 @@ class LOGFONT(Structure): user32.ReleaseDC.argtypes = [c_void_p, HDC] -user32.SetProcessDPIAware.argtypes = [] +try: + user32.SetProcessDPIAware.argtypes = [] +except AttributeError: + pass # not present on XP # gdiplus diff --git a/vispy/util/dpi/_win32.py b/vispy/util/dpi/_win32.py --- a/vispy/util/dpi/_win32.py +++ b/vispy/util/dpi/_win32.py @@ -10,7 +10,10 @@ def get_dpi(): """Get screen DPI from the OS""" - user32.SetProcessDPIAware() + try: + user32.SetProcessDPIAware() + except AttributeError: + pass # not present on XP dc = user32.GetDC(0) h_size = gdi32.GetDeviceCaps(dc, HORZSIZE) v_size = gdi32.GetDeviceCaps(dc, VERTSIZE)
Vispy Windows XP Compatibility When trying to run a Vispy Application in windows xp project will not start due to fault "Attribute Error: function 'SetProcessDPIAware' not found". First instance traced back to "vispy\ext\gdi32plus.py line 165" this line was commented out and program ran again and produced the same fault but pointed at "vispy\util\dpi_win32.py line 13" this line was also commented out and the program finally loaded. Exhaustive testing is not yet complete but program is basically functional. It appears the "SetProcessDPIAware" API is not supported in windows XP and only partially supported in windows vista and later, see.... https://msdn.microsoft.com/en-us/library/dn469266(v=vs.85).aspx and .... https://msdn.microsoft.com/en-us/library/dn302122(v=vs.85).aspx. Further testing needs to be done to see whether Vispy is obtaining proper DPI settings. reference: http://www.experts-exchange.com/Programming/Languages/Scripting/Python/Q_21794611.html
Thanks for the report! Seems like you have a decent handle on the issues -- are you up for submitting a fix? The easiest (and crappiest) solution would just be to detect XP's presence, and not use the selected functions in that case, returning some sensible default (e.g. 92 or 96). We could start there, and later add more complete support, or just add more complete/better support from the start, depending on your willingness to pursue this. I'm happy to help or even fix it myself if you're not up for it. FWIW Vispy is able to get the DPI from my machine running Windows 8.1. I haven't tested it on other operating systems, since that's all I have easy access to right now. Perhaps @rossant has? No I just have a Windows 8.1 machine (and Windows 10 preview in a VM). You'll see on gitter some pointers on how to possibly update the code so that it also work with XP (but this requires more testing on XP).
2015-03-29T20:19:38
vispy/vispy
887
vispy__vispy-887
[ "886" ]
4d4e0446091f32c1ef02a44c74e5b102f5b8cb79
diff --git a/vispy/app/backends/_qt.py b/vispy/app/backends/_qt.py --- a/vispy/app/backends/_qt.py +++ b/vispy/app/backends/_qt.py @@ -579,6 +579,7 @@ def _init_specific(self, p, kwargs): if not self.isValid(): raise RuntimeError('context could not be created') self.setAutoBufferSwap(False) # to make consistent with other backends + self.setFocusPolicy(QtCore.Qt.WheelFocus) def _vispy_close(self): # Force the window or widget to shut down
Focus problem in Qt When embedding a VisPy canvas in a QMainWindow dock widget, the keyboard events are not received by VisPy. It might be a focus problem. You can test this in the primitive_qt_viewer example, by implement an `on_key_press` event in the canvas. Any ideas?
2015-05-02T07:42:04
vispy/vispy
889
vispy__vispy-889
[ "888" ]
4b09714ebfecb3fccccf3fd19dc1ab17cfd4fd59
diff --git a/vispy/visuals/shaders/function.py b/vispy/visuals/shaders/function.py --- a/vispy/visuals/shaders/function.py +++ b/vispy/visuals/shaders/function.py @@ -19,6 +19,7 @@ import re import logging +import numpy as np from ...util.eq import eq from ...util import logger @@ -238,14 +239,10 @@ def __setitem__(self, key, val): # try just updating its value. variable = storage.get(key, None) if isinstance(variable, Variable): - try: + if np.any(variable.value != val): variable.value = val self.changed(value_changed=True) - return - except Exception: - # Setting value on existing Variable failed for some - # reason; will need to create a new Variable instead. - pass + return # Could not set variable.value directly; instead we will need # to create a new ShaderObject @@ -465,7 +462,7 @@ def _get_replaced_code(self, names): if '$' in code: v = parsing.find_template_variables(code) logger.warning('Unsubstituted placeholders in code: %s\n' - ' replacements made: %s' % + ' replacements made: %s', (v, list(self._expressions.keys()))) return code + '\n' diff --git a/vispy/visuals/shaders/program.py b/vispy/visuals/shaders/program.py --- a/vispy/visuals/shaders/program.py +++ b/vispy/visuals/shaders/program.py @@ -38,7 +38,7 @@ def vert(self): @vert.setter def vert(self, vcode): if hasattr(self, '_vert') and self._vert is not None: - self._vert.changed.disconnect((self, '_source_changed')) + self._vert._dependents.pop(self) self._vert = vcode if self._vert is None: @@ -46,7 +46,7 @@ def vert(self, vcode): vcode = preprocess(vcode) self._vert = MainFunction(vcode) - self._vert.changed.connect((self, '_source_changed')) + self._vert._dependents[self] = None self._need_build = True self.changed(code_changed=True, value_changed=False) @@ -58,7 +58,7 @@ def frag(self): @frag.setter def frag(self, fcode): if hasattr(self, '_frag') and self._frag is not None: - self._frag.changed.disconnect((self, '_source_changed')) + self._frag._dependents.pop(self) self._frag = fcode if self._frag is None: @@ -66,7 +66,7 @@ def frag(self, fcode): fcode = preprocess(fcode) self._frag = MainFunction(fcode) - self._frag.changed.connect((self, '_source_changed')) + self._frag._dependents[self] = None self._need_build = True self.changed(code_changed=True, value_changed=False) @@ -77,12 +77,12 @@ def prepare(self): pass # todo: remove! - def _source_changed(self, ev): + def _dep_changed(self, dep, code_changed=False, value_changed=False): logger.debug("ModularProgram source changed: %s", self) - if ev.code_changed: + if code_changed: self._need_build = True - self.changed(code_changed=ev.code_changed, - value_changed=ev.value_changed) + self.changed(code_changed=code_changed, + value_changed=value_changed) def draw(self, *args, **kwargs): self.build_if_needed() diff --git a/vispy/visuals/shaders/shader_object.py b/vispy/visuals/shaders/shader_object.py --- a/vispy/visuals/shaders/shader_object.py +++ b/vispy/visuals/shaders/shader_object.py @@ -1,20 +1,14 @@ # -*- coding: utf-8 -*- # Copyright (c) 2014, Vispy Development Team. # Distributed under the (new) BSD License. See LICENSE.txt for more info. +from weakref import WeakKeyDictionary + from ...util import logger -from ...util.event import EventEmitter, Event from ...ext.ordereddict import OrderedDict from ...ext.six import string_types from .compiler import Compiler -class ShaderChangeEvent(Event): - def __init__(self, code_changed=False, value_changed=False, **kwargs): - Event.__init__(self, type='shader_change', **kwargs) - self.code_changed = code_changed - self.value_changed = value_changed - - class ShaderObject(object): """ Base class for all objects that may be included in a GLSL program (Functions, Variables, Expressions). @@ -26,7 +20,7 @@ class ShaderObject(object): Dependencies are tracked hierarchically such that changes to any object will be propagated up the dependency hierarchy to trigger a recompile. """ - + @classmethod def create(self, obj, ref=None): """ Convert *obj* to a new ShaderObject. If the output is a Variable @@ -57,13 +51,12 @@ def create(self, obj, ref=None): return obj def __init__(self): - # emitted when any part of the code for this object has changed, - # including dependencies. - self.changed = EventEmitter(source=self, event_class=ShaderChangeEvent) - # objects that must be declared before this object's definition. # {obj: refcount} self._deps = OrderedDict() # OrderedDict for consistent code output + + # Objects that depend on this one will be informed of changes. + self._dependents = WeakKeyDictionary() @property def name(self): @@ -121,7 +114,7 @@ def _add_dep(self, dep): self._deps[dep] += 1 else: self._deps[dep] = 1 - dep.changed.connect(self._dep_changed) + dep._dependents[self] = None def _remove_dep(self, dep): """ Decrement the reference count for *dep*. If the reference count @@ -131,15 +124,23 @@ def _remove_dep(self, dep): refcount = self._deps[dep] if refcount == 1: self._deps.pop(dep) - dep.changed.disconnect(self._dep_changed) + dep._dependents.pop(self) else: self._deps[dep] -= 1 - - def _dep_changed(self, event): + + def _dep_changed(self, dep, code_changed=False, value_changed=False): """ Called when a dependency's expression has changed. """ - logger.debug("ShaderObject changed: %r" % event.source) - self.changed(event) + logger.debug("ShaderObject changed [code=%s, value=%s]", code_changed, + value_changed) + self.changed(code_changed, value_changed) + + def changed(self, code_changed=False, value_changed=False): + """Inform dependents that this shaderobject has changed. + """ + for d in self._dependents: + d._dep_changed(self, code_changed=code_changed, + value_changed=value_changed) def compile(self): """ Return a compilation of this object and its dependencies.
diff --git a/vispy/visuals/shaders/tests/test_function.py b/vispy/visuals/shaders/tests/test_function.py --- a/vispy/visuals/shaders/tests/test_function.py +++ b/vispy/visuals/shaders/tests/test_function.py @@ -314,8 +314,10 @@ def test_function_basics(): def test_function_changed(): ch = [] - def on_change(event): - ch.append(event.source) + class C(object): + def _dep_changed(self, dep, **kwargs): + ch.append(dep) + ch_obj = C() def assert_changed(*objs): assert set(ch) == set(objs) @@ -323,7 +325,7 @@ def assert_changed(*objs): ch.pop() fun1 = Function('void main(){$var1; $var2;}') - fun1.changed.connect(on_change) + fun1._dependents[ch_obj] = None fun1['var1'] = 'x' fun1['var2'] = 'y' assert_changed(fun1) @@ -337,7 +339,7 @@ def assert_changed(*objs): fun1['var1'] = 0.5 var1 = fun1['var1'] - var1.changed.connect(on_change) + var1._dependents[ch_obj] = None assert_changed(fun1) var1.name = 'xxx' @@ -354,7 +356,7 @@ def assert_changed(*objs): # test variable disconnect fun1['var1'] = Variable('var1', 7) var2 = fun1['var1'] - var2.changed.connect(on_change) + var2._dependents[ch_obj] = None #assert_changed(fun1) # var2 is now connected var2.value = (1, 2, 3, 4) @@ -371,9 +373,9 @@ def assert_changed(*objs): fun1['var2'] = exp1 assert_changed(fun1) - fun2.changed.connect(on_change) - fun3.changed.connect(on_change) - exp1.changed.connect(on_change) + fun2._dependents[ch_obj] = None + fun3._dependents[ch_obj] = None + exp1._dependents[ch_obj] = None fun2['var1'] = 'x' assert_changed(fun1, fun2, exp1)
A recent commit caused a big framerate drop in 3d The commit (found by bisection) is 6e82de1b3408555f6ce23b45b4568b66e2e86eb4. I'm not sure if it only affects 3d scenes, but that's the only place I've directly experienced it. After asking on gitter about it, I checked if it's fixed by #873, but it seems it isn't. I first noticed this in one of my own scenes, with a small number of visuals, that previously could be updated at 60fps with no issues but following this commit takes well over a second to update under mouse interaction. It's also detectable (but less obvious) in e.g. the examples/basics/visuals/tube.py example, though the framerate drop is not too large. This can be demonstrated by directly reverting 6e82de1b3408555f6ce23b45b4568b66e2e86eb4 , after which the problem is resolved (others are reintroduced, including the breaking of depth-testing, but it demonstrates that this commit is where the issue directly appears).
The problematic line seems to be 243 in vispy/visuals/shaders/function.py, though the real issue could be something elsewhere listening to the events and doing too much in response, I'm not sure what is intended here.
2015-05-03T01:52:49
vispy/vispy
930
vispy__vispy-930
[ "929" ]
6936898f862425dc677e06ee6dcfcdd4667cfd8d
diff --git a/vispy/gloo/gl/gl2.py b/vispy/gloo/gl/gl2.py --- a/vispy/gloo/gl/gl2.py +++ b/vispy/gloo/gl/gl2.py @@ -11,6 +11,7 @@ from . import _copy_gl_functions from ._constants import * # noqa +from ...util import logger # Ctypes stuff @@ -43,9 +44,11 @@ else: _fname = ctypes.util.find_library('GL') if not _fname: - raise RuntimeError('Could not load OpenGL library.') - # Load lib - _lib = ctypes.cdll.LoadLibrary(_fname) + logger.warning('Could not load OpenGL library.') + _lib = None + else: + # Load lib + _lib = ctypes.cdll.LoadLibrary(_fname) def _have_context(): @@ -62,6 +65,8 @@ def _get_gl_version(_lib): def _get_gl_func(name, restype, argtypes): # Based on a function in Pyglet + if _lib is None: + raise RuntimeError('Could not load OpenGL library, gl cannot be used') try: # Try using normal ctypes stuff func = getattr(_lib, name)
Importing gloo should not automatically load the OpenGL library I'm trying to run vispy on a headless server with docker, to use the ipynb webgl backend exclusively. I cannot `import vispy.gloo`: ``` File "/opt/conda/lib/python3.4/site-packages/vispy/gloo/__init__.py", line 47, in <module> from . import gl # noqa File "/opt/conda/lib/python3.4/site-packages/vispy/gloo/gl/__init__.py", line 213, in <module> from . import gl2 as default_backend # noqa File "/opt/conda/lib/python3.4/site-packages/vispy/gloo/gl/gl2.py", line 46, in <module> raise RuntimeError('Could not load OpenGL library.') RuntimeError: Could not load OpenGL library. ``` I should not need to have the OpenGL library on a headless server when using a remote backend.
I think it should be fine to not have this happen. It will probably mean nesting some `from . import gl` calls. Do you have time to fix it? Not sure i'll have time in the near future.. for now i just install the libs and it works, but it would be nice to have it fixed eventually!
2015-05-26T14:17:29
vispy/vispy
938
vispy__vispy-938
[ "937", "937" ]
2e72df7ba38e129ef3049c1e7e0e31f5a4c5c364
diff --git a/vispy/scene/cameras/cameras.py b/vispy/scene/cameras/cameras.py --- a/vispy/scene/cameras/cameras.py +++ b/vispy/scene/cameras/cameras.py @@ -1003,7 +1003,7 @@ def viewbox_mouse_event(self, event): elif 1 in event.buttons and keys.SHIFT in modifiers: # Translate norm = np.mean(self._viewbox.size) - if self._event_value is None: + if self._event_value is None or len(self._event_value) == 2: self._event_value = self.center dist = (p1 - p2) / norm * self._scale_factor dist[1] *= -1
Problem with turn ans shift key event In a Canvas with a turnable Camera, if you try to make a left click to turn the mesh and if you maintain the left click and after you press shift key you are an error message. Problem with turn ans shift key event In a Canvas with a turnable Camera, if you try to make a left click to turn the mesh and if you maintain the left click and after you press shift key you are an error message.
2015-05-28T11:24:16
vispy/vispy
939
vispy__vispy-939
[ "935" ]
558187503810af5b9bceaa51f1a84056310c71a1
diff --git a/make/make.py b/make/make.py --- a/make/make.py +++ b/make/make.py @@ -183,12 +183,15 @@ def test(self, arg): * examples - run all examples * examples [examples paths] - run given examples """ + # Note: By default, "python make full" *will* produce coverage data, + # whereas vispy.test('full') will not. This is because users won't + # really care about coveraged, but developers will. if not arg: return self.help('test') from vispy import test try: args = arg.split(' ') - test(args[0], ' '.join(args[1:])) + test(args[0], ' '.join(args[1:]), coverage=True) except Exception as err: print(err) if not isinstance(err, RuntimeError): diff --git a/vispy/util/logs.py b/vispy/util/logs.py --- a/vispy/util/logs.py +++ b/vispy/util/logs.py @@ -4,7 +4,6 @@ import base64 import logging -import math import sys import inspect import re @@ -30,7 +29,7 @@ def _get_vispy_caller(): line = str(record[0].f_lineno) func = record[3] cls = record[0].f_locals.get('self', None) - clsname = "" if cls is None else cls.__class__.__name__ + '.' + clsname = "" if cls is None else cls.__class__.__name__ + '.' caller = "{0}:{1}{2}({3}): ".format(module, clsname, func, line) return caller return 'unknown' @@ -314,7 +313,7 @@ def _handle_exception(ignore_callback_errors, print_callback_errors, obj, ii = registry[key] # Use logarithmic selection # (1, 2, ..., 10, 20, ..., 100, 200, ...) - if ii % (10 ** int(math.log10(ii))) == 0: + if ii == (2 ** int(np.log2(ii))): this_print = ii else: this_print = None diff --git a/vispy/visuals/line/line.py b/vispy/visuals/line/line.py --- a/vispy/visuals/line/line.py +++ b/vispy/visuals/line/line.py @@ -358,10 +358,13 @@ def draw(self, transforms): # Do we want to use OpenGL, and can we? GL = None - try: - import OpenGL.GL as GL - except ImportError: - pass + from vispy.app._default_app import default_app + if default_app is not None and \ + default_app.backend_name != 'ipynb_webgl': + try: + import OpenGL.GL as GL + except Exception: # can be other than ImportError sometimes + pass # Turn on line smooth and/or line width if GL:
diff --git a/vispy/app/tests/test_app.py b/vispy/app/tests/test_app.py --- a/vispy/app/tests/test_app.py +++ b/vispy/app/tests/test_app.py @@ -58,7 +58,7 @@ def _test_callbacks(canvas): backend._on_mouse_scroll(_id, 1, 0) backend._on_mouse_motion(_id, 10, 10) backend._on_close(_id) - elif 'qt' in backend_name.lower(): + elif any(x in backend_name.lower() for x in ('qt', 'pyside')): # constructing fake Qt events is too hard :( pass elif 'sdl2' in backend_name.lower(): @@ -230,13 +230,13 @@ def fake(event): 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] + # 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] + # attribute = program.attributes[0] program["pos"] = [1, 2, 3, 4] # use a real program diff --git a/vispy/scene/cameras/tests/__init__.py b/vispy/scene/cameras/tests/__init__.py new file mode 100644 diff --git a/vispy/testing/__init__.py b/vispy/testing/__init__.py --- a/vispy/testing/__init__.py +++ b/vispy/testing/__init__.py @@ -46,5 +46,6 @@ save_testing_image, TestingCanvas, has_pyopengl, # noqa run_tests_if_main, assert_is, assert_in, assert_not_in, assert_equal, - assert_not_equal, assert_raises, assert_true) # noqa + assert_not_equal, assert_raises, assert_true, # noqa + raises) # noqa from ._runners import test # noqa diff --git a/vispy/testing/_runners.py b/vispy/testing/_runners.py --- a/vispy/testing/_runners.py +++ b/vispy/testing/_runners.py @@ -14,64 +14,75 @@ from ..util import use_log_level, run_subprocess from ..util.ptime import time -from ._testing import SkipTest, has_backend, has_application, nottest +from ._testing import SkipTest, has_application, nottest _line_sep = '-' * 70 -def _get_root_dir(): - root_dir = os.getcwd() - if (op.isfile(op.join(root_dir, 'setup.py')) and - op.isdir(op.join(root_dir, 'vispy'))): +def _get_import_dir(): + import_dir = op.abspath(op.join(op.dirname(__file__), '..')) + up_dir = op.join(import_dir, '..') + if (op.isfile(op.join(up_dir, 'setup.py')) and + op.isdir(op.join(up_dir, 'vispy')) and + op.isdir(op.join(up_dir, 'examples'))): dev = True else: - root_dir = op.abspath(op.join(op.dirname(__file__), '..', '..')) - dev = True if op.isfile(op.join(root_dir, 'setup.py')) else False - return root_dir, dev + dev = False + return import_dir, dev _unit_script = """ -import pytest +try: + import pytest as tester +except ImportError: + import nose as tester try: import faulthandler faulthandler.enable() except Exception: pass -raise SystemExit(pytest.main(%r)) +raise SystemExit(tester.main(%r)) """ -def _unit(mode, extra_arg_string): +def _unit(mode, extra_arg_string, coverage=False): """Run unit tests using a particular mode""" - cwd = os.getcwd() + import_dir = _get_import_dir()[0] + cwd = op.abspath(op.join(import_dir, '..')) + extra_args = [''] + extra_arg_string.split(' ') + del extra_arg_string + use_pytest = False try: import pytest # noqa, analysis:ignore + use_pytest = True except ImportError: - print('Skipping pytest, pytest not installed') - raise SkipTest() + try: + import nose # noqa, analysis:ignore + except ImportError: + raise SkipTest('Skipping unit tests, pytest not installed') if mode == 'nobackend': msg = 'Running tests with no backend' - extra_arg_string = '-m "not vispy_app_test" ' + extra_arg_string - coverage = True + if use_pytest: + extra_args += ['-m', '"not vispy_app_test"'] + else: + extra_args += ['-a', '"!vispy_app_test"'] else: - with use_log_level('warning', print_msg=False): - has, why_not = has_backend(mode, out=['why_not']) - if not has: - msg = ('Skipping tests for backend %s, not found (%s)' - % (mode, why_not)) - print(_line_sep + '\n' + msg + '\n' + _line_sep + '\n') - raise SkipTest(msg) msg = 'Running tests with %s backend' % mode - extra_arg_string = '-m vispy_app_test ' + extra_arg_string - coverage = True - if coverage: - extra_arg_string += ' --cov vispy --no-cov-on-fail ' + if use_pytest: + extra_args += ['-m', 'vispy_app_test'] + else: + extra_args += ['-a', 'vispy_app_test'] + if coverage and use_pytest: + extra_args += ['--cov', 'vispy', '--no-cov-on-fail'] # make a call to "python" so that it inherits whatever the system # thinks is "python" (e.g., virtualenvs) - cmd = [sys.executable, '-c', _unit_script % extra_arg_string] + extra_arg_string = ' '.join(extra_args) + insert = extra_arg_string if use_pytest else extra_args + extra_args += [import_dir] # positional argument + cmd = [sys.executable, '-c', _unit_script % insert] env = deepcopy(os.environ) # We want to set this for all app backends plus "nobackend" to @@ -83,26 +94,32 @@ def _unit(mode, extra_arg_string): % (_line_sep, msg, env_str, extra_arg_string)) print(msg) sys.stdout.flush() - return_code = run_subprocess(cmd, return_code=True, cwd=cwd, env=env, - stdout=None, stderr=None)[2] + return_code = run_subprocess(cmd, return_code=True, cwd=cwd, + env=env, stdout=None, stderr=None)[2] if return_code: raise RuntimeError('unit failure (%s)' % return_code) - else: - out_name = '.coverage.%s' % mode + if coverage: + # Running a py.test with coverage will wipe out any files that + # exist as .coverage or .coverage.*. It should work to pass + # COVERAGE_FILE env var when doing run_subprocess above, but + # it does not. Therefore we instead use our own naming scheme, + # and in Travis when we combine them, use COVERAGE_FILE with the + # `coverage combine` command. + out_name = op.join(cwd, '.vispy-coverage.%s' % mode) if op.isfile(out_name): os.remove(out_name) - os.rename('.coverage', out_name) + os.rename(op.join(cwd, '.coverage'), out_name) def _flake(): """Test flake8""" orig_dir = os.getcwd() - root_dir, dev = _get_root_dir() - os.chdir(root_dir) + import_dir, dev = _get_import_dir() + os.chdir(op.join(import_dir, '..')) if dev: sys.argv[1:] = ['vispy', 'examples', 'make'] else: - sys.argv[1:] = ['vispy'] + sys.argv[1:] = [op.basename(import_dir)] sys.argv.append('--ignore=E226,E241,E265,E266,W291,W293,W503') sys.argv.append('--exclude=six.py,py24_ordereddict.py,glfw.py,' '_proxy.py,_es2.py,_gl2.py,_pyopengl2.py,' @@ -135,16 +152,14 @@ def _check_line_endings(): print('Running line endings check... ') sys.stdout.flush() report = [] - root_dir, dev = _get_root_dir() - if not dev: - root_dir = op.join(root_dir, 'vispy') - for dirpath, dirnames, filenames in os.walk(root_dir): + import_dir, dev = _get_import_dir() + for dirpath, dirnames, filenames in os.walk(import_dir): for fname in filenames: if op.splitext(fname)[1] in ('.pyc', '.pyo', '.so', '.dll'): continue # Get filename filename = op.join(dirpath, fname) - relfilename = op.relpath(filename, root_dir) + relfilename = op.relpath(filename, import_dir) # Open and check try: with open(filename, 'rb') as fid: @@ -203,7 +218,7 @@ def _examples(fnames_str): Can be a space-separated list of paths to test, or an empty string to auto-detect and run all examples. """ - root_dir, dev = _get_root_dir() + import_dir, dev = _get_import_dir() reason = None if not dev: reason = 'Cannot test examples unless in vispy git directory' @@ -226,7 +241,7 @@ def _examples(fnames_str): else: fnames = [op.join(d[0], fname) - for d in os.walk(op.join(root_dir, 'examples')) + for d in os.walk(op.join(import_dir, '..', 'examples')) for fname in d[2] if fname.endswith('.py')] fnames = sorted(fnames, key=lambda x: x.lower()) @@ -282,7 +297,7 @@ def _examples(fnames_str): @nottest -def test(label='full', extra_arg_string=''): +def test(label='full', extra_arg_string='', coverage=False): """Test vispy software Parameters @@ -292,6 +307,8 @@ def test(label='full', extra_arg_string=''): 'flake', or any backend name (e.g., 'qt'). extra_arg_string : str Extra arguments to sent to ``pytest``. + coverage : bool + If True, collect coverage data. """ from vispy.app.backends import BACKEND_NAMES as backend_names label = label.lower() @@ -302,16 +319,18 @@ def test(label='full', extra_arg_string=''): if label not in known_types + backend_names: raise ValueError('label must be one of %s, or a backend name %s, ' 'not \'%s\'' % (known_types, backend_names, label)) - work_dir = _get_root_dir()[0] - orig_dir = os.getcwd() # figure out what we actually need to run runs = [] if label in ('full', 'unit'): for backend in backend_names: - runs.append([partial(_unit, backend, extra_arg_string), + runs.append([partial(_unit, backend, extra_arg_string, coverage), backend]) elif label in backend_names: - runs.append([partial(_unit, label, extra_arg_string), label]) + runs.append([partial(_unit, label, extra_arg_string, coverage), label]) + + if label in ('full', 'unit', 'nobackend'): + runs.append([partial(_unit, 'nobackend', extra_arg_string, coverage), + 'nobackend']) if label == "examples": # take the extra arguments so that specific examples can be run @@ -321,9 +340,6 @@ def test(label='full', extra_arg_string=''): # run all the examples runs.append([partial(_examples, ""), 'examples']) - if label in ('full', 'unit', 'nobackend'): - runs.append([partial(_unit, 'nobackend', extra_arg_string), - 'nobackend']) if label in ('full', 'extra', 'lineendings'): runs.append([_check_line_endings, 'lineendings']) if label in ('full', 'extra', 'flake'): @@ -333,7 +349,6 @@ def test(label='full', extra_arg_string=''): skip = [] for run in runs: try: - os.chdir(work_dir) run[0]() except RuntimeError as exp: print('Failed: %s' % str(exp)) @@ -349,9 +364,7 @@ def test(label='full', extra_arg_string=''): traceback.print_exception(type_, value, tb) else: print('Passed\n') - finally: - sys.stdout.flush() - os.chdir(orig_dir) + sys.stdout.flush() dt = time() - t0 stat = '%s failed, %s skipped' % (fail if fail else 0, skip if skip else 0) extra = 'failed' if fail else 'succeeded' diff --git a/vispy/testing/_testing.py b/vispy/testing/_testing.py --- a/vispy/testing/_testing.py +++ b/vispy/testing/_testing.py @@ -125,6 +125,25 @@ def assert_is(expr1, expr2, msg=None): raise AssertionError(_format_msg(msg, std_msg)) +class raises(object): + """Helper class to test exception raising""" + def __init__(self, exc): + self.exc = exc + + def __enter__(self): + return self + + def __exit__(self, exc_typ, exc, tb): + if isinstance(exc, self.exc): + return True + elif exc is None: + raise AssertionError("Expected %s (no exception raised)" % + self.exc.__name__) + else: + raise AssertionError("Expected %s, got %s instead" % + (self.exc.__name__, type(exc).__name__)) + + ############################################################################### # GL stuff diff --git a/vispy/testing/image_tester.py b/vispy/testing/image_tester.py --- a/vispy/testing/image_tester.py +++ b/vispy/testing/image_tester.py @@ -57,7 +57,7 @@ tester = None -def get_tester(): +def _get_tester(): global tester if tester is None: tester = ImageTester() @@ -132,7 +132,7 @@ def assert_image_approved(image, standard_file, message=None, **kwargs): "%s`\n" % (std_file, data_path, standard_file)) if config['audit_tests']: sys.excepthook(*sys.exc_info()) - get_tester().test(image, std_image, message) + _get_tester().test(image, std_image, message) std_path = os.path.dirname(std_file) print('Saving new standard image to "%s"' % std_file) if not os.path.isdir(std_path): diff --git a/vispy/visuals/tests/__init__.py b/vispy/visuals/tests/__init__.py new file mode 100644 diff --git a/vispy/visuals/tests/test_rectangle.py b/vispy/visuals/tests/test_rectangle.py --- a/vispy/visuals/tests/test_rectangle.py +++ b/vispy/visuals/tests/test_rectangle.py @@ -7,9 +7,8 @@ from vispy.scene import visuals, transforms from vispy.testing import (requires_application, TestingCanvas, - run_tests_if_main) + run_tests_if_main, raises) from vispy.testing.image_tester import assert_image_approved -from pytest import raises @requires_application() @@ -36,7 +35,7 @@ def test_rectangle_draw(): width=80., radius=10., border_color='white') c.draw_visual(rectpolygon) - assert_image_approved("screenshot", 'visuals/rectpolygon4.png', + assert_image_approved("screenshot", 'visuals/rectpolygon4.png', min_corr=0.5) rectpolygon = visuals.Rectangle(pos=(50, 50, 0), height=60., @@ -71,7 +70,7 @@ def test_rectpolygon_draw(): rectpolygon.transform = transforms.STTransform(scale=(1.5, 0.5), translate=(50, 50)) c.draw_visual(rectpolygon) - assert_image_approved("screenshot", 'visuals/rectpolygon8.png', + assert_image_approved("screenshot", 'visuals/rectpolygon8.png', min_corr=0.5) rectpolygon = visuals.Rectangle(pos=(0., 0.), height=60., diff --git a/vispy/visuals/tests/test_volume.py b/vispy/visuals/tests/test_volume.py --- a/vispy/visuals/tests/test_volume.py +++ b/vispy/visuals/tests/test_volume.py @@ -1,17 +1,16 @@ # -*- coding: utf-8 -*- import numpy as np -from pytest import raises from vispy import scene from vispy.testing import (TestingCanvas, requires_application, - run_tests_if_main, requires_pyopengl) + run_tests_if_main, requires_pyopengl, + raises) from vispy.testing.image_tester import assert_image_approved @requires_pyopengl() def test_volume(): - vol = np.zeros((20, 20, 20), 'float32') vol[8:16, 8:16, :] = 1.0 @@ -28,7 +27,7 @@ def test_volume(): V.set_data(vol, (0.5, 0.8)) assert V.clim == (0.5, 0.8) with raises(ValueError): - V.set_data(vol, (0.5, 0.8, 1.0)) + V.set_data((0.5, 0.8, 1.0)) # Method V.method = 'iso' @@ -53,7 +52,7 @@ def test_volume_draw(): np.random.seed(2376) vol = np.random.normal(size=(20, 20, 20), loc=0.5, scale=0.2) vol[8:16, 8:16, :] += 1.0 - V = scene.visuals.Volume(vol, parent=v.scene) # noqa + scene.visuals.Volume(vol, parent=v.scene) # noqa v.camera.set_range() assert_image_approved(c.render(), 'visuals/volume.png') diff --git a/vispy/visuals/transforms/tests/__init__.py b/vispy/visuals/transforms/tests/__init__.py new file mode 100644
vispy.test() is broken for pip-installed vispy The tarball on PyPI does not include documentation, examples, or the `make` directory. The readme does not indicate any other way of running tests, so I have no way of verifying that my installation is correct (besides running random scripts).
I was under the impression that PyPI packages should be minimal so they don't take up more space than they need. @jdreaver indeed. AFAIK this is consistent with what other packages (numpy, scipy, scikit-learn, etc.) do to keep download sizes small. You should be able to do: ``` Python >>> import vispy >>> vispy.test() ``` But it's currently broken. I'll change the title here as a reminder to fix it, and update the README to tell people they can run it. For sure, leaving out documentation is understandable; I just mentioned it in case it was unintentional. But it would definitely be good to have those tests working (even if just minimal). I tried out `vispy.test()`, and I see this error: ``` Running tests with pyqt4 backend: _VISPY_TESTING_APP=pyqt4 -m vispy_app_test --cov vispy --no-cov-on-fail usage: -c [options] [file_or_dir] [file_or_dir] [...] -c: error: unrecognized arguments: --cov --no-cov-on-fail Failed: unit failure (2) ``` Now, it's obvious that I need `pytest-cov`, but I don't think it should be a requirement anywhere other than Travis (if that's possible.) Yeah, even with `pytest-cov` installed I get an error that needs to be fixed :) But yes, I agree that shouldn't be required. If I comment out the coverage stuff, then I get three errors in `vispy/gloo/gl/tests/test_functionality.py` (for both `pyqt4` and `pyglet` backends), other Qt backends do not run because the first one is loaded, the `nobackend` test seems to load extra tests from _other_ packages, and the remaining backends are skipped because I don't have the dependencies.
2015-05-28T17:24:25
vispy/vispy
969
vispy__vispy-969
[ "962" ]
b71f5f49d4196bd0b8b5d49b1d08822b2b0ecb63
diff --git a/vispy/mpl_plot/_mpl_to_vispy.py b/vispy/mpl_plot/_mpl_to_vispy.py --- a/vispy/mpl_plot/_mpl_to_vispy.py +++ b/vispy/mpl_plot/_mpl_to_vispy.py @@ -65,7 +65,6 @@ def open_axes(self, ax, props): # a['position'] # add borders vb = ViewBox(parent=self.canvas.scene, border_color='black', bgcolor=props['axesbg']) - vb.clip_method = 'fbo' # necessary for bgcolor vb.camera = PanZoomCamera() vb.camera.set_range(xlim, ylim, margin=0) ax_dict = dict(ax=ax, bounds=bounds, vb=vb, lims=xlim+ylim)
mpl_plot example no longer works This example currently shows the background and axes, but nothing within. ![screenshot from 2015-06-02 23-12-15](https://cloud.githubusercontent.com/assets/302469/7952015/e9301e06-097c-11e5-9a8b-acc3f6a40a44.png)
If you aren't sick of debugging and contributing to `vispy`, you can use [git bisect](http://webchick.net/node/99) to figure out whose fault it is :) Otherwise I can try to get to it in the next few days. ``` a3da64aff000a857c94cc5e93fd83bdb8a24a9c2 is the first bad commit commit a3da64aff000a857c94cc5e93fd83bdb8a24a9c2 Author: Eric Larson Date: Tue May 19 14:17:09 2015 -0700 FIX: Fix background colors :040000 040000 6f29bdb23d600a8aa29cee399b7f6a5a73133b30 626fe043168886ed882b07614db468b60f21311d M examples :040000 040000 edc6f6888b53f0cdaf862bcba5edcb347b53fd08 02e8b446164ede9c232fa4910fe7d04591bc2322 M vispy ``` Oh great :) That was a commit that should have fixed how ViewBox backgrounds got drawn. Somehow it must be getting drawn out of order. I'll try to look soon.
2015-06-03T16:08:10
vispy/vispy
978
vispy__vispy-978
[ "972" ]
fd265a81f68f6e17babf0252e8e19ca33ba6a385
diff --git a/vispy/util/config.py b/vispy/util/config.py --- a/vispy/util/config.py +++ b/vispy/util/config.py @@ -94,7 +94,7 @@ def _init(): VISPY_HELP = """ VisPy command line arguments: - --vispy-backend=(qt|pyqt4|pyt5|pyside|glfw|pyglet|sdl2|wx) + --vispy-backend=(qt|pyqt4|pyqt5|pyside|glfw|pyglet|sdl2|wx) Selects the backend system for VisPy to use. This will override the default backend selection in your configuration file.
docs error - should be PyQt5 was reading [config.py ](https://github.com/vispy/vispy/blob/75b683ed080440e881a2d0066b9ce182f4217569/vispy/util/config.py#L97), and I think it should be `pyqt4|pyqt5|...` rather that `pyt5` line no. 97
yes indeed, please fix in your next PR :)
2015-06-04T11:28:02
vispy/vispy
982
vispy__vispy-982
[ "977" ]
bc2d3047acf26a81f1c0d8f9175324e044e89459
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -134,5 +134,6 @@ def package_tree(pkgroot): 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', + 'Framework :: IPython' ], ) diff --git a/vispy/ipython/__init__.py b/vispy/ipython/__init__.py new file mode 100644 --- /dev/null +++ b/vispy/ipython/__init__.py @@ -0,0 +1,12 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, Vispy Development Team. +# Distributed under the (new) BSD License. See LICENSE.txt for more info. +""" +This module provides the binding between Vispy and IPython in the form of +an IPython extension +""" + +# load the two functions that IPython uses to instantiate an extension +# that way, the user only needs to run %load_ext vispy.ipython rather that +# %load_ext vispy.ipython.ipython +from .ipython import load_ipython_extension, unload_ipython_extension # noqa diff --git a/vispy/ipython/ipython.py b/vispy/ipython/ipython.py new file mode 100644 --- /dev/null +++ b/vispy/ipython/ipython.py @@ -0,0 +1,49 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, Vispy Development Team. +# Distributed under the (new) BSD License. See LICENSE.txt for more info. +"""Entry point for vispy's IPython bindings""" + +from distutils.version import LooseVersion + + +def load_ipython_extension(ipython): + """ Entry point of the IPython extension + + Parameters + ---------- + + IPython : IPython interpreter + An instance of the IPython interpreter that is handed + over to the extension + """ + import IPython + + # don't continue if IPython version is < 3.0 + ipy_version = LooseVersion(IPython.__version__) + if ipy_version < LooseVersion("3.0.0"): + ipython.write_err("Your IPython version is older than " + "version 3.0.0, the minimum for Vispy's" + "IPython backend. Please upgrade your IPython" + "version.") + return + + _load_webgl_backend(ipython) + + +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 unload_ipython_extension(ipython): + """ Unload the IPython extension + """ + pass
diff --git a/vispy/app/tests/test_ipython.py b/vispy/app/tests/test_ipython.py new file mode 100644 --- /dev/null +++ b/vispy/app/tests/test_ipython.py @@ -0,0 +1,41 @@ +# -*- coding: utf-8 -*- +# Copyright (c) 2015, Vispy Development Team. +# Distributed under the (new) BSD License. See LICENSE.txt for more info. +"""Tests for Vispy's IPython bindings""" + +# from vispy import IPython +from numpy.testing import assert_equal, assert_raises +from vispy.testing import requires_ipython + + +@requires_ipython(2.0) +def test_webgl_loading(): + """Test if the vispy.ipython extension loads the webGL backend + on IPython 3.0 and greater. + + Test if it fails to load the webGL backend for IPython versions + less that 3.0""" + + import IPython + from distutils.version import LooseVersion + from IPython.testing.globalipapp import get_ipython + + ipy = get_ipython() + ipy.run_cell("from vispy import app") + + if LooseVersion(IPython.__version__) >= LooseVersion("3.0.0"): + ipy.run_cell("%load_ext vispy.ipython") + ipy.run_cell("backend_name = app.use_app().backend_name") + # make sure that the webgl backend got loaded + assert_equal(ipy.user_ns["backend_name"], "ipynb_webgl") + else: + ipy.run_cell("%load_ext vispy.ipython") + ipy.run_cell("backend_name = app.use_app().backend_name") + + # the above call should have failed, and thus the key + # backend_name should not exist in the namespace + + def invalid_backend_access(ipy): + ipy.user_ns["backend_name"] + + assert_raises(KeyError, invalid_backend_access, ipy) diff --git a/vispy/testing/__init__.py b/vispy/testing/__init__.py --- a/vispy/testing/__init__.py +++ b/vispy/testing/__init__.py @@ -40,7 +40,8 @@ to determine what automatic tests are run. """ -from ._testing import (SkipTest, requires_application, requires_img_lib, # noqa +from ._testing import (SkipTest, requires_application, requires_ipython, # noqa + requires_img_lib, # noqa has_backend, requires_pyopengl, # noqa requires_scipy, has_matplotlib, # noqa save_testing_image, TestingCanvas, has_pyopengl, # noqa diff --git a/vispy/testing/_testing.py b/vispy/testing/_testing.py --- a/vispy/testing/_testing.py +++ b/vispy/testing/_testing.py @@ -242,6 +242,34 @@ def requires_img_lib(): return np.testing.dec.skipif(not has_img_lib, 'imageio or PIL required') +def has_ipython(version='3.0'): + """function that checks the presence of IPython""" + + # typecast version to a string, in case an integer is given + version = str(version) + + try: + import IPython # noqa + except Exception: + return False, "IPython library not found" + else: + if LooseVersion(IPython.__version__) >= LooseVersion(version): + return True, "IPython present" + else: + message = ( + "current IPython version: (%s) is " + "older than expected version: (%s)") % \ + (IPython.__version__, version) + + return False, message + + +def requires_ipython(version='3.0'): + ipython_present, message = has_ipython(version) + + return np.testing.dec.skipif(not ipython_present, message) + + def has_matplotlib(version='1.2'): """Determine if mpl is a usable version""" try:
automatically launch vispy in webgl mode if in notebook This could be a nice usability improvement, to have vispy automatically pickup the webgl back end if its running in a notebook. AFAIK, this is possible to detect since ipython provides a config object that can be used to query status. If there's a consensus on this, I'll try and write a pull request for this
That would be nice. You can use this: ``` python def in_ipython(): try: __IPYTHON__ except NameError: return False else: return True ``` I don't think that's enough: that only tells you if you're in `ipython` or not, not if you're in the notebook. For that you'd need to load the cfg object that ipython provides I guess -1: I often use desktop backends in the notebook, to have multiple popups also the webgl backend is too experimental at this point to be enabled by default finally, the kernel doesn't know whether you are in a notebook, and you'd need some ugly hacks to detect that i'd rather have an explicit `enable_notebook()` function, like in matplotlib, mpld3, and all other plotting libraries that work in the notebook @rossant we basically have that already with `use_app('ipynb_webgl')`, right? yes, i imagine we could save a few characters and improve tab completion discovery with such a function and we might want to enable other stuff in the notebook later @Eric89GXL yes, but that's not very nice to use, right? API wise :) It's too much internal detail (what is an "app"? why do I need to invoke "webgl"? stuff like that) There should be one (preferably obvious) way of doing things as much as possible. In this case maybe it's not obvious. At the same time I'd rather not increase the number of ways. So my problem with this is, say someone wants to use the Pyglet or SDL backend, what function should they use? Should we make separate functions for those? Maybe we can rename a function, or its arguments, or move it to a different namespace to make things clearer. Can you come up with an API that would be more intuitive in light of these issues? `enable_notebook()` could enable not only the app backend but also things like JavaScript modules etc, so it would not be equivalent to just `use_app`. The notebook backend is quite different from all the other backends (desktop) so I don't see a problem with that. I agree that functionally it operates differently (remote communication etc.), but we have actually constructed it to be as equivalent as possible to other backends in terms of the experience for end users. FWIW I see this as an advantage. Sure the backend does more complex processing, but all we have to do to use it is `use_app('ipynb_webgl')` to use it. If and when we needed more backend-specific options, they could go in the `use_app` function, especially since other backends might also need extensions at some point. Actually such options would probably go in the Canvas constructor, but we can cross that bridge later... To put it slightly differently, consider what would happen if we added some other backend that we think of as being "different" from our desktop ones. Maybe we find a way to embed our plots in a matplotlib axes instance, do we use `enable_matplotlib()`? We have talked about using GLFW as our main backend -- what if `qt` adds some cool remote features that we want to incorporate, do we add an `enable_qt_remote()` function? I don't find this as simple as the current solution, even if the current naming is bad. I think of all of these as being particular instances of instantiating an application to use, even if what they do under the hood is quite different. On one hand I agree with Eric, but I also recognise that users are going to forget (and thus having to look up) the "ipynb_webgl" name (at least I do). For desktop use, people actually do not need it in general, because Vispy is smart enough to select a good default app, this is not so much the case for the notebook (because the IPython folks deliberately made it hard to detect whether you're running in a notebook). Therefore, in this case I think practicality beats purity, and I would be in favour of a `enable_notebook()` function, that simply calls `use_app()`. what if we changed the name to `use_backend` or `enable_backend()`, then the name would be given in the docstring? or maybe we should just change the name of the backend to `notebook` (we can keep an alias to the old one if we want) so it would just be `enable_backend('notebook')`? That to me is almost the same and prevents future namespace pollution. Have you thought of creating an IPython extension instead? One that automatically switches backends and tunes whatever else might be necessary. It would work something like [holoviews](https://ioam.github.io/holoviews/) and should be familiar to any IPython user (e.g., `%load_ext vispy.ipython`). (Note: I am basing my understanding of the holoviews extension on the one line that appears at the beginning of the linked page, but that seems reasonable.) +1 for that solution, it seems like the nicest way to integrate. For now I guess all it would do is call `use_app`. Any takers for a PR? @bollu if you have time? @Eric89GXL I'm not sure as to what the plumbing needed for that is. I'll definitely take a look and outline what you need for this though. @QuLogic do we need a extension or a magic command? Like, matplotlib is just `%matplotlib` [like so](https://ipython.org/ipython-doc/dev/interactive/magics.html#magic-matplotlib), which is considered a "magic function", that is given access to `iPython's` context when it is called. However, an extension is way more extensive and gives close to complete control over the iPython shell. [docs for extension](http://ipython.org/ipython-doc/dev/config/extensions/#ipython-extensions). I'm guessing we would want it to be an extension for maximum future flexibility, but I still felt that this could be argued upon. I'm not sure you can create a magic command without installing an extension in the first place, but I didn't look too deeply into that side of it. @QuLogic if you load a module, it works. So I'm assuming somewhere in the pipeline of vispy, we check if we're running inside ipython, and then load the custom magic command module. [the docs are here](https://ipython.org/ipython-doc/dev/config/custommagics.html) I think the extension is the way to go Le dimanche 7 juin 2015, Siddharth [email protected] a écrit : > @QuLogic https://github.com/QuLogic if you load a module, it works. So > I'm assuming somewhere in the pipeline of vispy, we check if we're running > inside ipython, and then load the custom magic command module. the docs > are here https://ipython.org/ipython-doc/dev/config/custommagics.html > > — > Reply to this email directly or view it on GitHub > https://github.com/vispy/vispy/issues/977#issuecomment-109654568. @rossant very well. I'll try and get a pull request (WIP) that's a stub in an hour or so. We can move the discussion there, agreed?
2015-06-06T23:46:44
vispy/vispy
995
vispy__vispy-995
[ "993" ]
f529171f5557c75569a76445bb13028cf5640052
diff --git a/make/make.py b/make/make.py --- a/make/make.py +++ b/make/make.py @@ -180,6 +180,7 @@ def test(self, arg): * extra - run extra tests (line endings and style) * lineendings - test line ending consistency * flake - flake style testing (PEP8 and more) + * docs - test docstring parameters for correctness * examples - run all examples * examples [examples paths] - run given examples """
diff --git a/vispy/testing/_runners.py b/vispy/testing/_runners.py --- a/vispy/testing/_runners.py +++ b/vispy/testing/_runners.py @@ -8,6 +8,7 @@ import sys import os +import warnings from os import path as op from copy import deepcopy from functools import partial @@ -111,6 +112,30 @@ def _unit(mode, extra_arg_string, coverage=False): os.rename(op.join(cwd, '.coverage'), out_name) +def _docs(): + """test docstring paramters + using vispy/utils/tests/test_docstring_parameters.py""" + dev = _get_import_dir()[1] + + if not dev: + warnings.warn("Docstring test imports Vispy from" + " Vispy's installation. It is" + " recommended to setup Vispy using" + " 'python setup.py develop'" + " so that the latest sources are used automatically") + try: + # this should always be importable + from vispy.util.tests import test_docstring_parameters + print("Running docstring test...") + test_docstring_parameters.test_docstring_parameters() + except AssertionError as docstring_violations: + # the test harness expects runtime errors, + # not AssertionError. So wrap the AssertionError + # that is thrown by test_docstring_parameters() + # with a RuntimeError + raise RuntimeError(docstring_violations) + + def _flake(): """Test flake8""" orig_dir = os.getcwd() @@ -304,7 +329,7 @@ def test(label='full', extra_arg_string='', coverage=False): ---------- label : str Can be one of 'full', 'unit', 'nobackend', 'extra', 'lineendings', - 'flake', or any backend name (e.g., 'qt'). + 'flake', 'docs', or any backend name (e.g., 'qt'). extra_arg_string : str Extra arguments to sent to ``pytest``. coverage : bool @@ -314,7 +339,7 @@ def test(label='full', extra_arg_string='', coverage=False): label = label.lower() label = 'pytest' if label == 'nose' else label known_types = ['full', 'unit', 'lineendings', 'extra', 'flake', - 'nobackend', 'examples'] + 'docs', 'nobackend', 'examples'] if label not in known_types + backend_names: raise ValueError('label must be one of %s, or a backend name %s, ' @@ -344,6 +369,9 @@ def test(label='full', extra_arg_string='', coverage=False): runs.append([_check_line_endings, 'lineendings']) if label in ('full', 'extra', 'flake'): runs.append([_flake, 'flake']) + if label in ('extra', 'docs'): + runs.append([_docs, 'docs']) + t0 = time() fail = [] skip = []
Allow make.py test flake to run docstring tests as well As of now, `make.py test flake` does _not_ test the docstrings, which means the docstring tests present at `vispy/util/tests/test_docstring_parameters.py` need to be run separately. Forgetting that step means waiting for the CI to pass the build, have that fail after 5 minutes, and then fix the docstrings again. I propose to allow `make.py test flake`` to run the docstring tests as well (all forms of linting we have, basically) Thoughts?
2015-06-20T09:38:34
vispy/vispy
1,031
vispy__vispy-1031
[ "1028" ]
73c54c55c2a9875f14e55184cc1eaf43b262677a
diff --git a/examples/basics/scene/point_cloud.py b/examples/basics/scene/point_cloud.py new file mode 100644 --- /dev/null +++ b/examples/basics/scene/point_cloud.py @@ -0,0 +1,47 @@ +# -*- coding: utf-8 -*- +# vispy: gallery 10 +# Copyright (c) 2015, Vispy Development Team. +# Distributed under the (new) BSD License. See LICENSE.txt for more info. + +""" Demonstrates use of visual.Markers to create a point cloud with a +standard turntable camera to fly around with and a centered 3D Axis. +""" + +import numpy as np +import vispy.scene +from vispy.scene import visuals + +# +# Make a canvas and add simple view +# +canvas = vispy.scene.SceneCanvas(keys='interactive', show=True) +view = canvas.central_widget.add_view() + + +# generate data +pos = np.random.normal(size=(100000, 3), scale=0.2) +# one could stop here for the data generation, the rest is just to make the +# data look more interesting. Copied over from magnify.py +centers = np.random.normal(size=(50, 3)) +indexes = np.random.normal(size=100000, loc=centers.shape[0]/2., + scale=centers.shape[0]/3.) +indexes = np.clip(indexes, 0, centers.shape[0]-1).astype(int) +scales = 10**(np.linspace(-2, 0.5, centers.shape[0]))[indexes][:, np.newaxis] +pos *= scales +pos += centers[indexes] + +# create scatter object and fill in the data +scatter = visuals.Markers() +scatter.set_data(pos, edge_color=None, face_color=(1, 1, 1, .5), size=5) + +view.add(scatter) + +view.camera = 'turntable' # or try 'arcball' + +# add a colored 3D axis for orientation +axis = visuals.XYZAxis(parent=view.scene) + +if __name__ == '__main__': + import sys + if sys.flags.interactive != 1: + vispy.app.run()
Need simple scene point cloud demo So far only a complex grid-with-3-views example with 2D markers exist. I was certainly in the need of something simple like this and after a lot of digging and experimenting I reduced `magnify.py` to its minimum and added a third dimension to the markers. I think this could serve well as an intro demo for the absolute beginner like me. Let me know where should I point a pull request to or if I should wait until you guys have finished the MOAPR ;) ``` python """ Demonstrates use of visual.Markers to create a point cloud with a standard turntable camera to fly around with and a centered 3D Axis. """ import numpy as np import vispy.scene from vispy.scene import visuals # # Make a canvas and add simple view # canvas = vispy.scene.SceneCanvas(keys='interactive', show=True) view = canvas.central_widget.add_view() # generate data centers = np.random.normal(size=(50, 3)) pos = np.random.normal(size=(100000, 3), scale=0.2) indexes = np.random.normal(size=100000, loc=centers.shape[0]/2., scale=centers.shape[0]/3.) indexes = np.clip(indexes, 0, centers.shape[0]-1).astype(int) scales = 10**(np.linspace(-2, 0.5, centers.shape[0]))[indexes][:, np.newaxis] pos *= scales pos += centers[indexes] # create scatter object and fill in the data scatter = visuals.Markers() scatter.set_data(pos, edge_color=None, face_color=(1, 1, 1, .5), size=5) view.add(scatter) view.camera = 'turntable' axis = visuals.XYZAxis(parent=view.scene) if __name__ == '__main__': import sys if sys.flags.interactive != 1: vispy.app.run() ``` Now let's see how hard it is to add a second marker set to this for moons and planets.. ;)
Cool! You can go ahead and make this into a PR against the current master; it won't conflict with any of the open PRs. The file should go in `examples/basics/scene`. +1 from me, a PR into `master` should indeed be fine
2015-07-30T21:44:33
vispy/vispy
1,067
vispy__vispy-1067
[ "1065" ]
bf63b893b2153b21855a9e9a5c2f57938b5324ab
diff --git a/vispy/util/svg/geometry.py b/vispy/util/svg/geometry.py --- a/vispy/util/svg/geometry.py +++ b/vispy/util/svg/geometry.py @@ -1,25 +1,33 @@ -# ---------------------------------------------------------------------------- -# Anti-Grain Geometry (AGG) - Version 2.5 -# A high quality rendering engine for C++ -# Copyright (C) 2002-2006 Maxim Shemanarev -# Contact: [email protected] -# [email protected] -# http://antigrain.com +# Anti-Grain Geometry - Version 2.4 +# Copyright (C) 2002-2005 Maxim Shemanarev (McSeem) +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: # -# AGG is free software; you can redistribute it and/or -# modify it under the terms of the GNU General Public License -# as published by the Free Software Foundation; either version 2 -# of the License, or (at your option) any later version. +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. # -# AGG is distributed in the hope that it will be useful, -# but WITHOUT ANY WARRANTY; without even the implied warranty of -# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -# GNU General Public License for more details. +# 2. Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in +# the documentation and/or other materials provided with the +# distribution. # -# You should have received a copy of the GNU General Public License -# along with AGG; if not, write to the Free Software -# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, -# MA 02110-1301, USA. +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, +# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, +# STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING +# IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +# POSSIBILITY OF SUCH DAMAGE. # ---------------------------------------------------------------------------- # # Python translation by Nicolas P. Rougier
vispy/util/svg/geometry.py: BSD (2 clause) GPL (v2 or later) Hello guyes, I am preparing the debian package of the 0.4.0 version took from pypi. since I need to do a license check before uploading, I found this discrepancy. The original license is GPL2+ and you added a BSD-2 clauses on top of that. Do you have an email of the original author which allow to relicense his code into BSD ? cheers Fred
ping @rougier this is from the SVG code I'm the one that has written this file. It's a translation from the C++ antigrain library 2.4 which was BSD but the 2.5 version switched to GPL (but the code for this file is the same). But anyway, since it is a translation (from C++ to python with a fair amount of work), do we need to keep the original license anyway (I kept it just to point to the original work) ? And as a matter of fact, the original author of the antigrain library, Maxim Shemanarev, is dead. To my understanding translation is like a derivativ work of the original author. so yes you need to keep the original verion license. If you started your work from the 2.4 version which was BSD as you said it is ok,but if you started the work from the 2.5 version it is not :(. frommy point of view having it GPL2+ is not an issue, but from the point of view of the vispy team i could be an issue :) Since the source code for that file was identical between 2.4 and 2.5 (other than the license clause), can the code considered dual licensed, then? If it is, then it seems like we should be able to put in either the BSD license clause or the GPL license clause for the translated code. In other words, we can just swap the license notice in `vispy` since the translation was based on dual BSD/GPL licensed code in the first place. @picca does that sound right to you? I would says that if the file did not changed between 2.4 and 2.5 you selec one license but not dual license. In you case you should select BSD in order to release vispy as BSD and not GPL. cheers. can you put in that case the original BSD header in te files ? I know I know this is borring but it is quit eimportant. cheers and thanks @picca I agree. I could push a simple commit and release `0.4.1` to `pip`, would that work? What is your timeline for inclusion, by the way? If it's a month or two before anything comes of it, we could try to push out a new version `0.5` before then. There have been lots of bugfixes, enhancements, and changes. I have no time line :), I can do the 0.4.0 upload with the GPL header now and wait until 0.5.0 to do the correction later. It would be nice to have also the doc and the examples in the pypi version. could you check also if all the vispy/ext/*.py are still relevant ? We (dbian) do ot like embeded code, so it would be great if your could get rid of them as much as possible. We do not like also minified code, expecially in the documentation, do you think that it would be possible to have in pypi an option during the build which I could use in order to give the debian system path of the twitter javascript code ? @QuLogic has done some work to make it so that some of the `vispy/ext` packages can be removed. Basically the entire `vispy/ext/_bundled` directory can be deleted: https://github.com/vispy/vispy/tree/master/vispy/ext/_bundled Is there some way to mark this as the case for Debian packaging, or otherwise make it easier? We want to have them in the repo for most installs so that our only hard dependency is `numpy`, but for things like Debian we can make use of system packages instead. I was under the impression that most packages don' include those things with the PyPi versions. What twitter JavaScript code are you referring to? > I was under the impression that most packages don' include those things with the PyPi versions. Stupid early post. What I meant to say was, I was under the impression that most packages don't include `doc` and `examples` with their PyPi versions. Does e.g. `matplotlib` include the `doc` and `examples` in their PyPi uploads? I was refering to the bootstrap code used in skimage them, but it seems that it is no longer part of the code of vispy. you are right the debian package of matplotlib comes fromsourceforge version=3 opts="uversionmangle=s/rc/~rc/" \ http://sf.net/matplotlib/matplotlib-(.+)\.tar.gz nevertheless it would be great to add the example directory in the pipy lik ein the git repository. It is great to test vispy for a new comer.
2015-08-18T16:19:56
vispy/vispy
1,070
vispy__vispy-1070
[ "1040" ]
a74c4f5cbbdd4aad49e4122e5688d5adda471f12
diff --git a/examples/basics/scene/sphere.py b/examples/basics/scene/sphere.py --- a/examples/basics/scene/sphere.py +++ b/examples/basics/scene/sphere.py @@ -11,14 +11,28 @@ import sys from vispy import scene -canvas = scene.SceneCanvas(keys='interactive', size=(800, 600), show=True) +from vispy.visuals.transforms import STTransform + +canvas = scene.SceneCanvas(keys='interactive', bgcolor='white', + size=(800, 600), show=True) view = canvas.central_widget.add_view() view.camera = 'arcball' -view.padding = 100 -sphere = scene.visuals.Sphere(radius=1, parent=view.scene, - edge_color='black') +sphere1 = scene.visuals.Sphere(radius=1, method='latitude', parent=view.scene, + edge_color='black') + +sphere2 = scene.visuals.Sphere(radius=1, method='ico', parent=view.scene, + edge_color='black') + +sphere3 = scene.visuals.Sphere(radius=1, rows=10, cols=10, depth=10, + method='cube', parent=view.scene, + edge_color='black') + +sphere1.transform = STTransform(translate=[-2.5, 0, 0]) +sphere3.transform = STTransform(translate=[2.5, 0, 0]) + +view.camera.set_range(x=[-3, 3]) if __name__ == '__main__' and sys.flags.interactive == 0: canvas.app.run() diff --git a/vispy/geometry/generation.py b/vispy/geometry/generation.py --- a/vispy/geometry/generation.py +++ b/vispy/geometry/generation.py @@ -297,25 +297,7 @@ def create_box(width=1, height=1, depth=1, width_segments=1, height_segments=1, return vertices, faces, outline -def create_sphere(rows, cols, radius=1.0, offset=True): - """Create a sphere - - Parameters - ---------- - rows : int - Number of rows. - cols : int - Number of columns. - radius : float - Sphere radius. - offset : bool - Rotate each row by half a column. - - Returns - ------- - sphere : MeshData - Vertices and faces computed for a spherical surface. - """ +def _latitude(rows, cols, radius, offset): verts = np.empty((rows+1, cols, 3), dtype=np.float32) # compute vertices @@ -355,6 +337,118 @@ def create_sphere(rows, cols, radius=1.0, offset=True): return MeshData(vertices=verts, faces=faces) +def _ico(radius, subdivisions): + # golden ratio + t = (1.0 + np.sqrt(5.0))/2.0 + + # vertices of a icosahedron + verts = [(-1, t, 0), + (1, t, 0), + (-1, -t, 0), + (1, -t, 0), + (0, -1, t), + (0, 1, t), + (0, -1, -t), + (0, 1, -t), + (t, 0, -1), + (t, 0, 1), + (-t, 0, -1), + (-t, 0, 1)] + + # faces of the icosahedron + faces = [(0, 11, 5), + (0, 5, 1), + (0, 1, 7), + (0, 7, 10), + (0, 10, 11), + (1, 5, 9), + (5, 11, 4), + (11, 10, 2), + (10, 7, 6), + (7, 1, 8), + (3, 9, 4), + (3, 4, 2), + (3, 2, 6), + (3, 6, 8), + (3, 8, 9), + (4, 9, 5), + (2, 4, 11), + (6, 2, 10), + (8, 6, 7), + (9, 8, 1)] + + def midpoint(v1, v2): + return ((v1[0]+v2[0])/2, (v1[1]+v2[1])/2, (v1[2]+v2[2])/2) + + # subdivision + for _ in range(subdivisions): + for idx in range(len(faces)): + i, j, k = faces[idx] + a, b, c = verts[i], verts[j], verts[k] + ab, bc, ca = midpoint(a, b), midpoint(b, c), midpoint(c, a) + verts += [ab, bc, ca] + ij, jk, ki = len(verts)-3, len(verts)-2, len(verts)-1 + faces.append([i, ij, ki]) + faces.append([ij, j, jk]) + faces.append([ki, jk, k]) + faces[idx] = [jk, ki, ij] + verts = np.array(verts) + faces = np.array(faces) + + # make each vertex to lie on the sphere + lengths = np.sqrt((verts*verts).sum(axis=1)) + verts /= lengths[:, np.newaxis]/radius + return MeshData(vertices=verts, faces=faces) + + +def _cube(rows, cols, depth, radius): + # vertices and faces of tessellated cube + verts, faces, _ = create_box(1, 1, 1, rows, cols, depth) + verts = verts['position'] + + # make each vertex to lie on the sphere + lengths = np.sqrt((verts*verts).sum(axis=1)) + verts /= lengths[:, np.newaxis]/radius + return MeshData(vertices=verts, faces=faces) + + +def create_sphere(rows=10, cols=10, depth=10, radius=1.0, offset=True, + subdivisions=3, method='latitude'): + """Create a sphere + Parameters + ---------- + rows : int + Number of rows (for method='latitude' and 'cube'). + cols : int + Number of columns (for method='latitude' and 'cube'). + depth : int + Number of depth segments (for method='cube'). + radius : float + Sphere radius. + offset : bool + Rotate each row by half a column (for method='latitude'). + subdivisions : int + Number of subdivisions to perform (for method='ico') + method : str + Method for generating sphere. Accepts 'latitude' for latitude- + longitude, 'ico' for icosahedron, and 'cube' for cube based + tessellation. + + Returns + ------- + sphere : MeshData + Vertices and faces computed for a spherical surface. + """ + if method == 'latitude': + return _latitude(rows, cols, radius, offset) + elif method == 'ico': + return _ico(radius, subdivisions) + elif method == 'cube': + return _cube(rows, cols, depth, radius) + else: + raise Exception("Invalid method. Accepts: 'latitude', 'ico', 'cube'") + + def create_cylinder(rows, cols, radius=[1.0, 1.0], length=1.0, offset=False): """Create a cylinder diff --git a/vispy/visuals/sphere.py b/vispy/visuals/sphere.py --- a/vispy/visuals/sphere.py +++ b/vispy/visuals/sphere.py @@ -17,7 +17,17 @@ class SphereVisual(CompoundVisual): radius : float The size of the sphere. cols, rows : int - Number of rows and cols that make up the sphere mesh. + Number of rows and cols that make up the sphere mesh + (for method='latitude' and 'cube'). + depth : int + Number of depth segments that make up the sphere mesh + (for method='cube'). + subdivisions : int + Number of subdivisions to perform (for method='ico'). + method : str + Method for generating sphere. Accepts 'latitude' for + latitude-longitude, 'ico' for icosahedron, and 'cube' + for cube based tessellation. vertex_colors : ndarray Same as for `MeshVisual` class. See `create_sphere` for vertex ordering. @@ -30,11 +40,12 @@ class SphereVisual(CompoundVisual): The `Color` to use when drawing the sphere edges. If `None`, then no sphere edges are drawn. """ - def __init__(self, radius=1.0, cols=30, rows=30, vertex_colors=None, - face_colors=None, color=(0.5, 0.5, 1, 1), edge_color=None, - **kwargs): + def __init__(self, radius=1.0, cols=30, rows=30, depth=30, subdivisions=3, + method='latitude', vertex_colors=None, face_colors=None, + color=(0.5, 0.5, 1, 1), edge_color=None, **kwargs): - mesh = create_sphere(cols, rows, radius=radius) + mesh = create_sphere(cols, rows, depth, radius=radius, + subdivisions=subdivisions, method=method) self._mesh = MeshVisual(vertices=mesh.get_vertices(), faces=mesh.get_faces(),
diff --git a/vispy/geometry/tests/test_generation.py b/vispy/geometry/tests/test_generation.py --- a/vispy/geometry/tests/test_generation.py +++ b/vispy/geometry/tests/test_generation.py @@ -25,7 +25,13 @@ def test_cube(): def test_sphere(): """Test sphere function""" - md = create_sphere(10, 20, radius=10) + md = create_sphere(rows=10, cols=20, radius=10, method='latitude') + radii = np.sqrt((md.get_vertices() ** 2).sum(axis=1)) + assert_allclose(radii, np.ones_like(radii) * 10) + md = create_sphere(subdivisions=5, radius=10, method='ico') + radii = np.sqrt((md.get_vertices() ** 2).sum(axis=1)) + assert_allclose(radii, np.ones_like(radii) * 10) + md = create_sphere(rows=20, cols=20, depth=20, radius=10, method='cube') radii = np.sqrt((md.get_vertices() ** 2).sum(axis=1)) assert_allclose(radii, np.ones_like(radii) * 10)
ENH: More uniform tessellation of spheres Right now our sphere tessellation is done using latitute-longitute type calculations, which are not uniform. I have some code for more even tessellation of sphere that I or someone else could add if they feel like it.
A very good approach is to start with a tetrahedon and subdividing it N times (until its smooth enough): https://code.google.com/p/visvis/source/browse/functions/solidSphere.py#14 I have pretty efficient icosahedron and octahedron subdividing, I don't know if those are better or worse I think the only difference is the exact level of smoothness that you can reach. Each time you do a subdivision, the mesh will be "twice as smooth", you cannot go in between. But you could if you chose a different initial geometry. Don't think that this point will actually be an issue. I'd just pick one shape and go with that :P I can take this up if nobody else is assigned. I already have code for sphere generation by subdividing an icosahedron. Btw, will the existing `create_sphere()` function be replaced or do we create a new function say `create_icosphere(radius, subdivisions)`? I think `create_sphere` could just be enhanced with a `method` argument or so
2015-08-20T06:27:03
vispy/vispy
1,084
vispy__vispy-1084
[ "1081" ]
b48e4d3cf410b853a74b666c475c603e46725e55
diff --git a/vispy/app/backends/ipython/_widget.py b/vispy/app/backends/ipython/_widget.py --- a/vispy/app/backends/ipython/_widget.py +++ b/vispy/app/backends/ipython/_widget.py @@ -57,7 +57,10 @@ def set_canvas(self, canvas): self.gen_event = self.canvas_backend._gen_event #setup the backend widget then. - def events_received(self, _, msg): + # In IPython < 4, these callbacks are given two arguments; in + # IPython/jupyter 4, they take 3. events_received is variadic to + # accommodate both cases. + def events_received(self, _, msg, *args): if msg['msg_type'] == 'init': self.canvas_backend._reinit_widget() elif msg['msg_type'] == 'events':
IPython WebGL Examples not working. The IPython notebook examples are not working with the latest IPython(Jupyter) 4.0 release.
I', trying the vispy notebook widget running locally on my latop (python3, latest jupyter+ipthon from git) . The `webgl_example_1.ipynb` shows a black empty canvas and the following log is printed in the output sell : ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) TypeError: events_received() takes 3 positional arguments but 4 were given --------------------------------------------------------------------------- TypeError Traceback (most recent call last) TypeError: events_received() takes 3 positional arguments but 4 were given --------------------------------------------------------------------------- TypeError Traceback (most recent call last) TypeError: events_received() takes 3 positional arguments but 4 were given ``` while in `webgl_example_2.ipynb` i got the cloud of points visualized correctly, the start/stop timer commands also works fine, but it still print out the same error log in the output cell : ``` --------------------------------------------------------------------------- TypeError Traceback (most recent call last) TypeError: events_received() takes 3 positional arguments but 4 were given --------------------------------------------------------------------------- ... ... ... ... --------------------------------------------------------------------------- TypeError Traceback (most recent call last) TypeError: events_received() takes 3 positional arguments but 4 were given --------------------------------------------------------------------------- ``` **note**: this is running locally on a laptop (osx) The same settings (software version) on a remote server running debian i got this log : ``` WARNING: could not determine DPI WARNING:vispy:could not determine DPI xdpyinfo: unable to open display "". Can't open display ``` there is an issue for this [here](https://github.com/vispy/vispy/issues/1047)
2015-09-15T12:52:19
vispy/vispy
1,113
vispy__vispy-1113
[ "966" ]
364be8c2f9911fb6c780a0467d8b142c4de87ba2
diff --git a/vispy/visuals/volume.py b/vispy/visuals/volume.py --- a/vispy/visuals/volume.py +++ b/vispy/visuals/volume.py @@ -335,6 +335,7 @@ before_loop=""" vec4 color3 = vec4(0.0); // final color vec3 dstep = 1.5 / u_shape; // step to sample derivative + gl_FragColor = vec4(0.0); """, in_loop=""" if (val > u_threshold-0.2) {
Buggy display with iso volume example Using `examples/basics/scene/volume.py` and switching to iso rendering method produces a [pretty strange view](http://youtu.be/3becSPxKIq8). ![screenshot from 2015-06-02 20-33-11](https://cloud.githubusercontent.com/assets/302469/7952618/7438357a-0986-11e5-8771-cafdb56cde95.png) System is the same as before (Intel HD 4600): ``` Platform: Linux-4.0.4-301.fc22.x86_64-x86_64-with-fedora-22-Twenty_Two Python: 3.4.2 (default, Jan 12 2015, 12:13:20) [GCC 4.9.2 20150107 (Red Hat 4.9.2-5)] Backend: PyQt4 pyqt4: ('PyQt4', '4.11.3', '4.8.6') pyqt5: None pyside: None pyglet: pyglet 1.2.1 glfw: None sdl2: None wx: None egl: EGL 1.4 (DRI2) Mesa Project: OpenGL OpenGL_ES OpenGL_ES2 OpenGL_ES3 _test: None GL version: '3.0 Mesa 10.5.4' MAX_TEXTURE_SIZE: 8192 ```
OpenGL on Intel :( I would love to see how this looks in WebGL on the same driver. Do you have a sample? I tried to throw it in the notebook, but it doesn't seem like the WebGL backend is ready for this example just yet (or I did something wrong.) No I don't think the Volume rendering works in WebGL yet. Sorry I probably should have mentioned that. On current master, it is now a bunch of purple cubes. ![screenshot from 2015-09-21 23-32-44](https://cloud.githubusercontent.com/assets/302469/10010410/1f3997b4-60b9-11e5-9d2f-010c9a335fe5.png) wow I wish all bugs were that pretty Did you try playing with the iso threshold? If that threshold is off, you can get weird results... There are artifacts on the supposed-to-be transparent regions, e.g., with a threshold at 2, which is _way_ above anything in the file, there is still this random noise: ![screenshot from 2015-09-24 03-57-07](https://cloud.githubusercontent.com/assets/302469/10068237/bd1de74c-6270-11e5-8044-43d0be4e4b7f.png) That noise seems to appear on the backfaces. i.e. when the threshold has not been reached, the sample is not transparent as it should. Is this noise the only problem? Can you try adding `gl_FragColor = vec4(0.0);` here: https://github.com/vispy/vispy/blob/master/vispy/visuals/volume.py#L336 That does help somewhat. For example, with threshold of 0.325 there is no more noise: ![screenshot from 2015-09-24 15-15-23](https://cloud.githubusercontent.com/assets/302469/10084057/625ef4fe-62cf-11e5-896d-513b43829e6f.png) With threshold of 0.125, it seems okay, but not _great_: ![screenshot from 2015-09-24 15-19-20](https://cloud.githubusercontent.com/assets/302469/10084118/bff1bf16-62cf-11e5-8d76-698b212b4545.png) With threshold of 0.0, it appears a bit blocky: ![screenshot from 2015-09-24 15-16-37](https://cloud.githubusercontent.com/assets/302469/10084073/71a63ddc-62cf-11e5-83bb-f929b4794a78.png) but I'm not sure if that's expected due to the Also, the colours are a bit random; here it is in mostly blue: ![screenshot from 2015-09-24 15-22-20](https://cloud.githubusercontent.com/assets/302469/10084180/193f1f64-62d0-11e5-9d89-1720761488b0.png) These results are as expected. It's CT data, which is inherently rather noisy. Especially with a threshold that's around the background intensity values, you'd expect to get these blocky structures. The color is probably due to the currently set colormap? Do you want to make a PR for the `gl_Fragcolor`, or shall I?
2015-10-24T05:59:25
vispy/vispy
1,136
vispy__vispy-1136
[ "1074" ]
f0add0de75287d3df29af08cacffc73bdbf5f88f
diff --git a/vispy/ext/_bundled/png.py b/vispy/ext/_bundled/png.py --- a/vispy/ext/_bundled/png.py +++ b/vispy/ext/_bundled/png.py @@ -45,8 +45,8 @@ import zlib # http://www.python.org/doc/2.4.4/lib/module-warnings.html import warnings -from .six.moves import map as imap -from .six import string_types +from ..six.moves import map as imap +from ..six import string_types import itertools diff --git a/vispy/ext/_bundled/six.py b/vispy/ext/_bundled/six.py --- a/vispy/ext/_bundled/six.py +++ b/vispy/ext/_bundled/six.py @@ -1,6 +1,6 @@ """Utilities for writing code that runs on Python 2 and 3""" -# Copyright (c) 2010-2013 Benjamin Peterson +# Copyright (c) 2010-2014 Benjamin Peterson # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal @@ -20,13 +20,15 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -import io +from __future__ import absolute_import + +import functools import operator import sys import types __author__ = "Benjamin Peterson <[email protected]>" -__version__ = "1.4.1" +__version__ = "1.8.0" # Useful for very coarse version differentiation. @@ -39,7 +41,6 @@ class_types = type, text_type = str binary_type = bytes - file_types = (io.TextIOWrapper, io.BufferedRandom) MAXSIZE = sys.maxsize else: @@ -48,7 +49,6 @@ class_types = (type, types.ClassType) text_type = unicode binary_type = str - file_types = (file, io.TextIOWrapper, io.BufferedRandom) if sys.platform.startswith("java"): # Jython always uses 32 bits. @@ -87,9 +87,9 @@ def __init__(self, name): def __get__(self, obj, tp): result = self._resolve() - setattr(obj, self.name, result) + setattr(obj, self.name, result) # Invokes __set__. # This is a bit ugly, but it avoids running this again. - delattr(tp, self.name) + delattr(obj.__class__, self.name) return result @@ -107,6 +107,27 @@ def __init__(self, name, old, new=None): def _resolve(self): return _import_module(self.mod) + def __getattr__(self, attr): + _module = self._resolve() + value = getattr(_module, attr) + setattr(self, attr, value) + return value + + +class _LazyModule(types.ModuleType): + + def __init__(self, name): + super(_LazyModule, self).__init__(name) + self.__doc__ = self.__class__.__doc__ + + def __dir__(self): + attrs = ["__doc__", "__name__"] + attrs += [attr.name for attr in self._moved_attributes] + return attrs + + # Subclasses should override this + _moved_attributes = [] + class MovedAttribute(_LazyDescr): @@ -133,9 +154,72 @@ def _resolve(self): return getattr(module, self.attr) +class _SixMetaPathImporter(object): + """ + A meta path importer to import six.moves and its submodules. + + This class implements a PEP302 finder and loader. It should be compatible + with Python 2.5 and all existing versions of Python3 + """ + def __init__(self, six_module_name): + self.name = six_module_name + self.known_modules = {} + + def _add_module(self, mod, *fullnames): + for fullname in fullnames: + self.known_modules[self.name + "." + fullname] = mod + + def _get_module(self, fullname): + return self.known_modules[self.name + "." + fullname] + + def find_module(self, fullname, path=None): + if fullname in self.known_modules: + return self + return None + + def __get_module(self, fullname): + try: + return self.known_modules[fullname] + except KeyError: + raise ImportError("This loader does not know module " + fullname) + + def load_module(self, fullname): + try: + # in case of a reload + return sys.modules[fullname] + except KeyError: + pass + mod = self.__get_module(fullname) + if isinstance(mod, MovedModule): + mod = mod._resolve() + else: + mod.__loader__ = self + sys.modules[fullname] = mod + return mod + + def is_package(self, fullname): + """ + Return true, if the named module is a package. + + We need this method to get correct spec objects with + Python 3.4 (see PEP451) + """ + return hasattr(self.__get_module(fullname), "__path__") -class _MovedItems(types.ModuleType): + def get_code(self, fullname): + """Return None + + Required, if is_package is implemented""" + self.__get_module(fullname) # eventually raises ImportError + return None + get_source = get_code # same as get_code + +_importer = _SixMetaPathImporter(__name__) + + +class _MovedItems(_LazyModule): """Lazy loading of moved objects""" + __path__ = [] # mark as package _moved_attributes = [ @@ -143,11 +227,15 @@ class _MovedItems(types.ModuleType): MovedAttribute("filter", "itertools", "builtins", "ifilter", "filter"), MovedAttribute("filterfalse", "itertools", "itertools", "ifilterfalse", "filterfalse"), MovedAttribute("input", "__builtin__", "builtins", "raw_input", "input"), + MovedAttribute("intern", "__builtin__", "sys"), MovedAttribute("map", "itertools", "builtins", "imap", "map"), MovedAttribute("range", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("reload_module", "__builtin__", "imp", "reload"), MovedAttribute("reduce", "__builtin__", "functools"), + MovedAttribute("shlex_quote", "pipes", "shlex", "quote"), MovedAttribute("StringIO", "StringIO", "io"), + MovedAttribute("UserDict", "UserDict", "collections"), + MovedAttribute("UserList", "UserList", "collections"), MovedAttribute("UserString", "UserString", "collections"), MovedAttribute("xrange", "__builtin__", "builtins", "xrange", "range"), MovedAttribute("zip", "itertools", "builtins", "izip", "zip"), @@ -156,12 +244,15 @@ class _MovedItems(types.ModuleType): MovedModule("builtins", "__builtin__"), MovedModule("configparser", "ConfigParser"), MovedModule("copyreg", "copy_reg"), + MovedModule("dbm_gnu", "gdbm", "dbm.gnu"), + MovedModule("_dummy_thread", "dummy_thread", "_dummy_thread"), MovedModule("http_cookiejar", "cookielib", "http.cookiejar"), MovedModule("http_cookies", "Cookie", "http.cookies"), MovedModule("html_entities", "htmlentitydefs", "html.entities"), MovedModule("html_parser", "HTMLParser", "html.parser"), MovedModule("http_client", "httplib", "http.client"), MovedModule("email_mime_multipart", "email.MIMEMultipart", "email.mime.multipart"), + MovedModule("email_mime_nonmultipart", "email.MIMENonMultipart", "email.mime.nonmultipart"), MovedModule("email_mime_text", "email.MIMEText", "email.mime.text"), MovedModule("email_mime_base", "email.MIMEBase", "email.mime.base"), MovedModule("BaseHTTPServer", "BaseHTTPServer", "http.server"), @@ -171,12 +262,14 @@ class _MovedItems(types.ModuleType): MovedModule("queue", "Queue"), MovedModule("reprlib", "repr"), MovedModule("socketserver", "SocketServer"), + MovedModule("_thread", "thread", "_thread"), MovedModule("tkinter", "Tkinter"), MovedModule("tkinter_dialog", "Dialog", "tkinter.dialog"), MovedModule("tkinter_filedialog", "FileDialog", "tkinter.filedialog"), MovedModule("tkinter_scrolledtext", "ScrolledText", "tkinter.scrolledtext"), MovedModule("tkinter_simpledialog", "SimpleDialog", "tkinter.simpledialog"), MovedModule("tkinter_tix", "Tix", "tkinter.tix"), + MovedModule("tkinter_ttk", "ttk", "tkinter.ttk"), MovedModule("tkinter_constants", "Tkconstants", "tkinter.constants"), MovedModule("tkinter_dnd", "Tkdnd", "tkinter.dnd"), MovedModule("tkinter_colorchooser", "tkColorChooser", @@ -192,22 +285,29 @@ class _MovedItems(types.ModuleType): MovedModule("urllib_error", __name__ + ".moves.urllib_error", "urllib.error"), MovedModule("urllib", __name__ + ".moves.urllib", __name__ + ".moves.urllib"), MovedModule("urllib_robotparser", "robotparser", "urllib.robotparser"), + MovedModule("xmlrpc_client", "xmlrpclib", "xmlrpc.client"), + MovedModule("xmlrpc_server", "SimpleXMLRPCServer", "xmlrpc.server"), MovedModule("winreg", "_winreg"), ] for attr in _moved_attributes: setattr(_MovedItems, attr.name, attr) + if isinstance(attr, MovedModule): + _importer._add_module(attr, "moves." + attr.name) del attr -moves = sys.modules[__name__ + ".moves"] = _MovedItems(__name__ + ".moves") +_MovedItems._moved_attributes = _moved_attributes +moves = _MovedItems(__name__ + ".moves") +_importer._add_module(moves, "moves") -class Module_six_moves_urllib_parse(types.ModuleType): +class Module_six_moves_urllib_parse(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_parse""" _urllib_parse_moved_attributes = [ MovedAttribute("ParseResult", "urlparse", "urllib.parse"), + MovedAttribute("SplitResult", "urlparse", "urllib.parse"), MovedAttribute("parse_qs", "urlparse", "urllib.parse"), MovedAttribute("parse_qsl", "urlparse", "urllib.parse"), MovedAttribute("urldefrag", "urlparse", "urllib.parse"), @@ -221,16 +321,26 @@ class Module_six_moves_urllib_parse(types.ModuleType): MovedAttribute("unquote", "urllib", "urllib.parse"), MovedAttribute("unquote_plus", "urllib", "urllib.parse"), MovedAttribute("urlencode", "urllib", "urllib.parse"), + MovedAttribute("splitquery", "urllib", "urllib.parse"), + MovedAttribute("splittag", "urllib", "urllib.parse"), + MovedAttribute("splituser", "urllib", "urllib.parse"), + MovedAttribute("uses_fragment", "urlparse", "urllib.parse"), + MovedAttribute("uses_netloc", "urlparse", "urllib.parse"), + MovedAttribute("uses_params", "urlparse", "urllib.parse"), + MovedAttribute("uses_query", "urlparse", "urllib.parse"), + MovedAttribute("uses_relative", "urlparse", "urllib.parse"), ] for attr in _urllib_parse_moved_attributes: setattr(Module_six_moves_urllib_parse, attr.name, attr) del attr -sys.modules[__name__ + ".moves.urllib_parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse") -sys.modules[__name__ + ".moves.urllib.parse"] = Module_six_moves_urllib_parse(__name__ + ".moves.urllib.parse") +Module_six_moves_urllib_parse._moved_attributes = _urllib_parse_moved_attributes + +_importer._add_module(Module_six_moves_urllib_parse(__name__ + ".moves.urllib_parse"), + "moves.urllib_parse", "moves.urllib.parse") -class Module_six_moves_urllib_error(types.ModuleType): +class Module_six_moves_urllib_error(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_error""" @@ -243,11 +353,13 @@ class Module_six_moves_urllib_error(types.ModuleType): setattr(Module_six_moves_urllib_error, attr.name, attr) del attr -sys.modules[__name__ + ".moves.urllib_error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib_error") -sys.modules[__name__ + ".moves.urllib.error"] = Module_six_moves_urllib_error(__name__ + ".moves.urllib.error") +Module_six_moves_urllib_error._moved_attributes = _urllib_error_moved_attributes + +_importer._add_module(Module_six_moves_urllib_error(__name__ + ".moves.urllib.error"), + "moves.urllib_error", "moves.urllib.error") -class Module_six_moves_urllib_request(types.ModuleType): +class Module_six_moves_urllib_request(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_request""" @@ -284,16 +396,19 @@ class Module_six_moves_urllib_request(types.ModuleType): MovedAttribute("urlcleanup", "urllib", "urllib.request"), MovedAttribute("URLopener", "urllib", "urllib.request"), MovedAttribute("FancyURLopener", "urllib", "urllib.request"), + MovedAttribute("proxy_bypass", "urllib", "urllib.request"), ] for attr in _urllib_request_moved_attributes: setattr(Module_six_moves_urllib_request, attr.name, attr) del attr -sys.modules[__name__ + ".moves.urllib_request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib_request") -sys.modules[__name__ + ".moves.urllib.request"] = Module_six_moves_urllib_request(__name__ + ".moves.urllib.request") +Module_six_moves_urllib_request._moved_attributes = _urllib_request_moved_attributes +_importer._add_module(Module_six_moves_urllib_request(__name__ + ".moves.urllib.request"), + "moves.urllib_request", "moves.urllib.request") -class Module_six_moves_urllib_response(types.ModuleType): + +class Module_six_moves_urllib_response(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_response""" @@ -307,11 +422,13 @@ class Module_six_moves_urllib_response(types.ModuleType): setattr(Module_six_moves_urllib_response, attr.name, attr) del attr -sys.modules[__name__ + ".moves.urllib_response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib_response") -sys.modules[__name__ + ".moves.urllib.response"] = Module_six_moves_urllib_response(__name__ + ".moves.urllib.response") +Module_six_moves_urllib_response._moved_attributes = _urllib_response_moved_attributes + +_importer._add_module(Module_six_moves_urllib_response(__name__ + ".moves.urllib.response"), + "moves.urllib_response", "moves.urllib.response") -class Module_six_moves_urllib_robotparser(types.ModuleType): +class Module_six_moves_urllib_robotparser(_LazyModule): """Lazy loading of moved objects in six.moves.urllib_robotparser""" @@ -322,20 +439,26 @@ class Module_six_moves_urllib_robotparser(types.ModuleType): setattr(Module_six_moves_urllib_robotparser, attr.name, attr) del attr -sys.modules[__name__ + ".moves.urllib_robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib_robotparser") -sys.modules[__name__ + ".moves.urllib.robotparser"] = Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser") +Module_six_moves_urllib_robotparser._moved_attributes = _urllib_robotparser_moved_attributes + +_importer._add_module(Module_six_moves_urllib_robotparser(__name__ + ".moves.urllib.robotparser"), + "moves.urllib_robotparser", "moves.urllib.robotparser") class Module_six_moves_urllib(types.ModuleType): """Create a six.moves.urllib namespace that resembles the Python 3 namespace""" - parse = sys.modules[__name__ + ".moves.urllib_parse"] - error = sys.modules[__name__ + ".moves.urllib_error"] - request = sys.modules[__name__ + ".moves.urllib_request"] - response = sys.modules[__name__ + ".moves.urllib_response"] - robotparser = sys.modules[__name__ + ".moves.urllib_robotparser"] + __path__ = [] # mark as package + parse = _importer._get_module("moves.urllib_parse") + error = _importer._get_module("moves.urllib_error") + request = _importer._get_module("moves.urllib_request") + response = _importer._get_module("moves.urllib_response") + robotparser = _importer._get_module("moves.urllib_robotparser") + def __dir__(self): + return ['parse', 'error', 'request', 'response', 'robotparser'] -sys.modules[__name__ + ".moves.urllib"] = Module_six_moves_urllib(__name__ + ".moves.urllib") +_importer._add_module(Module_six_moves_urllib(__name__ + ".moves.urllib"), + "moves.urllib") def add_move(move): @@ -362,11 +485,6 @@ def remove_move(name): _func_code = "__code__" _func_defaults = "__defaults__" _func_globals = "__globals__" - - _iterkeys = "keys" - _itervalues = "values" - _iteritems = "items" - _iterlists = "lists" else: _meth_func = "im_func" _meth_self = "im_self" @@ -376,11 +494,6 @@ def remove_move(name): _func_defaults = "func_defaults" _func_globals = "func_globals" - _iterkeys = "iterkeys" - _itervalues = "itervalues" - _iteritems = "iteritems" - _iterlists = "iterlists" - try: advance_iterator = next @@ -429,21 +542,37 @@ def next(self): get_function_globals = operator.attrgetter(_func_globals) -def iterkeys(d, **kw): - """Return an iterator over the keys of a dictionary.""" - return iter(getattr(d, _iterkeys)(**kw)) +if PY3: + def iterkeys(d, **kw): + return iter(d.keys(**kw)) + + def itervalues(d, **kw): + return iter(d.values(**kw)) + + def iteritems(d, **kw): + return iter(d.items(**kw)) + + def iterlists(d, **kw): + return iter(d.lists(**kw)) +else: + def iterkeys(d, **kw): + return iter(d.iterkeys(**kw)) -def itervalues(d, **kw): - """Return an iterator over the values of a dictionary.""" - return iter(getattr(d, _itervalues)(**kw)) + def itervalues(d, **kw): + return iter(d.itervalues(**kw)) -def iteritems(d, **kw): - """Return an iterator over the (key, value) pairs of a dictionary.""" - return iter(getattr(d, _iteritems)(**kw)) + def iteritems(d, **kw): + return iter(d.iteritems(**kw)) -def iterlists(d, **kw): - """Return an iterator over the (key, [values]) pairs of a dictionary.""" - return iter(getattr(d, _iterlists)(**kw)) + def iterlists(d, **kw): + return iter(d.iterlists(**kw)) + +_add_doc(iterkeys, "Return an iterator over the keys of a dictionary.") +_add_doc(itervalues, "Return an iterator over the values of a dictionary.") +_add_doc(iteritems, + "Return an iterator over the (key, value) pairs of a dictionary.") +_add_doc(iterlists, + "Return an iterator over the (key, [values]) pairs of a dictionary.") if PY3: @@ -467,8 +596,9 @@ def int2byte(i): else: def b(s): return s + # Workaround for standalone backslash def u(s): - return unicode(s, "unicode_escape") + return unicode(s.replace(r'\\', r'\\\\'), "unicode_escape") unichr = unichr int2byte = chr def byte2int(bs): @@ -484,19 +614,16 @@ def iterbytes(buf): if PY3: - import builtins - exec_ = getattr(builtins, "exec") + exec_ = getattr(moves.builtins, "exec") def reraise(tp, value, tb=None): + if value is None: + value = tp() if value.__traceback__ is not tb: raise value.with_traceback(tb) raise value - - print_ = getattr(builtins, "print") - del builtins - else: def exec_(_code_, _globs_=None, _locs_=None): """Execute code in a namespace.""" @@ -516,14 +643,24 @@ def exec_(_code_, _globs_=None, _locs_=None): """) +print_ = getattr(moves.builtins, "print", None) +if print_ is None: def print_(*args, **kwargs): - """The new-style print function.""" + """The new-style print function for Python 2.4 and 2.5.""" fp = kwargs.pop("file", sys.stdout) if fp is None: return def write(data): if not isinstance(data, basestring): data = str(data) + # If the file has an encoding, encode unicode with it. + if (isinstance(fp, file) and + isinstance(data, unicode) and + fp.encoding is not None): + errors = getattr(fp, "errors", None) + if errors is None: + errors = "strict" + data = data.encode(fp.encoding, errors) fp.write(data) want_unicode = False sep = kwargs.pop("sep", None) @@ -563,18 +700,63 @@ def write(data): _add_doc(reraise, """Reraise an exception.""") +if sys.version_info[0:2] < (3, 4): + def wraps(wrapped, assigned=functools.WRAPPER_ASSIGNMENTS, + updated=functools.WRAPPER_UPDATES): + def wrapper(f): + f = functools.wraps(wrapped)(f) + f.__wrapped__ = wrapped + return f + return wrapper +else: + wraps = functools.wraps def with_metaclass(meta, *bases): """Create a base class with a metaclass.""" - return meta("NewBase", bases, {}) + # This requires a bit of explanation: the basic idea is to make a dummy + # metaclass for one level of class instantiation that replaces itself with + # the actual metaclass. + class metaclass(meta): + def __new__(cls, name, this_bases, d): + return meta(name, bases, d) + return type.__new__(metaclass, 'temporary_class', (), {}) + def add_metaclass(metaclass): """Class decorator for creating a class with a metaclass.""" def wrapper(cls): orig_vars = cls.__dict__.copy() + slots = orig_vars.get('__slots__') + if slots is not None: + if isinstance(slots, str): + slots = [slots] + for slots_var in slots: + orig_vars.pop(slots_var) orig_vars.pop('__dict__', None) orig_vars.pop('__weakref__', None) - for slots_var in orig_vars.get('__slots__', ()): - orig_vars.pop(slots_var) return metaclass(cls.__name__, cls.__bases__, orig_vars) - return wrapper \ No newline at end of file + return wrapper + +# Complete the moves implementation. +# This code is at the end of this module to speed up module loading. +# Turn this module into a package. +__path__ = [] # required for PEP 302 and PEP 451 +__package__ = __name__ # see PEP 366 @ReservedAssignment +if globals().get("__spec__") is not None: + __spec__.submodule_search_locations = [] # PEP 451 @UndefinedVariable +# Remove other six meta path importers, since they cause problems. This can +# happen if six is removed from sys.modules and then reloaded. (Setuptools does +# this for some reason.) +if sys.meta_path: + for i, importer in enumerate(sys.meta_path): + # Here's some real nastiness: Another "instance" of the six module might + # be floating around. Therefore, we can't use isinstance() to check for + # the six meta path importer, since the other six instance will have + # inserted an importer with different class. + if (type(importer).__name__ == "_SixMetaPathImporter" and + importer.name == __name__): + del sys.meta_path[i] + break + del i, importer +# Finally, add the importer to the meta path import hook. +sys.meta_path.append(_importer) diff --git a/vispy/ext/six.py b/vispy/ext/six.py --- a/vispy/ext/six.py +++ b/vispy/ext/six.py @@ -7,13 +7,18 @@ Handle loading six package from system or from the bundled copy """ -import imp +try: + import importlib +except ImportError: + importlib = None + import imp import io +import sys from distutils.version import StrictVersion -_SIX_MIN_VERSION = StrictVersion('1.4.1') +_SIX_MIN_VERSION = StrictVersion('1.8.0') _SIX_SEARCH_PATH = ['vispy.ext._bundled.six', 'six'] @@ -37,24 +42,32 @@ def _find_module(name, path=None): def _import_six(search_path=_SIX_SEARCH_PATH): for mod_name in search_path: - try: - mod_info = _find_module(mod_name) - except ImportError: - continue + if importlib is not None: + try: + six_mod = importlib.import_module(mod_name) + except ImportError: + continue + else: + try: + mod_info = _find_module(mod_name) + except ImportError: + continue + else: + try: + # Using __name__ causes the import to effectively overwrite + # this shim. + six_mod = imp.load_module(__name__, *mod_info) + finally: + if mod_info[0] is not None: + mod_info[0].close() try: - mod = imp.load_module(__name__, *mod_info) - finally: - if mod_info[0] is not None: - mod_info[0].close() - - try: - if StrictVersion(mod.__version__) >= _SIX_MIN_VERSION: + if StrictVersion(six_mod.__version__) >= _SIX_MIN_VERSION: break except (AttributeError, ValueError): - # Attribute error if the six module isn't what it should be and doesn't - # have a .__version__; ValueError if the version string exists but is - # somehow bogus/unparseable + # Attribute error if the six module isn't what it should be and + # doesn't have a .__version__; ValueError if the version string + # exists but is somehow bogus/unparseable continue else: raise ImportError( @@ -63,6 +76,28 @@ def _import_six(search_path=_SIX_SEARCH_PATH): "this warning consult the packager of your Vispy " "distribution.".format(_SIX_MIN_VERSION)) + # Using importlib does not overwrite this shim, so do it ourselves. + this_module = sys.modules[__name__] + if not hasattr(this_module, '_importer'): + # Copy all main six attributes. + for name, value in six_mod.__dict__.items(): + if name.startswith('__'): + continue + this_module.__dict__[name] = value + + # Tell six's importer to accept this shim's name as its own. + importer = six_mod._importer + known_modules = list(importer.known_modules.items()) + for name, mod in known_modules: + this_name = __name__ + name[len(mod_name):] + importer.known_modules[this_name] = mod + + # Turn this shim into a package just like six does. + this_module.__path__ = [] # required for PEP 302 and PEP 451 + this_module.__package__ = __name__ # see PEP 366 + if this_module.__dict__.get('__spec__') is not None: + this_module.__spec__.submodule_search_locations = [] # PEP 451 + _import_six()
Bundled six fails to import when frozen When I freeze a simple vispy program, I can't import vispy because the import logic in `vispy.ext.six` fails when frozen. I have been trying to figure out how to fix this, but I couldn't in a reasonable amount of time so I will post my progress here. Here is the script I am using to freeze the program (`freeze.py`): ``` python from cx_Freeze import setup, Executable setup_kwargs = { 'scripts': ['program.py'], 'executables': [Executable("program.py")], } setup(**setup_kwargs) ``` Here is the one-line "program" that just imports vispy (`program.py`): ``` python import vispy ``` To freeze and run, just install `vispy` and `cx_Freeze` and type: ``` sh $ python freeze.py build_exe $ ./build/exe.linux-x86_64-3.4/program ``` (Your build folder is going to be different on a non-Linux machine or if you don't use Python 3.4). This fails when vispy tries to do `imp.find_module('vispy.ext._bundled.six')`. I tried importing `six` like some of the other bundled packages if `hasattr(sys, "frozen")` is true in `vispy/ext/six.py`...: ``` python ... if hasattr(sys, "frozen"): try: from ._bundled.six import * # noqa except ImportError: from six import * # noqa else: _import_six() ... ``` ...but that didn't work. I got this error: ``` ImportError: No module named 'vispy.ext.six.moves'; 'vispy.ext.six' is not a package ``` I know @QuLogic did the bundling; do you have any ideas?
Did you try adding `vispy.ext.six` to the list of cx_freeze includes? Althought that one is just a module that is imported in several places. I would, however, expect it to be necessary to add `vispy.ext._bundled.six` to the cx_freeze includes, as its imported dynamically. I have tried both of those. I manually verified that the `vispy.ext.six` and `vispy.ext._bundled.six` modules were present in the zip file. I was wondering if @QuLogic had input on what is different between the bundled `six` and the other bundled modules in terms of importing functionality. I was under the impression that cx_Freeze uses `imp.find_module` itself, but for some reason in this context it fails. I also tried just installing `six` separately and including it in the frozen build, but the `imp.find_module` call still fails. I will try to investigate this further in the next couple of weeks. I think `six` might be different because we need a certain minimum version of `six` for compatibility. There is no difference between the bundled `six` and the others, but you are having problems with the shim. You can try leaving out the bundled copy and only using a separate copy, but the shim might still give you trouble. The shim was borrowed from Astropy and uses some crazy magic to get `six` working. I am not familiar with cx_Freeze and why it might be interfering with it. The "not a package" suggests there's a missing `__init__.py` but it should be there (unless cx_Freeze is missing it.) Perhaps it's because `imp` is deprecated in Python 3? Does it work on a Python 2 bundle? I got an example application to work! Here is a summary of what I did: - The only way I could get vispy to freeze was to undo the changes @QuLogic made to bundled libraries. More specifically, I removed the shims for `six` and `png` and moved the `six.py` and `png.py` files directly into `vispy/ext`. - I had to manually add the glsl files to the freeze script, and add a modification to `vispy/glsl/__init__.py`: ``` python ... if hasattr(sys, "frozen"): path = op.join(op.dirname(sys.executable), "vispy", "glsl") else: path = op.dirname(__file__) or '.' ... ``` - I did a similar thing for `vispy.io._data`. Here is the change to `vispy/io/datasets.py`: ``` python if hasattr(sys, "frozen"): DATA_DIR = op.join(op.dirname(sys.executable), 'vispy', 'io', '_data') else: DATA_DIR = op.join(op.dirname(__file__), '_data') ``` - I had to specify that I wanted to include`vispy.app.backends`. Here is my final `freeze.py` file: ``` python from cx_Freeze import setup, Executable import os import vispy.glsl import vispy.io glsl_folder = os.path.dirname(vispy.glsl.__file__) io_folder = os.path.dirname(vispy.io.__file__) io_data_folder = os.path.join(io_folder, "_data") data_files = [ (glsl_folder, os.path.join("vispy", "glsl")), (io_data_folder, os.path.join("vispy", "io", "_data")), ] setup_kwargs = { 'scripts': ['program.py'], 'options': { 'build_exe': { 'include_files': data_files, 'packages': [ 'vispy.app.backends', ], }, }, 'executables': [Executable("program.py")], } setup(**setup_kwargs) ``` The only real problem I see in integrating these changes is the shims for the bundled packages. I'm afraid I would have to dive deep into cx_Freeze to figure out why they don't work, and I don't have that kind of time :smile:. I guess we have to decide if allowing dependencies to be unbundled is more important than allowing users to freeze code. It would be a shame if vispy couldn't be deployed in a frozen application. Also, we could use `pkg_resources` to abstract away loading data files. Then, users wouldn't have to manually add the files to their freeze script, and we wouldn't need to add `if hasattr(sys, "frozen")` everywhere we load data. Lastly, [here](https://github.com/jdreaver/vispy/commit/01dab6b689fd2fe01d7e69560d3205648cbd8715) is a link to the full commit I made for reference. @QuLogic are the shims we have used by repos other than `astropy` (i.e., are they very common)? Is the purpose to make Debian/Fedora packaging easier? I should also note that it seems like astropy [can't be frozen either](https://github.com/astropy/astropy/pull/960), so I don't know if they have successfully worked around the shim problems. I used following dirty workaround with cx_Freeze ``` python import six .... setup_kwargs = { 'scripts': ['program.py'], 'options': { 'build_exe': { include_files': [six.__file__, ... other included files] ... ``` The problem with this approach is that this includes the six.py file which is later compiled to .pyc (created with the first run of binary release). Not sure if this is any help , definitely not so clean. The problem with Astropy is unrelated; it's much older than when they included the `six` shim. If you print the exception [here](https://github.com/vispy/vispy/blob/master/vispy/ext/six.py#L42), you can see that the shim fails to import `vispy`. That's probably a bug in cx_Freeze where it overrides `importlib` but not `imp`. However, even if you switch to `importlib` (which can't be done unilaterally since Vispy supports 2.6), you run into the same "not a package" error above. I think this can be worked around, but `six` 1.4.1 uses a completely different method to create `six.moves` than later versions. Can we bump the requirement to something more recent? It should be okay to bump the `six` requirement Thanks for the info @QuLogic!
2015-11-26T01:49:09
vispy/vispy
1,153
vispy__vispy-1153
[ "1146" ]
e9b0cf1655a08e6cac50ac6fd1119e1d3e59b02d
diff --git a/vispy/app/base.py b/vispy/app/base.py --- a/vispy/app/base.py +++ b/vispy/app/base.py @@ -4,6 +4,7 @@ from ..util import SimpleBunch import time +from timeit import default_timer class BaseApplicationBackend(object): @@ -60,6 +61,7 @@ def __init__(self, vispy_canvas): from .canvas import Canvas # Avoid circular import assert isinstance(vispy_canvas, Canvas) self._vispy_canvas = vispy_canvas + self._last_time = 0 # We set the _backend attribute of the vispy_canvas to self, # because at the end of the __init__ of the CanvasBackend @@ -186,6 +188,10 @@ def _vispy_mouse_press(self, **kwargs): return ev def _vispy_mouse_move(self, **kwargs): + if default_timer() - self._last_time < .01: + return + self._last_time = default_timer() + # default method for delivering mouse move events to the canvas kwargs.update(self._vispy_mouse_data)
Low fps with high-frequency mouse If mouse frequency is set to 1000Hz (for a specialized gaming mouses), the rendering speed falls dramatically for vispy-widgets that use scene graph. Moving a 125Hz mouse around: 80-120 fps Moving a 1000Hz mouse around: 5-20 fps Code: ``` python import numpy as np from vispy import app, scene from vispy.visuals import MarkersVisual app.use_app("PyQt4") canvas = scene.SceneCanvas(show=True) canvas.measure_fps() view = canvas.central_widget.add_view() view.camera = 'panzoom' view.camera.rect = (0, 0, 800, 800) Markers = scene.visuals.create_visual_node(MarkersVisual) vis = Markers() vis.set_data(np.array([[100, 100, 0], [400, 100, 0], [400, 400, 0], [100, 400, 0]], dtype=np.float32)) view.add(vis) app.run() ```
2016-01-15T10:13:23
vispy/vispy
1,213
vispy__vispy-1213
[ "1207" ]
053b6f40da9246db6e1746a07bc0141a3756eb14
diff --git a/vispy/util/fetching.py b/vispy/util/fetching.py --- a/vispy/util/fetching.py +++ b/vispy/util/fetching.py @@ -43,7 +43,7 @@ def load_data_file(fname, directory=None, force_download=False): fname : str The path to the file on the local system. """ - _url_root = 'https://github.com/vispy/demo-data/raw/master/' + _url_root = 'http://github.com/vispy/demo-data/raw/master/' url = _url_root + fname if directory is None: directory = config['data_path']
diff --git a/vispy/testing/image_tester.py b/vispy/testing/image_tester.py --- a/vispy/testing/image_tester.py +++ b/vispy/testing/image_tester.py @@ -377,7 +377,7 @@ def get_test_data_repo(): test_data_tag = 'test-data-5' data_path = config['test_data_path'] - git_path = 'https://github.com/vispy/test-data' + git_path = 'http://github.com/vispy/test-data' gitbase = git_cmd_base(data_path) if os.path.isdir(data_path):
problem with basic plot example Hi, I have some issues to run the following example: https://github.com/vispy/vispy/blob/master/examples/basics/plotting/colorbar.py: Im on OS X Yosemite: ``` $ python --version Python 2.7.6 vispy.sys_info(): Platform: Darwin-14.5.0-x86_64-i386-64bit Python: 2.7.6 (default, Apr 10 2014, 13:40:11) [GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)] Backend: PyQt5 pyqt4: None pyqt5: ('PyQt5', '5.6', '5.3.0') pyside: None pyglet: None glfw: None sdl2: None wx: None egl: None osmesa: None _test: None GL version: u'2.1 NVIDIA-10.4.2 310.41.35f01' MAX_TEXTURE_SIZE: 16384 Extensions: u'GL_ARB_color_buffer_float GL_ARB_depth_buffer_float GL_ARB_depth_clamp GL_ARB_depth_texture GL_ARB_draw_buffers GL_ARB_draw_elements_base_vertex GL_ARB_draw_instanced GL_ARB_fragment_program GL_ARB_fragment_program_shadow GL_ARB_fragment_shader GL_ARB_framebuffer_object GL_ARB_framebuffer_sRGB GL_ARB_half_float_pixel GL_ARB_half_float_vertex GL_ARB_imaging GL_ARB_instanced_arrays GL_ARB_multisample GL_ARB_multitexture GL_ARB_occlusion_query GL_ARB_pixel_buffer_object GL_ARB_point_parameters GL_ARB_point_sprite GL_ARB_provoking_vertex GL_ARB_seamless_cube_map GL_ARB_shader_objects GL_ARB_shader_texture_lod GL_ARB_shading_language_100 GL_ARB_shadow GL_ARB_sync GL_ARB_texture_border_clamp GL_ARB_texture_compression GL_ARB_texture_compression_rgtc GL_ARB_texture_cube_map GL_ARB_texture_env_add GL_ARB_texture_env_combine GL_ARB_texture_env_crossbar GL_ARB_texture_env_dot3 GL_ARB_texture_float GL_ARB_texture_mirrored_repeat GL_ARB_texture_non_power_of_two GL_ARB_texture_rectangle GL_ARB_texture_rg GL_ARB_transpose_matrix GL_ARB_vertex_array_bgra GL_ARB_vertex_blend GL_ARB_vertex_buffer_object GL_ARB_vertex_program GL_ARB_vertex_shader GL_ARB_window_pos GL_EXT_abgr GL_EXT_bgra GL_EXT_bindable_uniform GL_EXT_blend_color GL_EXT_blend_equation_separate GL_EXT_blend_func_separate GL_EXT_blend_minmax GL_EXT_blend_subtract GL_EXT_clip_volume_hint GL_EXT_debug_label GL_EXT_debug_marker GL_EXT_depth_bounds_test GL_EXT_draw_buffers2 GL_EXT_draw_range_elements GL_EXT_fog_coord GL_EXT_framebuffer_blit GL_EXT_framebuffer_multisample GL_EXT_framebuffer_multisample_blit_scaled GL_EXT_framebuffer_object GL_EXT_framebuffer_sRGB GL_EXT_geometry_shader4 GL_EXT_gpu_program_parameters GL_EXT_gpu_shader4 GL_EXT_multi_draw_arrays GL_EXT_packed_depth_stencil GL_EXT_packed_float GL_EXT_provoking_vertex GL_EXT_rescale_normal GL_EXT_secondary_color GL_EXT_separate_specular_color GL_EXT_shadow_funcs GL_EXT_stencil_two_side GL_EXT_stencil_wrap GL_EXT_texture_array GL_EXT_texture_compression_dxt1 GL_EXT_texture_compression_s3tc GL_EXT_texture_env_add GL_EXT_texture_filter_anisotropic GL_EXT_texture_integer GL_EXT_texture_lod_bias GL_EXT_texture_mirror_clamp GL_EXT_texture_rectangle GL_EXT_texture_shared_exponent GL_EXT_texture_sRGB GL_EXT_texture_sRGB_decode GL_EXT_timer_query GL_EXT_transform_feedback GL_EXT_vertex_array_bgra GL_APPLE_aux_depth_stencil GL_APPLE_client_storage GL_APPLE_element_array GL_APPLE_fence GL_APPLE_float_pixels GL_APPLE_flush_buffer_range GL_APPLE_flush_render GL_APPLE_object_purgeable GL_APPLE_packed_pixels GL_APPLE_pixel_buffer GL_APPLE_rgb_422 GL_APPLE_row_bytes GL_APPLE_specular_vector GL_APPLE_texture_range GL_APPLE_transform_hint GL_APPLE_vertex_array_object GL_APPLE_vertex_array_range GL_APPLE_vertex_point_size GL_APPLE_vertex_program_evaluators GL_APPLE_ycbcr_422 GL_ATI_separate_stencil GL_ATI_texture_env_combine3 GL_ATI_texture_float GL_ATI_texture_mirror_once GL_IBM_rasterpos_clip GL_NV_blend_square GL_NV_conditional_render GL_NV_depth_clamp GL_NV_fog_distance GL_NV_fragment_program_option GL_NV_fragment_program2 GL_NV_light_max_exponent GL_NV_multisample_filter_hint GL_NV_point_sprite GL_NV_texgen_reflection GL_NV_texture_barrier GL_NV_vertex_program2_option GL_NV_vertex_program3 GL_SGIS_generate_mipmap GL_SGIS_texture_edge_clamp GL_SGIS_texture_lod ' ('Numpy version:', '1.11.0') ('Qt version:', '5.3.0') ('SIP version:', '4.18') ('PyQt version:', '5.6') ``` Could you tell me what is wrong about my installation? It seems there is some issue with PyQt. Why does it search for PyQt4 if I installed PyQt5? ``` $ $ python colorbar.py INFO: Could not import backend "PyQt4": No module named PyQt4 WARNING: Traceback (most recent call last): File "colorbar.py", line 48, in <module> fig.show(run=True) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/app/canvas.py", line 429, in show self._backend._vispy_set_visible(visible) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/app/backends/_qt.py", line 335, in _vispy_set_visible self.showNormal() File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/app/backends/_qt.py", line 431, in event out = super(QtBaseCanvasBackend, self).event(ev) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/app/backends/_qt.py", line 703, in paintGL self._vispy_canvas.events.draw(region=None) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/util/event.py", line 455, in __call__ self._invoke_callback(cb, event) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/util/event.py", line 475, in _invoke_callback self, cb_event=(cb, event)) << caught exception here: >> File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/util/event.py", line 471, in _invoke_callback cb(event) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/scene/canvas.py", line 207, in on_draw self._draw_scene() File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/scene/canvas.py", line 253, in _draw_scene self.draw_visual(self.scene) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/scene/canvas.py", line 291, in draw_visual node.draw() File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/scene/visuals.py", line 98, in draw self._visual_superclass.draw(self) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/visuals/visual.py", line 588, in draw v.draw() File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/visuals/visual.py", line 588, in draw v.draw() File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/visuals/visual.py", line 432, in draw if self._prepare_draw(view=self) is False: File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/visuals/text/text.py", line 443, in _prepare_draw self._font._lowres_size) for t in text]) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/visuals/text/text.py", line 157, in _text_to_vbo glyph = font[char] File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/visuals/text/text.py", line 69, in __getitem__ self._load_char(char) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/visuals/text/text.py", line 83, in _load_char _load_glyph(self._font, char, self._glyphs) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/util/fonts/_quartz.py", line 87, in _load_glyph font = _load_font(f['face'], f['bold'], f['italic']) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/util/fonts/_quartz.py", line 46, in _load_font return _load_vispy_font(face, bold, italic) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/util/fonts/_quartz.py", line 24, in _load_vispy_font fname = _get_vispy_font_filename(face, bold, italic) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/util/fonts/_vispy_fonts.py", line 20, in _get_vispy_font_filename return load_data_file('fonts/%s' % name) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/util/fetching.py", line 68, in load_data_file _fetch_file(url, fname) File "/usr/local/Cellar/python/2.7.6/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/vispy-0.5.0.dev0-py2.7.egg/vispy/util/fetching.py", line 243, in _fetch_file 'Dataset fetching aborted (%s)' % (url, e)) RuntimeError: Error while fetching file https://github.com/vispy/demo-data/raw/master/fonts/OpenSans-Regular.ttf. Dataset fetching aborted (<urlopen error unknown url type: https>) ERROR: Invoking <bound method Fig.on_draw of <Fig (PyQt5) at 0x10992d050>> for DrawEvent ERROR: Invoking <bound method Fig.on_draw of <Fig (PyQt5) at 0x10992d050>> repeat 2 ERROR: Invoking <bound method Fig.on_draw of <Fig (PyQt5) at 0x10992d050>> repeat 4 ```
It appears the error isn't with using PyQt4 here: you can see that that's just a warning. It searches for PyQt4 just because that's a backend, and raises an error when it doesn't find it. However, your program DOES find PyQt5 and use it - the last 3 lines in your traceback show the error in Fig (PyQt5). The REAL problem comes from trying to fetch OpenSans-Regular.ttf from [here](https://github.com/vispy/demo-data/tree/master/fonts). For whatever reason, there was a failure with urllib running urllib.request.urlopen on that link to the font. Specifically, it dislikes the https at the start of the url fetch file. It's possible you could fix this by just dropping the 's' from the _url_root string on line 46 of vispy/util/fetching.py. Overall, this may just be a problem with whatever urllib VisPy is trying to import.
2016-05-10T09:24:15
vispy/vispy
1,358
vispy__vispy-1358
[ "1357" ]
dffa51d946c8f6f7a5ae5a396e165c3d2f1b8e78
diff --git a/vispy/app/backends/_wx.py b/vispy/app/backends/_wx.py --- a/vispy/app/backends/_wx.py +++ b/vispy/app/backends/_wx.py @@ -218,13 +218,19 @@ def __init__(self, *args, **kwargs): else: self._gl_context = p.context.shared.ref._gl_context + if p.position is None: + pos = wx.DefaultPosition + else: + pos = p.position + if p.parent is None: style = (wx.MINIMIZE_BOX | wx.MAXIMIZE_BOX | wx.CLOSE_BOX | wx.SYSTEM_MENU | wx.CAPTION | wx.CLIP_CHILDREN) style |= wx.NO_BORDER if not p.decorate else wx.RESIZE_BORDER style |= wx.STAY_ON_TOP if p.always_on_top else 0 - self._frame = wx.Frame(None, wx.ID_ANY, p.title, p.position, - p.size, style) + self._frame = wx.Frame(None, wx.ID_ANY, p.title, pos, p.size, + style) + if not p.resizable: self._frame.SetSizeHints(p.size[0], p.size[1], p.size[0], p.size[1]) @@ -245,7 +251,7 @@ def __init__(self, *args, **kwargs): self._frame = None self._fullscreen = False self._init = False - GLCanvas.__init__(self, parent, wx.ID_ANY, pos=p.position, + GLCanvas.__init__(self, parent, wx.ID_ANY, pos=pos, size=p.size, style=0, name='GLCanvas', attribList=self._gl_attribs)
Using wxPython 4.0.0b2 problem ``` Python 3.5.3 (default, Sep 7 2017, 16:23:57) [GCC 6.3.0 20170406] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import vispy >>> vispy.use('wx') >>> print(vispy.sys_info()) Platform: Linux-4.10.0-35-generic-x86_64-with-Ubuntu-17.04-zesty Python: 3.5.3 (default, Sep 7 2017, 16:23:57) [GCC 6.3.0 20170406] NumPy: 1.13.1 Backend: wx pyqt4: None pyqt5: None pyside: ('PySide', '1.2.2', '4.8.7') pyglet: None glfw: None sdl2: sdl2 0.9.3 wx: wxPython 4.0.0b2 egl: None osmesa: OSMesa _test: None App info-gathering error: Traceback (most recent call last): File "/home/eldar/src/vispy/vispy/util/config.py", line 432, in sys_info canvas = Canvas('Test', (10, 10), show=False, app=app) File "/home/eldar/src/vispy/vispy/app/canvas.py", line 205, in __init__ self.create_native() File "/home/eldar/src/vispy/vispy/app/canvas.py", line 222, in create_native self._app.backend_module.CanvasBackend(self, **self._backend_kwargs) File "/home/eldar/src/vispy/vispy/app/backends/_wx.py", line 227, in __init__ p.size, style) TypeError: Frame(): arguments did not match any overloaded call: overload 1: too many arguments overload 2: argument 4 has unexpected type 'NoneType' ```
2017-09-24T09:58:50
vispy/vispy
1,360
vispy__vispy-1360
[ "1359" ]
dffa51d946c8f6f7a5ae5a396e165c3d2f1b8e78
diff --git a/vispy/app/backends/_wx.py b/vispy/app/backends/_wx.py --- a/vispy/app/backends/_wx.py +++ b/vispy/app/backends/_wx.py @@ -128,7 +128,7 @@ class ApplicationBackend(BaseApplicationBackend): def __init__(self): BaseApplicationBackend.__init__(self) - self._event_loop = wx.EventLoop() + self._event_loop = wx.GUIEventLoop() wx.EventLoop.SetActive(self._event_loop) def _vispy_get_backend_name(self):
wxPython 4 deprecated call ``` Python 3.5.3 (default, Sep 7 2017, 16:23:57) [GCC 6.3.0 20170406] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import vispy >>> vispy.use('wx') >>> print(vispy.sys_info()) Platform: Linux-4.10.0-35-generic-x86_64-with-Ubuntu-17.04-zesty Python: 3.5.3 (default, Sep 7 2017, 16:23:57) [GCC 6.3.0 20170406] NumPy: 1.13.1 Backend: wx pyqt4: None pyqt5: None pyside: ('PySide', '1.2.2', '4.8.7') pyglet: None glfw: None sdl2: sdl2 0.9.3 wx: wxPython 4.0.0b2 egl: None osmesa: OSMesa _test: None ``` Warning: ``` /home/eldar/src/vispy/vispy/app/backends/_wx.py:131: wxPyDeprecationWarning: Using deprecated class EventLoop. Use GUIEventLoop instead. self._event_loop = wx.EventLoop() ```
2017-09-24T10:17:23
vispy/vispy
1,362
vispy__vispy-1362
[ "1361" ]
cb98a7890893e5759ff7232b0abe3dac6a00a741
diff --git a/examples/tutorial/app/simple_wx.py b/examples/tutorial/app/simple_wx.py --- a/examples/tutorial/app/simple_wx.py +++ b/examples/tutorial/app/simple_wx.py @@ -43,15 +43,20 @@ def __init__(self): file_menu = wx.Menu() file_menu.Append(wx.ID_EXIT, "&Quit") self.Bind(wx.EVT_MENU, self.on_quit, id=wx.ID_EXIT) + self.Bind(wx.EVT_SHOW, self.on_show) MenuBar.Append(file_menu, "&File") self.SetMenuBar(MenuBar) - self.canvas = Canvas(app="wx", parent=self, show=True) + self.canvas = Canvas(app="wx", parent=self) def on_quit(self, event): self.canvas.stop_timer() self.Close(True) + def on_show(self, event): + self.canvas.show() + event.Skip() + if __name__ == '__main__': myapp = wx.App(0)
examples/tutorial/app/simple_wx.py issue ``` Traceback (most recent call last): File "simple_wx.py", line 58, in <module> frame = TestFrame() File "simple_wx.py", line 49, in __init__ self.canvas = Canvas(app="wx", parent=self, show=True) File "simple_wx.py", line 20, in __init__ app.Canvas.__init__(self, *args, **kwargs) File "/home/eldar/src/vispy/vispy/app/canvas.py", line 208, in __init__ self.set_current() File "/home/eldar/src/vispy/vispy/app/canvas.py", line 406, in set_current self._backend._vispy_set_current() File "/home/eldar/src/vispy/vispy/app/backends/_wx.py", line 302, in _vispy_set_current self.SetCurrent(self._gl_context) wx._core.wxAssertionError: C++ assertion "xid" failed at /home/eldar/src/wx/wxPython_Phoenix/wxPython-4.0.0b2/ext/wxWidgets/src/unix/glx11.cpp(194) in SetCurrent(): window must be shown ```
I assumed with your previous PRs that you had gotten a working Canvas with wx. Did something change? @davidh-ssec It isn't related bug.
2017-09-25T18:42:00
vispy/vispy
1,377
vispy__vispy-1377
[ "1347" ]
e20cc9883b94f6ac79246b9574beb91e804a998e
diff --git a/vispy/app/backends/_qt.py b/vispy/app/backends/_qt.py --- a/vispy/app/backends/_qt.py +++ b/vispy/app/backends/_qt.py @@ -287,7 +287,12 @@ def __init__(self, *args, **kwargs): # Qt supports OS double-click events, so we set this here to # avoid double events self._double_click_supported = True - self._physical_size = p.size + if hasattr(self, 'devicePixelRatio'): + # handle high DPI displays in PyQt5 + ratio = self.devicePixelRatio() + else: + ratio = 1 + self._physical_size = (p.size[0] * ratio, p.size[1] * ratio) # Activate touch and gesture. # NOTE: we only activate touch on OS X because there seems to be
SceneCanvas central_widget display area is wrong (PyQt5 & SDL2) Hi, I tried this code, but plot area is wrong because SceneCanvas central_widget is not placed at correct area. https://github.com/vispy/vispy/issues/1189#issuecomment-198597473 I think the bug is because of PyQt5/SDL2, but I'm not familiar with Qt... <img width="764" alt="2017-07-23 1 24 02" src="https://user-images.githubusercontent.com/5352478/28493057-442f397e-6f4a-11e7-8cc9-2f5a0e2d9b2b.png"> I tried PyQt5, PyGlet, Glfw and SDL2 as backend app. In PyQt5 and SDL2, display area is wrong. In PyGlet and Glfw, display area is correct. PyGlet is a little slow, so I'll use Glfw. My environment is... OS: macOS Sierra vispy: 0.4.0 Python: 3.6.2 Qt: 5.9.1 PyQt: 5.9 SLD2: 2.0.5 PySDL2: 0.9.5 Glfw: 3.2.1 PyGlet: 1.2.4 vispy, PyGlet and PySDL2 are installed by pip. Python, Qt, PyQt, SLD2 are installed by Homebrew.
@hayashikun Thanks for the report. Can you try your code with PyQt4 and let me know how it goes? In the past I had noticed some issues with PyQt5 but assumed it was my fault. I haven't tried anything recently. This is most likely related to OSX HiDPI @Eric89GXL Very possible. I am on a Mac too. Wasn't this addressed by a PR a while ago (can't find it now)? @hayashikun Could you try installing vispy from the github `master` branch and trying PyQt5 again? If so and it still fails, what about PyQt4? Thank you for your quick response. I tried https://github.com/vispy/vispy/issues/1189#issuecomment-198597473 code in vispy master (0.5.0.dev0) with PyQt5, it still fails and it behavior is different from 0.4.0. ![output](https://user-images.githubusercontent.com/5352478/28493902-8183aec6-6f5a-11e7-85a7-9eb47f5e27a6.gif) And, I need some time to try with PyQt4 because Qt4 and PyQt4 can't install via Homebrew. 😭 @hayashikun Anaconda might be a good place to start and force `conda install pyqt<5`. Hi, I installed Anaconda and tried. It succeeded with PyQt4! PyQt5 installed by Anaconda still fail. Thanks. I'll have to look in to this later. Not sure I'll have any more time this weekend. Hello, I read source code and search the cause of this bug. First, I've compared PyQt5 and Glfw running and check variables by putting breakpoints. See gif I attached in my before comment, initially displayed view is correct even with PyQt5. A mouse click cause this invalid displaying. In my environments I told before, `pixel_scale` of Canvas is different between Glfw (correct) and PyQt5 (incorrect) **after mouse clicking**. https://github.com/vispy/vispy/blob/master/vispy/scene/canvas.py#L237 https://github.com/vispy/vispy/blob/master/vispy/app/canvas.py#L351 Just after `app.run()`, `pixel_scale = 2` both PyQt5 and Glfw. So, both display is correct. But after click some point, `pixel_scale = 1` in PyQt5 so display is incorrect. (in Glfw, `pixel_scale = 2` so display is correct) In conclusion, the reason why pixel_scale is changed is `QtBaseCanvasBackend._physical_size` is changed in `__init__`. https://github.com/vispy/vispy/blob/master/vispy/app/backends/_qt.py#L290 Correct `_physical_size` setting is done in this below. https://github.com/vispy/vispy/blob/master/vispy/app/backends/_qt.py#L694 By deleting L290, it run correctly. I'd like to submit PR for this bug fixing and discuss about detail in the PR. I'm not sure I understand your solution. Does `resizeGL` get called by the Qt system when the Qt Window is first generated? It isn't called from within vispy from what I can tell so it makes sense to use that as an initialization step. However, I also notice that `self._vispy_set_size(*p.size)` is called in the `__init__` method. Also removing that line may have consequences because it is used in `_vispy_get_physical_size()`. Any instance attribute should be initialized in the `__init__` method. Regardless, the biggest problem I have with this change is that it changes something in the `_qt.py` module that is shared between PyQt4 and PyQt5 without showing why it works in one and not the other. If I'm completely missing something about your solution, please let me know. I haven't researched it too much, but it looks like Qt5 has the method `devicePixelRatio()` that we could use in cases like this. If we used something like this we'd have to be careful that mouse events get treated properly too.
2017-10-29T16:51:45
vispy/vispy
1,380
vispy__vispy-1380
[ "1233" ]
4aeb3f2ffa41170a2ec946cfa7573854110059f3
diff --git a/vispy/util/dpi/_linux.py b/vispy/util/dpi/_linux.py --- a/vispy/util/dpi/_linux.py +++ b/vispy/util/dpi/_linux.py @@ -26,6 +26,14 @@ def _get_dpi_from(cmd, pattern, func): return func(*map(float, match.groups())) +def _xrandr_calc(x_px, y_px, x_mm, y_mm): + if x_mm == 0 or y_mm == 0: + logger.warning("'xrandr' output has screen dimension of 0mm, " + + "can't compute proper DPI") + return 96. + return 25.4 * (x_px / x_mm + y_px / y_mm) / 2 + + def get_dpi(raise_error=True): """Get screen DPI from the OS @@ -51,7 +59,7 @@ def get_dpi(raise_error=True): from_xrandr = _get_dpi_from( 'xrandr', r'(\d+)x(\d+).*?(\d+)mm x (\d+)mm', - lambda x_px, y_px, x_mm, y_mm: 25.4 * (x_px / x_mm + y_px / y_mm) / 2) + _xrandr_calc) if from_xrandr is not None: return from_xrandr if raise_error:
Vispy Linux Error ( division by zero) When I try to tun the vispy on linux I get the following error: ``` from vispy.plot import Fig f = Fig() /lib/python2.7/site-packages/vispy/util/dpi/_linux.pyc in <lambda>(x_px, y_px, x_mm, y_mm) 49 from_xrandr = _get_dpi_from( 50 'xrandr', r'(\d+)x(\d+).*?(\d+)mm x (\d+)mm', ---> 51 lambda x_px, y_px, x_mm, y_mm: 25.4 * (x_px / x_mm + y_px / y_mm) / 2) 52 if from_xrandr is not None: 53 return from_xrandr ``` ZeroDivisionError: float division by zero
I can't reproduce this on Ubuntu 14.04 and the mainline code as of Jun 15. Are you running against the mainline code? I'm still getting this on 0.4.0 and Git :/ Arch Linux EDIT: And sadly Python 2 and 3. @Lartza @motamedi79 If you are still available for testing could you try running the `xrandr` command on your machine and letting me know the input. This function is fairly simple in that it runs `xdpyinfo` and if the command fails or is not what vispy expects it tries running `xrandr` and does the same checks. It is apparently getting output from `xrandr` that it understands but one of the `mm` in the output must be 0 based on the error message. I will try reproducing this if you are not available. Can't even remember what I was trying to do with vispy back then but luckily the issue is reproducible easily. Installing xorg-xdpyinfo seems to fix it yet xdpyinfo is not indicated as a dependency of vispy anywhere at all :/ ``` [lartza@archvm ~]$ xrandr Screen 0: minimum 320 x 200, current 1360 x 768, maximum 16384 x 16384 VGA-1 connected primary 1360x768+0+0 (normal left inverted right x axis y axis) 0mm x 0mm 1360x768 59.95*+ 60.02 2560x1600 59.99 59.97 1920x1440 60.00 1856x1392 60.00 1792x1344 60.00 2048x1152 60.00 1920x1200 59.88 59.95 1920x1080 60.00 1600x1200 60.00 1680x1050 59.95 59.88 1400x1050 59.98 59.95 1600x900 60.00 1280x1024 60.02 1440x900 59.89 59.90 1280x960 60.00 1366x768 59.79 60.00 1280x800 59.81 59.91 1280x768 59.87 59.99 1280x720 60.00 1024x768 60.00 800x600 60.32 56.25 848x480 60.00 640x480 59.94 ``` @Lartza awesome. Thank you. Any idea why the `VGA-1` line ends with `0mm x 0mm` (I'm not sure what that is trying to list). Edit: Ah it's screen dimensions. I'm guessing (and googled a bit), if that should report the size of the physical screen for DPI calculations it's because it's not a physical screen but VirtualBox. But honestly don't know :P @larsoner Any objections to having this logic default to a DPI of `96.` with a warning if screen dimensions have a `0` in them? 96 is the default if `DISPLAY` isn't set or if xrandr has no recognizable output. We already default to 96 here: https://github.com/vispy/vispy/blob/acc4c4b24ff4e628253641df887a6e58fbd24a8e/vispy/util/dpi/_linux.py#L29 +1 for fixing 0 DPI -> 96 DPI (maybe with a warning?), assuming that's what you mean @davidh-ssec
2017-10-30T15:40:59
vispy/vispy
1,381
vispy__vispy-1381
[ "1259" ]
15809851fb7da72626499764cf839d98ff0b3a01
diff --git a/vispy/geometry/generation.py b/vispy/geometry/generation.py --- a/vispy/geometry/generation.py +++ b/vispy/geometry/generation.py @@ -403,7 +403,7 @@ def midpoint(v1, v2): def _cube(rows, cols, depth, radius): # vertices and faces of tessellated cube - verts, faces, _ = create_box(1, 1, 1, rows, cols, depth) + verts, faces, _ = create_box(1, 1, 1, cols, rows, depth) verts = verts['position'] # make each vertex to lie on the sphere diff --git a/vispy/visuals/sphere.py b/vispy/visuals/sphere.py --- a/vispy/visuals/sphere.py +++ b/vispy/visuals/sphere.py @@ -47,7 +47,7 @@ def __init__(self, radius=1.0, cols=30, rows=30, depth=30, subdivisions=3, method='latitude', vertex_colors=None, face_colors=None, color=(0.5, 0.5, 1, 1), edge_color=None, **kwargs): - mesh = create_sphere(cols, rows, depth, radius=radius, + mesh = create_sphere(rows, cols, depth, radius=radius, subdivisions=subdivisions, method=method) self._mesh = MeshVisual(vertices=mesh.get_vertices(),
Sphere.py rows and cols wrong way round Hi, Might be wrong, but it looks like in vispy/visuals/Sphere.py, when passing rows and cols to create_sphere, they are passed back to front. create_sphere expects rows then cols, but SphereVisual passes cols then rows. As they're unnamed, I was producing different meshes than I expected. Thanks
2017-10-31T02:05:38
vispy/vispy
1,383
vispy__vispy-1383
[ "1382" ]
fee0ef4d3c4672090ef67fc75ee76a973af8d69e
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -109,7 +109,6 @@ def package_tree(pkgroot): 'vispy': [op.join('io', '_data', '*'), op.join('html', 'static', 'js', '*'), op.join('app', 'tests', 'qt-designer.ui'), - op.join('..', 'doc', '*'), ], 'vispy.glsl': ['*.vert','*.frag', "*.glsl"],
Wrong install location for docs From `setup.py`: ``` setup( [...] package_data={ 'vispy': [op.join('io', '_data', '*'), op.join('html', 'static', 'js', '*'), op.join('app', 'tests', 'qt-designer.ui'), op.join('..', 'doc', '*'), ], ``` This line `op.join('..', 'doc', '*')` is wrong for a system-wide install. It leads to the documentation being install under `dist-packages` or `site-packages`, which is definitely non-standard. IMO, the best would be to just not install the docs yourself, and let the package build system (conda or Debian) handle it.
Hm I thought I had tested this before committing it and that it was going in the vispy directory. I had added that line to include the `doc` directory in the PyPI tarball for your Debian packaging. What would be the proper way to add the `doc` directory to `setup.py` for your packaging? As far as I can tell there is no proper way to add a directory *outside* the package directory to be inside the package directory. I would have to move the `doc` submodule (or symlink it) to inside the package. @ghisvail my understanding was that you needed the `doc` directory in PyPI, is that correct? Edit: The only other way I see for uploading documentation to PyPI is with `upload_sphinx` which puts it on pythonhosted.org.
2017-10-31T14:48:15
vispy/vispy
1,386
vispy__vispy-1386
[ "1385" ]
2a9e6692ff9a8a2a109d1ff246d57618fbba8e79
diff --git a/vispy/scene/widgets/grid.py b/vispy/scene/widgets/grid.py --- a/vispy/scene/widgets/grid.py +++ b/vispy/scene/widgets/grid.py @@ -5,7 +5,9 @@ from __future__ import division import numpy as np +from vispy.geometry import Rect from .widget import Widget +from .viewbox import ViewBox from ...ext.cassowary import (SimplexSolver, expression, Variable, WEAK, REQUIRED, @@ -25,7 +27,6 @@ class Grid(Widget): Keyword arguments to pass to `Widget`. """ def __init__(self, spacing=6, **kwargs): - from .viewbox import ViewBox self._next_cell = [0, 0] # row, col self._cells = {} self._grid_widgets = {} @@ -235,7 +236,6 @@ def add_view(self, row=None, col=None, row_span=1, col_span=1, **kwargs : dict Keyword arguments to pass to `ViewBox`. """ - from .viewbox import ViewBox view = ViewBox(**kwargs) return self.add_widget(view, row, col, row_span, col_span) @@ -495,8 +495,11 @@ def _update_child_widget_dim(self): else: y = np.sum(value_vectorized(self._height_grid[col][0:row])) - widget.size = (width, height) - widget.pos = (x, y) + if isinstance(widget, ViewBox): + widget.rect = Rect(x, y, width, height) + else: + widget.size = (width, height) + widget.pos = (x, y) @property def _widget_grid(self):
Wrong scale on X and Y axis LinePlot On lineplot initialisation the X and Y axis will often be incorrect by 1 (major) division. This can be fixed by scrolling which updates the axis numbers. This problem doesn't happen every time however. Example: `self.x = np.linspace(0, 1000, 1000) self.y = np.linspace(0, 50000, 1000)` will sometimes produce a line from -10k to 40k rather than 0 to 50k ` def initGraph(self): self.line = None self.fig = None self.fig = vp.Fig(size=(1200, 380), position=(-40, -50)) self.fig.create_native() self.fig.native.setParent(self.ui.canvas) self.x = np.linspace(0, 1000, 1000) self.y = np.linspace(0, 50000, 1000) self.line = self.fig[0, 0].plot((self.x, self.y), width=1, color='blue', xlabel='', ylabel='', marker_size=-10) self.line._line.method = 'agg' `
Currently looking in to this. Here is a complete test case: ``` import numpy as np import vispy.plot as vp from vispy import app x = np.linspace(0, 1000, 1000) y = np.linspace(0, 50000, 1000) line = None fig = None fig = vp.Fig(size=(1200, 380), position=(-40, -50)) fig.create_native() #fig.native.setParent(ui.canvas) x = np.linspace(0, 1000, 1000) y = np.linspace(0, 50000, 1000) line = fig[0, 0].plot((x, y), width=1, color='blue', xlabel='', ylabel='', marker_size=-10) line._line.method = 'agg' #fig[0, 0].xaxis._view_changed() app.run() ``` The issue seems to be some kind of race condition on the transform changing. If you uncomment the commented line above you *should* consistently get the right ranges on load. I'm still looking for a long term fix. Edit: ...nevermind. Still inconsistent.
2017-11-05T03:45:52
vispy/vispy
1,387
vispy__vispy-1387
[ "1349" ]
c1fd20ba5a8976edceee9b0838502054079d6791
diff --git a/vispy/visuals/ellipse.py b/vispy/visuals/ellipse.py --- a/vispy/visuals/ellipse.py +++ b/vispy/visuals/ellipse.py @@ -27,6 +27,8 @@ class EllipseVisual(PolygonVisual): The border color to use. border_width: float The width of the border in pixels + Line widths > 1px are only + guaranteed to work when using `border_method='agg'` method. radius : float | tuple Radius or radii of the ellipse Defaults to (0.1, 0.1) @@ -35,10 +37,12 @@ class EllipseVisual(PolygonVisual): Defaults to 0. span_angle : float Span angle of the ellipse in degrees - Defaults to 0. + Defaults to 360. num_segments : int Number of segments to be used to draw the ellipse Defaults to 100 + **kwargs : dict + Keyword arguments to pass to `PolygonVisual`. """ def __init__(self, center=None, color='black', border_color=None, border_width=1, radius=(0.1, 0.1), start_angle=0., @@ -49,11 +53,14 @@ def __init__(self, center=None, color='black', border_color=None, self._span_angle = span_angle self._num_segments = num_segments + # triangulation can be very slow + kwargs.setdefault('triangulate', False) PolygonVisual.__init__(self, pos=None, color=color, border_color=border_color, border_width=border_width, **kwargs) self._mesh.mode = "triangle_fan" + self._regen_pos() self._update() @staticmethod @@ -79,11 +86,11 @@ def _generate_vertices(center, radius, start_angle, span_angle, num_segments + 1) # PolarProjection - vertices[:-1, 0] = center[0] + xr * np.cos(theta) - vertices[:-1, 1] = center[1] + yr * np.sin(theta) + vertices[1:, 0] = center[0] + xr * np.cos(theta) + vertices[1:, 1] = center[1] + yr * np.sin(theta) - # close the curve - vertices[num_segments + 1] = np.float32([center[0], center[1]]) + # specify center point (not used in border) + vertices[0] = np.float32([center[0], center[1]]) return vertices @@ -98,6 +105,7 @@ def center(self, center): """ The center of the ellipse """ self._center = center + self._regen_pos() self._update() @property @@ -109,6 +117,7 @@ def radius(self): @radius.setter def radius(self, radius): self._radius = radius + self._regen_pos() self._update() @property @@ -120,6 +129,7 @@ def start_angle(self): @start_angle.setter def start_angle(self, start_angle): self._start_angle = start_angle + self._regen_pos() self._update() @property @@ -131,6 +141,7 @@ def span_angle(self): @span_angle.setter def span_angle(self, span_angle): self._span_angle = span_angle + self._regen_pos() self._update() @property @@ -146,34 +157,14 @@ def num_segments(self, num_segments): raise ValueError('EllipseVisual must consist of more than 1 ' 'segment') self._num_segments = num_segments + self._regen_pos() self._update() - def _update(self): - if self._center is None: - return - + def _regen_pos(self): vertices = self._generate_vertices(center=self._center, radius=self._radius, start_angle=self._start_angle, span_angle=self._span_angle, num_segments=self._num_segments) - - # NOTE: we do not use PolygonVisual's - # inbuilt update() because the triangulation method - # it uses is expensive. See discussion on - # (campagnola/vispy #2) for more details - if not self._color.is_blank: - self._mesh.set_data(vertices=vertices, - color=self._color.rgba) - - # connect vertices for a closed loop when - # drawing the border. However, delete the last - # vertex so there is no line connecting the center - # to the border - if not self._border_color.is_blank: - border_pos = vertices[:-1] - - self._border.set_data(pos=border_pos, - color=self._border_color.rgba, - width=self._border_width, - connect='strip') + # don't use the center point + self._pos = vertices[1:] diff --git a/vispy/visuals/polygon.py b/vispy/visuals/polygon.py --- a/vispy/visuals/polygon.py +++ b/vispy/visuals/polygon.py @@ -34,17 +34,32 @@ class PolygonVisual(CompoundVisual): Border color of the polygon. border_width : int Border width in pixels. + Line widths > 1px are only + guaranteed to work when using `border_method='agg'` method. + border_method : str + Mode to use for drawing the border line (see `LineVisual`). + + * "agg" uses anti-grain geometry to draw nicely antialiased lines + with proper joins and endcaps. + * "gl" uses OpenGL's built-in line rendering. This is much faster, + but produces much lower-quality results and is not guaranteed to + obey the requested line width or join/endcap styles. + + triangulate : boolean + Triangulate the set of vertices **kwargs : dict - Keyword arguments to pass to `PolygonVisual`. + Keyword arguments to pass to `CompoundVisual`. """ def __init__(self, pos=None, color='black', - border_color=None, border_width=1, **kwargs): + border_color=None, border_width=1, border_method='gl', + triangulate=True, **kwargs): self._mesh = MeshVisual() - self._border = LineVisual() + self._border = LineVisual(method=border_method) self._pos = pos self._color = Color(color) self._border_width = border_width self._border_color = Color(border_color) + self._triangulate = triangulate self._update() CompoundVisual.__init__(self, [self._mesh, self._border], **kwargs) @@ -53,25 +68,27 @@ def __init__(self, pos=None, color='black', self.freeze() def _update(self): - self.data = PolygonData(vertices=np.array(self._pos, dtype=np.float32)) if self._pos is None: return - if not self._color.is_blank: - pts, tris = self.data.triangulate() + if not self._color.is_blank and self._triangulate: + data = PolygonData(vertices=np.array(self._pos, dtype=np.float32)) + pts, tris = data.triangulate() set_state(polygon_offset_fill=False) self._mesh.set_data(vertices=pts, faces=tris.astype(np.uint32), color=self._color.rgba) + elif not self._color.is_blank: + self.mesh.set_data(vertices=self._pos, + color=self._color.rgba) if not self._border_color.is_blank: # Close border if it is not already. border_pos = self._pos - if np.any(border_pos[0] != border_pos[1]): + if np.any(border_pos[0] != border_pos[-1]): border_pos = np.concatenate([border_pos, border_pos[:1]], axis=0) self._border.set_data(pos=border_pos, color=self._border_color.rgba, - width=self._border_width, - connect='strip') + width=self._border_width) self._border.update() diff --git a/vispy/visuals/rectangle.py b/vispy/visuals/rectangle.py --- a/vispy/visuals/rectangle.py +++ b/vispy/visuals/rectangle.py @@ -28,6 +28,8 @@ class RectangleVisual(PolygonVisual): The border color to use. border_width : int Border width in pixels. + Line widths > 1px are only + guaranteed to work when using `border_method='agg'` method. height : float Length of the rectangle along y-axis Defaults to 1.0 @@ -37,6 +39,8 @@ class RectangleVisual(PolygonVisual): radius : float | array Radii of curvatures of corners in clockwise order from top-left Defaults to 0. + **kwargs : dict + Keyword arguments to pass to `PolygonVisual`. """ def __init__(self, center=None, color='black', border_color=None, border_width=1, height=1.0, width=1.0, @@ -47,32 +51,42 @@ def __init__(self, center=None, color='black', border_color=None, self._color = Color(color) self._border_color = Color(border_color) self._border_width = border_width + self._radius = radius + self._center = center - # HACK, NOTE: this order is _intentional_ - # the self._radius is set to none to block all - # calls to self._update(). This is because - # self._update() depends on having self.mesh and - # self.border which are instantiated by PolygonVisual's - # __init__ - self._radius = None - self.center = None - + # triangulation can be very slow + kwargs.setdefault('triangulate', False) PolygonVisual.__init__(self, pos=None, color=color, border_color=border_color, border_width=border_width, **kwargs) - self.radius = radius - self.center = center - self._mesh.mode = 'triangle_fan' + self._regen_pos() self._update() - def _generate_vertices(self, center, radius, height, width): - - half_height = self._height / 2. - half_width = self._width / 2. + @staticmethod + def _generate_vertices(center, radius, height, width): + half_height = height / 2. + half_width = width / 2. hw = min(half_height, half_width) + if isinstance(radius, (list, tuple)): + if len(radius) != 4: + raise ValueError("radius must be float or 4 value tuple/list" + " (got %s of length %d)" % (type(radius), + len(radius))) + + if (radius > np.ones(4) * hw).all(): + raise ValueError('Radius of curvature cannot be greater than\ + half of min(width, height)') + radius = np.array(radius, dtype=np.float32) + + else: + if radius > hw: + raise ValueError('Radius of curvature cannot be greater than\ + half of min(width, height)') + radius = np.ones(4) * radius + num_segments = (radius / hw * 500.).astype(int) bias1 = np.ones(4) * half_width - radius @@ -135,6 +149,7 @@ def center(self, center): """ The center of the ellipse """ self._center = center + self._regen_pos() self._update() @property @@ -148,6 +163,7 @@ def height(self, height): if height <= 0.: raise ValueError('Height must be positive') self._height = height + self._regen_pos() self._update() @property @@ -161,6 +177,7 @@ def width(self, width): if width <= 0.: raise ValueError('Width must be positive') self._width = width + self._regen_pos() self._update() @property @@ -171,55 +188,15 @@ def radius(self): @radius.setter def radius(self, radius): - half_height = self._height / 2. - half_width = self._width / 2. - hw = min(half_height, half_width) - - if isinstance(radius, (list, tuple)): - if len(radius) != 4: - raise ValueError("radius must be float or 4 value tuple/list" - " (got %s of length %d)" % (type(radius), - len(radius))) - - if (radius > np.ones(4) * hw).all(): - raise ValueError('Radius of curvature cannot be greater than\ - half of min(width, height)') - radius = np.array(radius, dtype=np.float32) - - else: - if radius > hw: - raise ValueError('Radius of curvature cannot be greater than\ - half of min(width, height)') - radius = np.ones(4) * radius - self._radius = radius + self._regen_pos() self._update() - def _update(self): - if not self._center: - return - - if self._radius is None: - return - + def _regen_pos(self): vertices = self._generate_vertices(center=self._center, radius=self._radius, height=self._height, width=self._width) - + # don't use the center point and only use X/Y coordinates + vertices = vertices[1:, ..., :2] self._pos = vertices - - # NOTE: Do not call PolygonVisual's _update() here because it - # uses triangulation which is super slow - if not self._color.is_blank: - self.mesh.set_data(vertices=vertices, - color=self._color.rgba) - - # when passing vertices to the Border, delete the - # vertices that creates loops since PolygonVisual - # closes loops. However, closing the loop of a solid figure - # will create a solid line from the center of the solid figure - # to the edge - if not self._border_color.is_blank: - self.border.set_data(pos=vertices[1:, ..., :2], - color=self._border_color.rgba)
diff --git a/vispy/testing/image_tester.py b/vispy/testing/image_tester.py --- a/vispy/testing/image_tester.py +++ b/vispy/testing/image_tester.py @@ -149,7 +149,8 @@ def assert_image_approved(image, standard_file, message=None, **kwargs): if std_image is None: raise Exception("Test standard %s does not exist." % std_file) else: - if os.getenv('TRAVIS') is not None: + if os.getenv('TRAVIS') is not None or \ + os.getenv('APPVEYOR') is not None: _save_failed_test(image, std_image, standard_file) raise @@ -375,7 +376,7 @@ def get_test_data_repo(): # This tag marks the test-data commit that this version of vispy should # be tested against. When adding or changing test images, create # and push a new tag and update this variable. - test_data_tag = 'test-data-6' + test_data_tag = 'test-data-7' data_path = config['test_data_path'] git_path = 'http://github.com/vispy/test-data' diff --git a/vispy/visuals/tests/test_rectangle.py b/vispy/visuals/tests/test_rectangle.py --- a/vispy/visuals/tests/test_rectangle.py +++ b/vispy/visuals/tests/test_rectangle.py @@ -53,6 +53,15 @@ def test_rectangle_draw(): assert_image_approved(c.render(), 'visuals/rectpolygon5.png') + rectpolygon.parent = None + rectpolygon = visuals.Rectangle(center=(50, 50, 0), height=60., + width=80., radius=[25, 10, 0, 15], + color='red', border_color=(0, 1, 1, 1), + border_width=5, border_method='agg', + parent=c.scene) + + assert_image_approved(c.render(), 'visuals/rectpolygon10.png') + @requires_application() def test_rectpolygon_draw():
minor: border width bug in rectangleVisual Hi, the border width argument of the rectangle.py (visuals) is not passed to the polygon class. The last lines of code in the file should be: `if not self._border_color.is_blank:` ` self.border.set_data(pos=vertices[1:, ..., :2],` ` color=self._border_color.rgba,` **`width=self._border_width`**)
The border width is provided to the `PolygonVisual.__init__` class. It is not currently possible to change the border width after init so it shouldn't need to be passed from what I understand. https://github.com/vispy/vispy/blob/master/vispy/visuals/rectangle.py#L62 Do you have some example code that doesn't work as you would expect? In this code the border width of the rectangles is ignored (at least in my setup vispy-0.5.0dev). with the above change in the rectangle.py code, the border width can be set... ` import numpy as np from vispy import gloo from vispy import app from vispy.util.transforms import perspective, translate, rotate from vispy import color from vispy import visuals from vispy.visuals import TextVisual class Canvas(app.Canvas): def __init__(self): app.Canvas.__init__(self, title='Test', keys='interactive', decorate=False, size=(1024, 800)) self.mainVP = (0, 0, 1024, 800) self.textClose = visuals.TextVisual('Close', bold=False, color='white', font_size=18, pos=[self.mainVP[2]/2 , self.mainVP[3]/2]) self.textClose.transforms.configure(canvas=self, viewport=self.mainVP) self.boxClose = visuals.RectangleVisual(center=[self.mainVP[2]/2, self.mainVP[3]/2], color=None, border_color='gray', border_width=6, height=50.0, width=100.0, radius=[10.0, 10.0, 0.0, 0.0]) self.boxClose.transforms.configure(canvas=self, viewport=self.mainVP) self.show() def on_timer(self, event): self.update() def on_resize(self, event): self.apply_zoom() def on_mouse_press(self, event): self.mousePress = event.pos clickRatio = self.mousePress / self.size if clickRatio[0] > 0.45 and clickRatio[0] < 0.55 and clickRatio[1] < 0.55 and clickRatio[1] > 0.45: print("close button") def on_draw(self, event): gloo.clear(color=True, depth=True, stencil=True) gloo.set_viewport(*self.mainVP) self.boxClose.draw() self.textClose.draw() def apply_zoom(self): gloo.set_viewport(0, 0, *self.physical_size) if __name__ == '__main__': c = Canvas() app.run() ` @cstrub Looks good and makes sense. Looks like this was caused by some changes a long time ago when some non-related updates were made to the RectangleVisual. While I'm not super happy about how those changes were done, your change is the simplest solution. Would you mind making a pull request? @Eric89GXL If they make a pull request and add a test for this, should they make a pull request for the `test-data` repository (https://github.com/vispy/test-data/tree/master/visuals)? I think that's how it's supposed to work, yeah @davidh-ssec Could you replicate the problem and the "fix"? In my setup the "fix" only works if I have pyopengl installed (3.1.1), rather than just pyqt (4.10.4). Without pyopengl the border width is always ignored. I am not deep enough into vispy to understand this effect... I would prefer if someone else could take a look at this and eventually make the changes in the repository(?)
2017-11-06T01:28:24
vispy/vispy
1,389
vispy__vispy-1389
[ "1172" ]
c1fd20ba5a8976edceee9b0838502054079d6791
diff --git a/vispy/scene/cameras/__init__.py b/vispy/scene/cameras/__init__.py --- a/vispy/scene/cameras/__init__.py +++ b/vispy/scene/cameras/__init__.py @@ -15,6 +15,9 @@ that a certain part of the scene is mapped to the bounding rectangle of the ViewBox. """ +__all__ = ['ArcballCamera', 'BaseCamera', 'FlyCamera', 'MagnifyCamera', + 'Magnify1DCamera', 'PanZoomCamera', 'TurntableCamera'] + from ._base import make_camera # noqa from .base_camera import BaseCamera # noqa from .panzoom import PanZoomCamera # noqa
Camera API documentation missing I could not find a list of available cameras in the docs: http://vispy.org/scene.html?highlight=cameras#module-vispy.scene.cameras
2017-11-06T12:05:08
vispy/vispy
1,391
vispy__vispy-1391
[ "1124" ]
911ce673e78df9cdc41dce1b1dac456e1cf13dfd
diff --git a/examples/basics/scene/one_scene_four_cams.py b/examples/basics/scene/one_scene_four_cams.py --- a/examples/basics/scene/one_scene_four_cams.py +++ b/examples/basics/scene/one_scene_four_cams.py @@ -8,11 +8,12 @@ """ Demonstrating a single scene that is shown in four different viewboxes, each with a different camera. -""" -# todo: the panzoom camera sometimes work, sometimes not. Not sure why. -# we should probably make iterating over children deterministic, so that -# an error like this becomes easier to reproduce ... +Note: + This example just creates four scenes using the same visual. + Multiple views are currently not available. See #1124 how this could + be achieved. +""" import sys @@ -22,7 +23,7 @@ canvas.size = 800, 600 canvas.show() -# Create two ViewBoxes, place side-by-side +# Create four ViewBoxes vb1 = scene.widgets.ViewBox(border_color='white', parent=canvas.scene) vb2 = scene.widgets.ViewBox(border_color='white', parent=canvas.scene) vb3 = scene.widgets.ViewBox(border_color='white', parent=canvas.scene) @@ -38,33 +39,16 @@ grid.add_widget(vb4, 1, 1) # Create some visuals to show -# AK: Ideally, we could just create one visual that is present in all -# scenes, but that results in flicker for the PanZoomCamera, I suspect -# due to errors in transform caching. im1 = io.load_crate().astype('float32') / 255 -#image1 = scene.visuals.Image(im1, grid=(20, 20), parent=scenes) for par in scenes: image = scene.visuals.Image(im1, grid=(20, 20), parent=par) -#vol1 = np.load(io.load_data_file('volume/stent.npz'))['arr_0'] -#volume1 = scene.visuals.Volume(vol1, parent=scenes) -#volume1.transform = scene.STTransform(translate=(0, 0, 10)) - # Assign cameras vb1.camera = scene.BaseCamera() vb2.camera = scene.PanZoomCamera() vb3.camera = scene.TurntableCamera() vb4.camera = scene.FlyCamera() - -# If True, show a cuboid at each camera -if False: - cube = scene.visuals.Cube((3, 3, 5)) - cube.transform = scene.STTransform(translate=(0, 0, 6)) - for vb in (vb1, vb2, vb3, vb4): - vb.camera.parents = scenes - cube.add_parent(vb.camera) - if __name__ == '__main__': if sys.flags.interactive != 1: app.run()
SceneGraph: HowTo view single scene in different viewboxes Using https://github.com/vispy/vispy/blob/master/examples/basics/scene/one_scene_four_cams.py to view a single scene in four different viewboxes doesn't work. The scene is actually generated four times, not only once. There are reminders of multi-parenting commented out in the example, but this won't work any more (since removal of multi-parenting). Is it possible to have one scene viewed from different angels (eg. top view, front view and side view) without recreating the scene four times?
Ahh crap, I thought we did a better job than that with the example :) IIRC you should be able to have multiple views of the same object / scene, it was built into the big scenegraph update. It involved having a concept of "visual views". @campagnola knows the system better than I do, though. Yeah, I read the different PRs and almost everything else from SceneGraph here, but there is no hint on howto accomplish that. It would be really nice if @campagnola could have a look. This scenegraph-ability is most-wanted here. @Eric89GXL In example https://github.com/vispy/vispy/blob/master/examples/basics/visuals/line_prototype.py I found something which seems to be the "visual view". It is shown there for a line visual. I tried to get this running with the ImageVisual but had to change some code quick and dirty to get ImageVisual (view._method_used - freeze problem) running. I finally managed to get different views of one image visual on an app.Canvas. Anyway this "visual view" works just for a single visual, not for a complete scene. @campagnola could you elaborate a bit on how to achieve simultaneous views of one scene. It should be possible, shouldn't it? In the meanwhile I try to get my scene into one visual. Any help very much appreciated! Ping @Eric89GXL @campagnola While working through open issues, is there any news on this? I would also have a look myself to figure something out. A bit of guidance or pointers what to consider and where to look is very much appreciated. Unfortunately I don't have the time or the knowledge remaining to help :( @Eric89GXL No worries! But is there some status on the whole project's whereabouts? AFAIK none of the original main devs (@rougier @rossant @almarklein @campagnola) have much time to devote to VisPy currently Yes, the current status is not clear I don't think anyone is going to work on the project anytime soon, unfortunately @kmuehlbauer, you are right that having multiple views was built into the visual system, but we stopped short of implementing this for the scenegraph as well. If you're interested in giving it a try, here's the basic idea: - `Visual` is the class that does opengl drawing. It uses a `TransformSystem` to decide how to map from its own coordinates back to the screen. From any visual you can create a `VisualView`, which allows you to render the same visual using a different `TransformSystem`. - `VisualNode` is the glue that makes visuals work inside the scenegraph, but it does not yet implement a `view()` method of its own. - You need to implement `VisualNode.view()`, which will return an instance of a new class called `ViewNode(Node)` (or similar). This new class will behave somewhat like `VisualNode`, except that there will not be a need for many subclasses like `VisualNode` has. Something like: ``` class ViewNode(Node): def __init__(self, viewed_node): self._view = self.viewed_node.view() def draw(self): self._view.draw() def _update_trsys(self, event): # update self._view.transforms here ``` - This new class will contain a reference to a `VisualView`. It's `draw()` method will call the view's `draw()` method, and its `_update_trsys()` method will update the view's transform system. - To make a view on an entire branch of the scenegraph, you would need to create a parallel graph constructed entirely of `ViewNode` instances. Ideally, this graph would automatically update itself to reflect changes in the original scenegraph branch. Let's talk more if you'd like to give it a try. Thanks @Eric89GXL, @rougier, @rossant for the status update. @campagnola Thanks for explaining how this can be achieved. I'm using scenegraph quite often and also managed to get the `VisualView` working for one visual. I'll have to learn more how scenegraph and the `VisualNode` is working in order to completely follow your notes. But I'm not give in that fast. I'll come back for asking more detailed questions and appreciate your offer for help, @campagnola.
2017-11-07T09:51:24
vispy/vispy
1,392
vispy__vispy-1392
[ "1298" ]
911ce673e78df9cdc41dce1b1dac456e1cf13dfd
diff --git a/examples/demo/gloo/two_qt_widgets.py b/examples/demo/gloo/two_qt_widgets.py new file mode 100644 --- /dev/null +++ b/examples/demo/gloo/two_qt_widgets.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python +# -*- coding: utf-8 -*- +# vispy: testskip + +""" +Example demonstrating the use of two GLCanvases in one QtApp. +""" + +from PyQt4 import QtGui, QtCore +import sys + +from fireworks import Canvas as FireCanvas +from rain import Canvas as RainCanvas + + +class MainWindow(QtGui.QMainWindow): + def __init__(self): + QtGui.QMainWindow.__init__(self) + + self.resize(1000, 500) + self.setWindowTitle('vispy example ...') + + self.splitter_h = QtGui.QSplitter(QtCore.Qt.Horizontal) + + # Central Widget + splitter1 = QtGui.QSplitter(QtCore.Qt.Horizontal) + + self.rain_canvas = RainCanvas() + self.rain_canvas.create_native() + self.rain_canvas.native.setParent(self) + self.fireworks_canvas = FireCanvas() + self.fireworks_canvas.create_native() + self.fireworks_canvas.native.setParent(self) + + splitter1.addWidget(self.fireworks_canvas.native) + splitter1.addWidget(self.rain_canvas.native) + + self.setCentralWidget(splitter1) + + +if __name__ == '__main__': + appQt = QtGui.QApplication(sys.argv) + win = MainWindow() + win.show() + appQt.exec_()
Multiple OpenGL windows not working Tested using the latest Github code from today. The GL tutorial tests (e.g. fireworks.py, cube.py) work fine within a PyQT application. But if you attempt to display two of them simultaneously (two widgets in one app) then both of them break, either corrupted graphics or failure to repaint the widget. Should two GL widgets be possible with vispy? Attached a simple test app "test.py" that shows the issue. Code is as follows and uses the standard fireworks.py, cube.py examples: ``` from PyQt5.QtCore import * from PyQt5.QtWidgets import * import cube, fireworks class Form(QWidget): def __init__(self, parent=None): super(Form, self).__init__(parent) cube_canvas = cube.Canvas() fireworks_canvas = fireworks.Canvas() Layout1 = QVBoxLayout() Layout1.addWidget(fireworks_canvas.native) Layout1.addWidget(cube_canvas.native) mainLayout = QGridLayout() mainLayout.addLayout(Layout1, 0, 1) self.setLayout(mainLayout) self.setWindowTitle("Vispy") if __name__ == '__main__': import sys app = QApplication(sys.argv) screen = Form() screen.show() sys.exit(app.exec_()) ``` [2glviews.tar.gz](https://github.com/vispy/vispy/files/685855/2glviews.tar.gz)
@kelvinlawson I'm not really sure, but this seems to be connected with the propagation of events. This gist [here](https://gist.github.com/kmuehlbauer/c521e2b05f5383651d157d5c44344949) shows adaptions of this [fireworks](https://github.com/vispy/vispy/blob/master/examples/demo/gloo/fireworks.py) and this [rotating_cube](https://github.com/vispy/vispy/blob/master/examples/basics/gloo/rotate_cube.py) inside one QT5 Application side-by-side. @rougier might shed some light, what would be needed to get the low level gl-stuff working instead. @kelvinlawson Did you get along with it? A short notice will be sufficient. The difficulty is to route the event to the right context anytime and I'm not sure how things are handled with glir. For glumpy, there is an explicit switch to one context or the other when necessary (see https://github.com/glumpy/glumpy/blob/master/examples/app-two-windows.py) I'd also be curious if something like this works in PyQt4 since it is a more heavily tested backend. Or at least works better. The GLIR "CURRENT" command (`set_current`/`_vispy_set_current` in vispy) should direct the GL calls to the right context. Mouse, keyboard, and timer events are another story. @kmuehlbauer Is your gist something that we should consider making an example? How much modifying needed to be done to get this to work? @davidh-ssec I can try to set this up also for qt4. Is it what you meant with *modifying work*? Should be fairly easy 😬. @kmuehlbauer You mentioned having to modify the example code a bit to get this to work. Would it be possible to just import the examples in *this* new example? Maybe modify the existing examples so they work better, but without stopping them from working independently. @davidh-ssec I'll have a look into this, didn't thought about `importing` so far. Keep you posted!
2017-11-07T10:40:07
vispy/vispy
1,395
vispy__vispy-1395
[ "641" ]
a753088db368112b296a42047414e58d65912293
diff --git a/vispy/gloo/glir.py b/vispy/gloo/glir.py --- a/vispy/gloo/glir.py +++ b/vispy/gloo/glir.py @@ -1041,8 +1041,8 @@ def _get_alignment(self, width): # if we can divide the width by the # alignment cleanly # valid alignments are 1,2,4 and 8 - # put 4 first, since it's the default - alignments = [4, 8, 2, 1] + # 4 is the default + alignments = [8, 4, 2, 1] for alignment in alignments: if width % alignment == 0: return alignment
Alignment wrong computation when aligned on 8 bytes Hello, While reviewing code in vispy/glir.py I found this comment that looks erroneous: ``` # we know the alignment is appropriate # if we can divide the width by the # alignment cleanly # valid alignments are 1,2,4 and 8 # put 4 first, since it's the default alignments = [4, 8, 2, 1] for alignment in alignments: if width % alignment == 0: return alignment ``` the issue is that if width is multiple of 8 then the alignment returned will always be 4... since it is always multiple of 4 too. So either either remove the "8" case for speed or define alignment to [8,4,2,1]. Laurent
Good point. I think this piece of code is originally from PyGLy so @adamlwgriffiths might want to know about this. Also cc @rougier. Using 4 rather than 8 is not a problem, only potentially, using 8 when possible could be faster. So should we ditch the 8 or put 8 first? Not sur e I've anything to say on that. What is the context for such alignment ? It's the alignment of elements for texture upload, and similar code is used in taking screenshots. > Using 4 rather than 8 is not a problem, only potentially, using 8 when possible could be faster. So should we ditch the 8 or put 8 first? Can't we just have `alignments = [8, 4, 2, 1]`? The performance impact is in the 1 percent range, seemingly insignificant. Anyway `alignments = [4, 8, 2, 1]` doesn't make sense at all. Yes let's do 8/4/2/1 and see if anything breaks
2017-11-11T15:55:43
vispy/vispy
1,404
vispy__vispy-1404
[ "1403" ]
9d46fac28eac985fbe5d032d1581710fb74999ea
diff --git a/examples/basics/scene/isocurve.py b/examples/basics/scene/isocurve.py --- a/examples/basics/scene/isocurve.py +++ b/examples/basics/scene/isocurve.py @@ -21,8 +21,8 @@ view = canvas.central_widget.add_view() # Create the image -img_data = np.empty((100, 100, 3), dtype=np.ubyte) -noise = np.random.normal(size=(100, 100), loc=50, scale=150) +img_data = np.empty((200, 100, 3), dtype=np.ubyte) +noise = np.random.normal(size=(200, 100), loc=50, scale=150) noise = gaussian_filter(noise, (4, 4, 0)) img_data[:] = noise[..., np.newaxis] image = scene.visuals.Image(img_data, parent=view.scene) diff --git a/examples/basics/scene/isocurve_updates.py b/examples/basics/scene/isocurve_updates.py --- a/examples/basics/scene/isocurve_updates.py +++ b/examples/basics/scene/isocurve_updates.py @@ -44,13 +44,13 @@ box.camera.aspect = 1.0 # Create random image -img_data1 = np.empty((100, 100, 3), dtype=np.ubyte) -noise = np.random.normal(size=(100, 100), loc=50, scale=150) +img_data1 = np.empty((200, 100, 3), dtype=np.ubyte) +noise = np.random.normal(size=(200, 100), loc=50, scale=150) noise = gaussian_filter(noise, (4, 4, 0)) img_data1[:] = noise[..., np.newaxis] # create 2d array with some function -x, y = np.mgrid[0:2*np.pi:101j, 0:2*np.pi:101j] +x, y = np.mgrid[0:2*np.pi:201j, 0:2*np.pi:101j] myfunc = np.cos(2*x[:-1, :-1]) + np.sin(2*y[:-1, :-1]) # add image to viewbox1 @@ -84,8 +84,8 @@ myfunc, levels=levels2, color_lev='cubehelix', parent=vb4.scene) # set viewport -vb3.camera.set_range((0, 100), (0, 100)) -vb4.camera.set_range((0, 100), (0, 100)) +vb3.camera.set_range((-100, 200), (0, 200)) +vb4.camera.set_range((0, 100), (0, 200)) # setup update parameters diff --git a/vispy/visuals/isocurve.py b/vispy/visuals/isocurve.py --- a/vispy/visuals/isocurve.py +++ b/vispy/visuals/isocurve.py @@ -104,9 +104,9 @@ def set_data(self, data): # if using matplotlib isoline algorithm we have to check for meshgrid # and we can setup the tracer object here if _HAS_MPL: - if self._X is None or self._X.T.shape != data.shape: - self._X, self._Y = np.meshgrid(np.arange(data.shape[0]), - np.arange(data.shape[1])) + if self._X is None or self._X.shape != data.shape: + self._X, self._Y = np.meshgrid(np.arange(data.shape[1]), + np.arange(data.shape[0])) self._iso = cntr.Cntr(self._X, self._Y, self._data.astype(float)) if self._clim is None:
Possible dimensions error in Isocurve Hi, working by Vispy, that is great! I think I found a possible problem in ` vispy/vispy/visuals/isocurve.py.` Isocurve works only if the data first dimension is equal to the second dimension. Taking a look at the code it seems that there is a wrong order of the arguments for the function np.meshgrid. In particular, if data has a shape, for instance (n,m), the result of the meshgrid function are two matrix (m,n). https://github.com/vispy/vispy/blob/9d46fac28eac985fbe5d032d1581710fb74999ea/vispy/visuals/isocurve.py#L107-L109 my solution: if self._X is None or self._X.T.shape != data.shape: self._X, self._Y = np.meshgrid(np.arange(data.shape[1]), **_<- changed_** np.arange(data.shape[0])) **_<- change_** Am I wrong? I hope it helps you. Kind regards, Luigi
@luigi1973 Yes, there is something fishy there. I would consider this a bug. But we need to check, which dimension is x and which is y (or cols /rows). Bitter truth is, that I didn't found that, when I was implementing the matplotlib contour algorithm back then. All examples where using equal-sized (x,y) dimensions, so this didn't surface. @larsoner Do we have any assignment on the sequence or order of dimensions (x/y, rows/columns)? I agree and this needs to be handled carefully. There is always confusion surrounding rows/cols versus x/y, especially when meshgrid comes in to play. I'm not sure what the requirement is. Probably best to do whatever `matplotlib` does ```python # if using matplotlib isoline algorithm we have to check for meshgrid # and we can setup the tracer object here if _HAS_MPL: if self._X is None or self._X.T.shape != data.shape: self._X, self._Y = np.meshgrid(np.arange(data.shape[0]), np.arange(data.shape[1])) self._iso = cntr.Cntr(self._X, self._Y, self._data.astype(float)) ``` This is actually the code to use the matplotlib contour line tracing (directly from the c code) in `IsocurveVisual`. Now doing this was/is not recommended from the matplotlib devs, we thought it would be good to have it here for performance reasons. The plain python approach is really slow. IMHO the order is (rows/cols) what also @luigi1973 already suggested, but then we have to fix also those if-clause (otherwise the meshgrid will be recreated everytime same-shape new data is loaded): ```python # if using matplotlib isoline algorithm we have to check for meshgrid # and we can setup the tracer object here if _HAS_MPL: if self._X is None or self._X.shape != data.shape: self._X, self._Y = np.meshgrid(np.arange(data.shape[1]), np.arange(data.shape[0])) self._iso = cntr.Cntr(self._X, self._Y, self._data.astype(float)) ``` @davidh-ssec Does that make sense to you? At least in the isocurve example the underlying image if sized (200,100) has 200 rows and 100 columns. So we should be on the safe side then, shouldn't we. Side Note: For those who do not need the isocurve vertices at all, they can use ContourVisual where the contour lines are created directly with shaders. This makes sense to me. It definitely seemed odd to have the `.T` in there so I'm glad that is gone. We can even compare meshgrid usage to the contour code in mpl: https://github.com/matplotlib/matplotlib/blob/49d5ced86c4dd3b8ce4ec8db235a1c49b9ae2f0f/lib/matplotlib/contour.py#L1610 So yes, this all looks good to me. `shape = (num_rows, num_cols)` and `x, y = np.meshgrid(x, y)` Edit: I ran the `isocurve.py` example and change the image size to `(300, 100)` with these changes and it all seems to make sense. Other than that I've never used this Visual before. Maybe the fixing PR should include a change to (200, 100) to make this more obvious? Yes, absolutely. I'll issue a fix as suggested in near time.
2017-12-16T09:34:58
vispy/vispy
1,458
vispy__vispy-1458
[ "1437" ]
d20e79412c891f4d3676d3ab21fb7bdd1565598d
diff --git a/vispy/visuals/isocurve.py b/vispy/visuals/isocurve.py --- a/vispy/visuals/isocurve.py +++ b/vispy/visuals/isocurve.py @@ -10,18 +10,16 @@ from ..color import ColorArray from ..color.colormap import _normalize, get_colormap from ..geometry.isocurve import isocurve -from ..testing import has_matplotlib +from ..testing import has_skimage -# checking for matplotlib -_HAS_MPL = has_matplotlib() -if _HAS_MPL: +# checking for scikit-image +_HAS_SKI = has_skimage() +if _HAS_SKI: try: - from matplotlib import _cntr as cntr + from skimage.measure import find_contours except ImportError: - import warnings - warnings.warn("VisPy is not yet compatible with matplotlib 2.2+") - _HAS_MPL = False - cntr = None + _HAS_SKI = False + find_contours = None class IsocurveVisual(LineVisual): @@ -55,9 +53,6 @@ def __init__(self, data=None, levels=None, color_lev=None, clim=None, self._need_color_update = True self._need_level_update = True self._need_recompute = True - self._X = None - self._Y = None - self._iso = None self._level_min = None self._data_is_uniform = False self._lc = None @@ -107,14 +102,6 @@ def set_data(self, data): """ self._data = data - # if using matplotlib isoline algorithm we have to check for meshgrid - # and we can setup the tracer object here - if _HAS_MPL: - if self._X is None or self._X.shape != data.shape: - self._X, self._Y = np.meshgrid(np.arange(data.shape[1]), - np.arange(data.shape[0])) - self._iso = cntr.Cntr(self._X, self._Y, self._data.astype(float)) - if self._clim is None: self._clim = (data.min(), data.max()) @@ -156,13 +143,15 @@ def _compute_iso_line(self): self._level_min = choice[0][0] for level in levels_to_calc: - # if we use matplotlib isoline algorithm we need to add half a + # if we use skimage isoline algorithm we need to add half a # pixel in both (x,y) dimensions because isolines are aligned to # pixel centers - if _HAS_MPL: - nlist = self._iso.trace(level, level, 0) - paths = nlist[:len(nlist)//2] - v, c = self._get_verts_and_connect(paths) + if _HAS_SKI: + contours = find_contours(self._data, level, + positive_orientation='high') + v, c = self._get_verts_and_connect(contours) + # swap row, column to column, row (x, y) + v[:, [0, 1]] = v[:, [1, 0]] v += np.array([0.5, 0.5]) else: paths = isocurve(self._data.astype(float).T, level,
diff --git a/vispy/testing/__init__.py b/vispy/testing/__init__.py --- a/vispy/testing/__init__.py +++ b/vispy/testing/__init__.py @@ -43,7 +43,7 @@ from ._testing import (SkipTest, requires_application, requires_ipython, # noqa requires_img_lib, # noqa has_backend, requires_pyopengl, # noqa - requires_scipy, has_matplotlib, # noqa + requires_scipy, has_matplotlib, has_skimage, # noqa save_testing_image, TestingCanvas, has_pyopengl, # noqa run_tests_if_main, assert_is, assert_in, assert_not_in, assert_equal, diff --git a/vispy/testing/_testing.py b/vispy/testing/_testing.py --- a/vispy/testing/_testing.py +++ b/vispy/testing/_testing.py @@ -294,6 +294,16 @@ def has_matplotlib(version='1.2'): return has_mpl +def has_skimage(version='0.11'): + """Determine if scikit-image is a usable version""" + try: + import skimage + except ImportError: + return False + sk_version = LooseVersion(skimage.__version__) + return sk_version >= LooseVersion(version) + + ############################################################################### # Visuals stuff
VisPy isocurve incompatible with matplotlib 2.2.0 Matplotlib 2.2 is now out and the private contour api `from matplotlib import _cntr` has been removed. We knew this day would come. @QuLogic pointed this thread out on gitter: https://mail.python.org/pipermail/matplotlib-users/2018-March/001313.html The TL;DR of that is that we can either copy the source from old mpl releases or we could try using skimage. I'm not a huge fan of adding such a huge (optional) dependency on to vispy, but as `isocurve.py` sits right now it uses the `_cntr` classes as an optional dependency so it shouldn't be a huge deal. http://scikit-image.org/docs/dev/auto_examples/edges/plot_contours.html As a quick hack I will try to make a PR in the next couple days to switch the import of `_cntr` to a try/except and use the slow contouring method if it isn't found. That should at least let our tests pass and give github users working code.
Note that there is GPU only solution but I don't know to what extent "real" contour lines are needed. Yes, we also have the IsolineFilter which can be attached to eg. Image Visual. Ah, ok. Sorry for the noise. @rougier Did you mean with GPU-method something like in IsolineFilter? I'm not sure actually. I've made them for glumpy (https://github.com/glumpy/glumpy/blob/master/examples/isocurves.py) but I don't remember if I've ported them to vispy... ![isocurves](https://user-images.githubusercontent.com/327203/37111152-48d41e4c-223f-11e8-8211-456ccffca40d.png) @rougier Actually we, means you, @larsoner and I discussed this some years ago. This was implemented when we did the spatial-filters using packed floats stuff. Here is the example https://github.com/vispy/vispy/blob/master/examples/basics/scene/contour.py You surely remember the eye of Mona Lisa. I'm currently working on replacing the mpl cntr usage with skimage. Is everyone (@larsoner, @kmuehlbauer, @rougier) ok with me completely removing the mpl usage? My thinking is if someone wants new vispy features then they should be ok making updates to all packages including MPL. Then again, they may not have skimage installed. Yes mpl 1.2 is too old to bother with a `try`/`except`. Feel free to do a `try/except` with `skimage` to make it fast if you want @larsoner my message on gitter had the wrong version. This is mpl 2.2 which is the latest release. I'm fine with a `try`/`except` for `skimage`. Just make sure similar functionality isn't available in `scipy` as it seems like a more common thing to have. Google shows nothing from scipy (but that could be me messing up my google cache with skimage results). The mailing list I linked to at the top suggests skimage from the mpl devs: https://mail.python.org/pipermail/matplotlib-users/2018-March/001313.html
2018-03-27T20:53:59
vispy/vispy
1,459
vispy__vispy-1459
[ "1440" ]
b6165ef9dd9729710d5fd9345501aa87a0818942
diff --git a/vispy/app/backends/_qt.py b/vispy/app/backends/_qt.py --- a/vispy/app/backends/_qt.py +++ b/vispy/app/backends/_qt.py @@ -164,6 +164,8 @@ def message_handler(*args): else: msg = msg.decode() if not isinstance(msg, string_types) else msg logger.warning(msg) + + try: QtCore.qInstallMsgHandler(message_handler) except AttributeError: @@ -283,6 +285,16 @@ def __init__(self, *args, **kwargs): self._fullscreen = True else: self._fullscreen = False + + # must set physical size before setting visible or fullscreen + # operations may make the size invalid + if hasattr(self, 'devicePixelRatio'): + # handle high DPI displays in PyQt5 + ratio = self.devicePixelRatio() + else: + ratio = 1 + self._physical_size = (p.size[0] * ratio, p.size[1] * ratio) + if not p.resizable: self.setFixedSize(self.size()) if p.position is not None: @@ -293,12 +305,6 @@ def __init__(self, *args, **kwargs): # Qt supports OS double-click events, so we set this here to # avoid double events self._double_click_supported = True - if hasattr(self, 'devicePixelRatio'): - # handle high DPI displays in PyQt5 - ratio = self.devicePixelRatio() - else: - ratio = 1 - self._physical_size = (p.size[0] * ratio, p.size[1] * ratio) # Activate touch and gesture. # NOTE: we only activate touch on OS X because there seems to be
Fullscreen problem with PyQt5 using scene.SceneCanvas canvas = scene.SceneCanvas(keys='interactive', size=(600, 600), show=True, fullscreen=True) This initializes fine. But when clicking the screen the canvas shrinks down to the left bottom corner. vispy.sys_info() gives me: ``` Platform: Windows-10-10.0.16299-SP0 Python: 3.6.4 (v3.6.4:d48eceb, Dec 19 2017, 06:04:45) [MSC v.1900 32 bit (Intel)] NumPy: 1.14.0 Backend: PyQt5 pyqt4: None pyqt5: ('PyQt5', '5.10', '5.10.0') pyside: None pyglet: None glfw: None sdl2: None wx: wxPython 4.0.1 egl: None osmesa: None _test: None GL version: '4.5.13456 Compatibility Profile Context FireGL 21.19.141.0' MAX_TEXTURE_SIZE: 16384 Extensions: 'GL_AMDX_debug_output GL_AMD_blend_minmax_factor GL_AMD_conservative_depth GL_AMD_debug_output GL_AMD_depth_clamp_separate GL_AMD_draw_buffers_blend GL_AMD_framebuffer_sample_positions GL_AMD_gcn_shader GL_AMD_gpu_shader_int64 GL_AMD_interleaved_elements GL_AMD_multi_draw_indirect GL_AMD_name_gen_delete GL_AMD_performance_monitor GL_AMD_pinned_memory GL_AMD_query_buffer_object GL_AMD_sample_positions GL_AMD_seamless_cubemap_per_texture GL_AMD_shader_atomic_counter_ops GL_AMD_shader_stencil_export GL_AMD_shader_stencil_value_export GL_AMD_shader_trinary_minmax GL_AMD_sparse_texture GL_AMD_stencil_operation_extended GL_AMD_texture_cube_map_array GL_AMD_texture_texture4 GL_AMD_transform_feedback3_lines_triangles GL_AMD_transform_feedback4 GL_AMD_vertex_shader_layer GL_AMD_vertex_shader_viewport_index GL_ARB_ES2_compatibility GL_ARB_ES3_1_compatibility GL_ARB_ES3_compatibility GL_ARB_arrays_of_arrays GL_ARB_base_instance GL_ARB_bindless_texture GL_ARB_blend_func_extended GL_ARB_buffer_storage GL_ARB_clear_buffer_object GL_ARB_clear_texture GL_ARB_clip_control GL_ARB_color_buffer_float GL_ARB_compatibility GL_ARB_compressed_texture_pixel_storage GL_ARB_compute_shader GL_ARB_conditional_render_inverted GL_ARB_conservative_depth GL_ARB_copy_buffer GL_ARB_copy_image GL_ARB_cull_distance GL_ARB_debug_output GL_ARB_depth_buffer_float GL_ARB_depth_clamp GL_ARB_depth_texture GL_ARB_derivative_control GL_ARB_direct_state_access GL_ARB_draw_buffers GL_ARB_draw_buffers_blend GL_ARB_draw_elements_base_vertex GL_ARB_draw_indirect GL_ARB_draw_instanced GL_ARB_enhanced_layouts GL_ARB_explicit_attrib_location GL_ARB_explicit_uniform_location GL_ARB_fragment_coord_conventions GL_ARB_fragment_layer_viewport GL_ARB_fragment_program GL_ARB_fragment_program_shadow GL_ARB_fragment_shader GL_ARB_framebuffer_no_attachments GL_ARB_framebuffer_object GL_ARB_framebuffer_sRGB GL_ARB_geometry_shader4 GL_ARB_get_program_binary GL_ARB_get_texture_sub_image GL_ARB_gpu_shader5 GL_ARB_gpu_shader_fp64 GL_ARB_half_float_pixel GL_ARB_half_float_vertex GL_ARB_imaging GL_ARB_indirect_parameters GL_ARB_instanced_arrays GL_ARB_internalformat_query GL_ARB_internalformat_query2 GL_ARB_invalidate_subdata GL_ARB_map_buffer_alignment GL_ARB_map_buffer_range GL_ARB_multi_bind GL_ARB_multi_draw_indirect GL_ARB_multisample GL_ARB_multitexture GL_ARB_occlusion_query GL_ARB_occlusion_query2 GL_ARB_pipeline_statistics_query GL_ARB_pixel_buffer_object GL_ARB_point_parameters GL_ARB_point_sprite GL_ARB_program_interface_query GL_ARB_provoking_vertex GL_ARB_query_buffer_object GL_ARB_robust_buffer_access_behavior GL_ARB_sample_shading GL_ARB_sampler_objects GL_ARB_seamless_cube_map GL_ARB_seamless_cubemap_per_texture GL_ARB_separate_shader_objects GL_ARB_shader_atomic_counters GL_ARB_shader_ballot GL_ARB_shader_bit_encoding GL_ARB_shader_draw_parameters GL_ARB_shader_group_vote GL_ARB_shader_image_load_store GL_ARB_shader_image_size GL_ARB_shader_objects GL_ARB_shader_precision GL_ARB_shader_stencil_export GL_ARB_shader_storage_buffer_object GL_ARB_shader_subroutine GL_ARB_shader_texture_image_samples GL_ARB_shader_texture_lod GL_ARB_shading_language_100 GL_ARB_shading_language_420pack GL_ARB_shading_language_packing GL_ARB_shadow GL_ARB_shadow_ambient GL_ARB_sparse_buffer GL_ARB_sparse_texture GL_ARB_stencil_texturing GL_ARB_sync GL_ARB_tessellation_shader GL_ARB_texture_barrier GL_ARB_texture_border_clamp GL_ARB_texture_buffer_object GL_ARB_texture_buffer_object_rgb32 GL_ARB_texture_buffer_range GL_ARB_texture_compression GL_ARB_texture_compression_bptc GL_ARB_texture_compression_rgtc GL_ARB_texture_cube_map GL_ARB_texture_cube_map_array GL_ARB_texture_env_add GL_ARB_texture_env_combine GL_ARB_texture_env_crossbar GL_ARB_texture_env_dot3 GL_ARB_texture_float GL_ARB_texture_gather GL_ARB_texture_mirror_clamp_to_edge GL_ARB_texture_mirrored_repeat GL_ARB_texture_multisample GL_ARB_texture_non_power_of_two GL_ARB_texture_query_levels GL_ARB_texture_query_lod GL_ARB_texture_rectangle GL_ARB_texture_rg GL_ARB_texture_rgb10_a2ui GL_ARB_texture_snorm GL_ARB_texture_stencil8 GL_ARB_texture_storage GL_ARB_texture_storage_multisample GL_ARB_texture_swizzle GL_ARB_texture_view GL_ARB_timer_query GL_ARB_transform_feedback2 GL_ARB_transform_feedback3 GL_ARB_transform_feedback_instanced GL_ARB_transform_feedback_overflow_query GL_ARB_transpose_matrix GL_ARB_uniform_buffer_object GL_ARB_vertex_array_bgra GL_ARB_vertex_array_object GL_ARB_vertex_attrib_64bit GL_ARB_vertex_attrib_binding GL_ARB_vertex_buffer_object GL_ARB_vertex_program GL_ARB_vertex_shader GL_ARB_vertex_type_10f_11f_11f_rev GL_ARB_vertex_type_2_10_10_10_rev GL_ARB_viewport_array GL_ARB_window_pos GL_ATI_draw_buffers GL_ATI_envmap_bumpmap GL_ATI_fragment_shader GL_ATI_meminfo GL_ATI_separate_stencil GL_ATI_texture_compression_3dc GL_ATI_texture_env_combine3 GL_ATI_texture_float GL_ATI_texture_mirror_once GL_EXT_abgr GL_EXT_bgra GL_EXT_bindable_uniform GL_EXT_blend_color GL_EXT_blend_equation_separate GL_EXT_blend_func_separate GL_EXT_blend_minmax GL_EXT_blend_subtract GL_EXT_compiled_vertex_array GL_EXT_copy_buffer GL_EXT_copy_texture GL_EXT_depth_bounds_test GL_EXT_direct_state_access GL_EXT_draw_buffers2 GL_EXT_draw_instanced GL_EXT_draw_range_elements GL_EXT_fog_coord GL_EXT_framebuffer_blit GL_EXT_framebuffer_multisample GL_EXT_framebuffer_object GL_EXT_framebuffer_sRGB GL_EXT_geometry_shader4 GL_EXT_gpu_program_parameters GL_EXT_gpu_shader4 GL_EXT_histogram GL_EXT_multi_draw_arrays GL_EXT_packed_depth_stencil GL_EXT_packed_float GL_EXT_packed_pixels GL_EXT_pixel_buffer_object GL_EXT_point_parameters GL_EXT_polygon_offset_clamp GL_EXT_provoking_vertex GL_EXT_rescale_normal GL_EXT_secondary_color GL_EXT_separate_specular_color GL_EXT_shader_image_load_store GL_EXT_shader_integer_mix GL_EXT_shadow_funcs GL_EXT_stencil_wrap GL_EXT_subtexture GL_EXT_texgen_reflection GL_EXT_texture3D GL_EXT_texture_array GL_EXT_texture_buffer_object GL_EXT_texture_compression_bptc GL_EXT_texture_compression_latc GL_EXT_texture_compression_rgtc GL_EXT_texture_compression_s3tc GL_EXT_texture_cube_map GL_EXT_texture_edge_clamp GL_EXT_texture_env_add GL_EXT_texture_env_combine GL_EXT_texture_env_dot3 GL_EXT_texture_filter_anisotropic GL_EXT_texture_integer GL_EXT_texture_lod GL_EXT_texture_lod_bias GL_EXT_texture_mirror_clamp GL_EXT_texture_object GL_EXT_texture_rectangle GL_EXT_texture_sRGB GL_EXT_texture_sRGB_decode GL_EXT_texture_shared_exponent GL_EXT_texture_snorm GL_EXT_texture_storage GL_EXT_texture_swizzle GL_EXT_timer_query GL_EXT_transform_feedback GL_EXT_vertex_array GL_EXT_vertex_array_bgra GL_EXT_vertex_attrib_64bit GL_IBM_texture_mirrored_repeat GL_INTEL_fragment_shader_ordering GL_KHR_context_flush_control GL_KHR_debug GL_KHR_robust_buffer_access_behavior GL_KHR_robustness GL_KTX_buffer_region GL_NV_blend_square GL_NV_conditional_render GL_NV_copy_depth_to_color GL_NV_copy_image GL_NV_depth_buffer_float GL_NV_explicit_multisample GL_NV_float_buffer GL_NV_half_float GL_NV_primitive_restart GL_NV_texgen_reflection GL_NV_texture_barrier GL_OES_EGL_image GL_SGIS_generate_mipmap GL_SGIS_texture_edge_clamp GL_SGIS_texture_lod GL_SUN_multi_draw_arrays GL_WIN_swap_hint WGL_EXT_swap_control' ``` ![image](https://user-images.githubusercontent.com/7489565/37203380-bf234a9c-238d-11e8-88e1-2b25b7a5b54d.png) ![image](https://user-images.githubusercontent.com/7489565/37203404-cd24ff28-238d-11e8-99fa-f1dcc7695908.png)
FYI you can do `print(vispy.sys_info())` to get readable output and you can use three backticks (on separate lines) to format code/literal blocks on github. What version of vispy is this? Are you sure you're on the newest version? I really thought I had fixed this. And if you do `fullscreen=False` does it behave properly? Didn't that made it worse? I just did pip install vispy. It says vispy-0.5.2.dist-info in my lib/site-packages folder. It works fine if fullscreen is false yes. Ok good to know. This is likely something I missed when I made the fix for the windowed mode. @mkkb I'm having trouble reproducing this using the current `master` branch. Could you try this on your system? Of course I'm on a high dpi macbook so I could have the opposite problem as you. Also do you have a small example? Maybe my click events aren't behaving the same as yours. ``` import sys import numpy as np from vispy import app, gloo, visuals, scene from vispy.visuals.transforms import STTransform from vispy.color import get_colormap canvas = scene.SceneCanvas(keys='interactive', size=(600,600), show=True, fullscreen=True) grid = canvas.central_widget.add_grid(margin=10) grid.spacing = 0 plot_view_name = 'scene_view' title_txt = 'View Title' x_title_txt = 'x-label' y_title_txt ='y-title' row_i = 0 col_i = 0 # Create title title = scene.Label( title_txt, color='white' ) title.height_max = 40 grid.add_widget( title, row=row_i, col=col_i, col_span=2 ) # Create y-axis yaxis = scene.AxisWidget(orientation='left', axis_label=y_title_txt, axis_font_size=12, axis_label_margin=50, tick_label_margin=5) yaxis.width_max = 80 grid.add_widget(yaxis, row=row_i+1, col=col_i) # Create x-axis xaxis = scene.AxisWidget(orientation='bottom', axis_label=x_title_txt, axis_font_size=12, axis_label_margin=30, tick_label_margin=5) xaxis.height_max = 40 grid.add_widget(xaxis, row=row_i+2, col=col_i+1) # Create the view to plot in plot_view = grid.add_view(row=row_i+1, col=col_i+1, border_color='white') plot_view.height_max = 900/3 # Add camera plot_view.camera = 'panzoom' xaxis.link_view( plot_view ) yaxis.link_view( plot_view ) if __name__ == '__main__' and sys.flags.interactive == 0: app.run() ``` I see the same bug using the script above. In fullscreen mode I also get the error: WARNING: Error drawing visual <vispy.visuals.mesh.MeshVisual object at 0x1ACCD970> When zooming/paning the graph view. Good news: I get the same error and results. Now to figure out why. 👍 You got any time to look on my pull request too, would be nice to get some feedback there while things are fresh in memory. @mkkb Your script works correct on my system with latest github-master. I see an axis in the upper part of the window and can zoom with mouse. @kmuehlbauer Do you have a hidpi display? No, normal display, afaik. New minimal example (working on something smaller): ``` from vispy import app, gloo, visuals, scene app.use_app('pyqt5') canvas = scene.SceneCanvas(keys='interactive', size=(600,600), show=True, fullscreen=True, bgcolor='red') grid = canvas.central_widget.add_grid() plot_view = grid.add_view(row=0, col=0, border_color='white') plot_view.camera = 'panzoom' if __name__ == '__main__': app.run() ``` My guess is I fixed the PyQt5 backend to work for hidpi displays but accidentally broke it for regular displays (assuming @mkkb is on a hidpi display). @davidh-ssec This works on pyqt4 and pyqt5, red fullscreen window. Obviously I am doing too many things this morning. My last comment was backwards. This is failing on HiDPI displays and working on regular displays. So my previous fixes must not have caught every usage of the physical display size. On my machine with this open in full screen, clicking anywhere on the canvas causes the white rectangle (on the border initially) to shrink to the lower left corner of the canvas window. This does not happen if `fullscreen=False`. Just a small update, I used the same example referenced in the other issue/PR and got the same results when setting fullscreen to True in the canvas init. As mentioned before this isn't a problem if you start out small and make it full screen. The other example code uses a different camera so it isn't camera specific. I printed out all of the sizes in the backend and things seem the same between the two cases (fullscreen False/True). @mkkb What happens for you if you do `show=False` in the canvas init and do `canvas.show()` right before the app.run is called? This "fixes" the issue for me.
2018-03-28T17:26:29
vispy/vispy
1,461
vispy__vispy-1461
[ "2", "1455" ]
b6165ef9dd9729710d5fd9345501aa87a0818942
diff --git a/examples/basics/visuals/line_draw.py b/examples/basics/visuals/line_draw.py --- a/examples/basics/visuals/line_draw.py +++ b/examples/basics/visuals/line_draw.py @@ -26,9 +26,9 @@ class EditLineVisual(scene.visuals.Line): def __init__(self, *args, **kwargs): scene.visuals.Line.__init__(self, *args, **kwargs) - + self.unfreeze() # initialize point markers - self.markers = scene.visuals.Markers() + self.markers = scene.visuals.Markers(parent=self) self.marker_colors = np.ones((len(self.pos), 4), dtype=np.float32) self.markers.set_data(pos=self.pos, symbol="s", edge_color="red", size=6) @@ -36,18 +36,19 @@ def __init__(self, *args, **kwargs): self.selected_index = -1 # snap grid size self.gridsize = 10 + self.freeze() - def draw(self, transforms): + def on_draw(self, event): # draw line and markers - scene.visuals.Line.draw(self, transforms) - self.markers.draw(transforms) + scene.visuals.Line.draw(self) + self.markers.draw() def print_mouse_event(self, event, what): """ print mouse events for debugging purposes """ print('%s - pos: %r, button: %s, delta: %r' % (what, event.pos, event.button, event.delta)) - def select_point(self, event, radius=5): + def select_point(self, pos_scene, radius=5): """ Get line point close to mouse pointer and its index @@ -61,19 +62,15 @@ def select_point(self, event, radius=5): picked point and index of the point in the pos array """ - # position in scene/document coordinates - pos_scene = event.pos[:3] - # project mouse radius from screen coordinates to document coordinates - mouse_radius = \ - (event.visual_to_canvas.imap(np.array([radius, radius, radius])) - - event.visual_to_canvas.imap(np.array([0, 0, 0])))[0] + + mouse_radius = 6 # print("Mouse radius in document units: ", mouse_radius) # find first point within mouse_radius index = 0 for p in self.pos: - if np.linalg.norm(pos_scene - p) < mouse_radius: + if np.linalg.norm(pos_scene[:3] - p) < mouse_radius: # print p, index # point found, return point and its index return p, index @@ -96,17 +93,17 @@ def update_markers(self, selected_index=-1, highlight_color=(1, 0, 0, 1)): self.markers.set_data(pos=self.pos, symbol=shape, edge_color='red', size=size, face_color=self.marker_colors) - def on_mouse_press(self, event): - self.print_mouse_event(event, 'Mouse press') - pos_scene = event.pos[:3] + def on_mouse_press(self, pos_scene): + # self.print_mouse_event(event, 'Mouse press') + # pos_scene = event.pos[:3] # find closest point to mouse and select it - self.selected_point, self.selected_index = self.select_point(event) + self.selected_point, self.selected_index = self.select_point(pos_scene) # if no point was clicked add a new one if self.selected_point is None: print("adding point", len(self.pos)) - self._pos = np.append(self.pos, [pos_scene], axis=0) + self._pos = np.append(self.pos, [pos_scene[:3]], axis=0) self.set_data(pos=self.pos) self.marker_colors = np.ones((len(self.pos), 4), dtype=np.float32) self.selected_point = self.pos[-1] @@ -120,26 +117,22 @@ def on_mouse_release(self, event): self.selected_point = None self.update_markers() - def on_mouse_move(self, event): - # left mouse button - if event.button == 1: - # self.print_mouse_event(event, 'Mouse drag') - if self.selected_point is not None: - pos_scene = event.pos - # update selected point to new position given by mouse - self.selected_point[0] = round(pos_scene[0] / self.gridsize) \ - * self.gridsize - self.selected_point[1] = round(pos_scene[1] / self.gridsize) \ - * self.gridsize - self.set_data(pos=self.pos) - self.update_markers(self.selected_index) + def on_mouse_move(self, pos_scene): + if self.selected_point is not None: + # update selected point to new position given by mouse + self.selected_point[0] = round(pos_scene[0] / self.gridsize) \ + * self.gridsize + self.selected_point[1] = round(pos_scene[1] / self.gridsize) \ + * self.gridsize + self.set_data(pos=self.pos) + self.update_markers(self.selected_index) - else: - # if no button is pressed, just highlight the marker that would be - # selected on click - hl_point, hl_index = self.select_point(event) - self.update_markers(hl_index, highlight_color=(0.5, 0.5, 1.0, 1.0)) - self.update() + def highlight_markers(self, pos_scene): + # if no button is pressed, just highlight the marker that would be + # selected on click + hl_point, hl_index = self.select_point(pos_scene) + self.update_markers(hl_index, highlight_color=(0.5, 0.5, 1.0, 1.0)) + self.update() class Canvas(scene.SceneCanvas): @@ -151,6 +144,7 @@ def __init__(self): # Create some initial points n = 7 + self.unfreeze() self.pos = np.zeros((n, 3), dtype=np.float32) self.pos[:, 0] = np.linspace(-50, 50, n) self.pos[:, 1] = np.random.normal(size=n, scale=10, loc=0) @@ -172,6 +166,21 @@ def __init__(self): self.show() self.selected_point = None scene.visuals.GridLines(parent=self.view.scene) + self.freeze() + + def on_mouse_press(self, event): + tr = self.scene.node_transform(self.line) + pos = tr.map(event.pos) + self.line.on_mouse_press(pos) + + def on_mouse_move(self, event): + # left mouse button + tr = self.scene.node_transform(self.line) + pos = tr.map(event.pos) + if event.button == 1: + self.line.on_mouse_move(pos) + else: + self.line.highlight_markers(pos) if __name__ == '__main__':
API Specification: event system examples/basics/visuals/line_draw.py Hi, I can't run the example line_draw.py. Someone can try if it is only my problem or if there is an issue? ``` Traceback (most recent call last): File "/home/........../basics/visuals/line_draw.py", line 178, in <module> win = Canvas() File "/home/........../basics/visuals/line_draw.py", line 154, in __init__ self.pos = np.zeros((n, 3), dtype=np.float32) File "/home/........../lib/python3.6/site-packages/vispy/util/frozen.py", line 16, in __setattr__ 'attributes' % (key, self)) AttributeError: 'pos' is not an attribute of class <Canvas (PyQt5) at 0x7f4334088f98>. Call "unfreeze()" to allow addition of new attributes Process finished with exit code 1 ```
We are tweaking some details (like scrolling), but I think we can close this one, right? Fine by me!
2018-03-29T20:07:18
vispy/vispy
1,534
vispy__vispy-1534
[ "1533" ]
f7b067fc6929d50802096bf11c33071619acad1c
diff --git a/vispy/app/backends/_glfw.py b/vispy/app/backends/_glfw.py --- a/vispy/app/backends/_glfw.py +++ b/vispy/app/backends/_glfw.py @@ -324,7 +324,7 @@ def _vispy_set_title(self, title): if self._id is None: return # Set the window title. Has no effect for widgets - glfw.glfwSetWindowTitle(self._id, title) + glfw.glfwSetWindowTitle(self._id, title.encode('utf-8')) def _vispy_set_size(self, w, h): if self._id is None:
GLFW glfw.glfwSetWindowTitle issue Hello there, I am using a library https://github.com/p5py/p5 which is dependent on vispy. When passing a new title as str to glfw.glfwSetWindowTitle only the first letter of the passed string is coming up as the changed title. I was able to find a workaround to this by passing the title by encoding it to utf-8 in https://github.com/vispy/vispy/blob/0ff2bacef0ec941c039708935a4cbd694ecf02ab/vispy/app/backends/_glfw.py#L327 like the implementation in https://github.com/vispy/vispy/blob/0ff2bacef0ec941c039708935a4cbd694ecf02ab/vispy/ext/glfw.py#L483 Now I am confused wether to make a pull request to p5py or vispy about this issue as p5py is accepting title as str. Thank You
2018-10-04T15:15:30
vispy/vispy
1,595
vispy__vispy-1595
[ "1594" ]
43f604f810f7acfa3d948d27778a5d352bf091a0
diff --git a/vispy/io/mesh.py b/vispy/io/mesh.py --- a/vispy/io/mesh.py +++ b/vispy/io/mesh.py @@ -39,10 +39,11 @@ def read_mesh(fname): if fmt in ('.obj'): return WavefrontReader.read(fname) elif fmt in ('.stl'): - mesh = load_stl(fname) - vertices = mesh.vertices - faces = mesh.faces - normals = mesh.face_normals + file_obj = open(fname, mode='rb') + mesh = load_stl(file_obj) + vertices = mesh['vertices'] + faces = mesh['faces'] + normals = mesh['face_normals'] texcoords = None return vertices, faces, normals, texcoords elif not format:
Load STL files into vispy Hi there, I think I found a bug in vispy/vispy/io/mesh.py in col 42: mesh = load_stl(fname) when I try to import a *.stl file by read_mesh(fname), an error occured like this: File "D:\Python3.5\lib\site-packages\vispy\io\mesh.py", line 43, in read_mesh mesh = load_stl(fname) File "D:\Python3.5\lib\site-packages\vispy\io\stl.py", line 43, in load_stl file_pos = file_obj.tell() AttributeError: 'str' object has no attribute 'tell' by change col42 into :mesh = trimesh.load(fname), problem soved!
2019-03-07T13:32:44
vispy/vispy
1,596
vispy__vispy-1596
[ "671" ]
43f604f810f7acfa3d948d27778a5d352bf091a0
diff --git a/vispy/visuals/xyz_axis.py b/vispy/visuals/xyz_axis.py --- a/vispy/visuals/xyz_axis.py +++ b/vispy/visuals/xyz_axis.py @@ -10,17 +10,24 @@ class XYZAxisVisual(LineVisual): x=red, y=green, z=blue. """ def __init__(self, **kwargs): - verts = np.array([[0, 0, 0], - [1, 0, 0], - [0, 0, 0], - [0, 1, 0], - [0, 0, 0], - [0, 0, 1]]) + pos = np.array([[0, 0, 0], + [1, 0, 0], + [0, 0, 0], + [0, 1, 0], + [0, 0, 0], + [0, 0, 1]]) color = np.array([[1, 0, 0, 1], [1, 0, 0, 1], [0, 1, 0, 1], [0, 1, 0, 1], [0, 0, 1, 1], [0, 0, 1, 1]]) - LineVisual.__init__(self, pos=verts, color=color, connect='segments', - method='gl', **kwargs) + connect = 'segments' + method = 'gl' + + kwargs.setdefault('pos', pos) + kwargs.setdefault('color', color) + kwargs.setdefault('connect', connect) + kwargs.setdefault('method', method) + + LineVisual.__init__(self, **kwargs)
XYZAxisVisuals Override Defaults It looks like XYZAxisVisual is not overridable in the **init** function for the verts and color arguments? Passing in `pos=my_custom_verts` results in `TypeError: __init__() got multiple values for keyword argument 'pos'`. The `**kwds` argument looks like it is being passed through to the Line class, via LineVisual. Does a method exist to specify the verts, color, and / or connect kwargs? I am hesitant to submit a PR modifying **kwds since I am not 100% sure how the passing is working.
@jlaura if you're still interested in this, we have started making it so that the kwargs are explicitly specified, so you could make the changes you wanted. If you don't have time let me know and I might be able to do it. (Sorry for the loooong delay.)
2019-03-07T15:30:33
vispy/vispy
1,624
vispy__vispy-1624
[ "914" ]
521485d842b8c7b29936e6d5b99aeecea6b6b679
diff --git a/vispy/scene/cameras/arcball.py b/vispy/scene/cameras/arcball.py --- a/vispy/scene/cameras/arcball.py +++ b/vispy/scene/cameras/arcball.py @@ -27,6 +27,8 @@ class ArcballCamera(Base3DRotationCamera): The distance of the camera from the rotation point (only makes sense if fov > 0). If None (default) the distance is determined from the scale_factor and fov. + translate_speed : float + Scale factor on translation speed when moving the camera center point. **kwargs : dict Keyword arguments to pass to `BaseCamera`. @@ -43,12 +45,13 @@ class ArcballCamera(Base3DRotationCamera): _state_props = Base3DRotationCamera._state_props + ('_quaternion',) - def __init__(self, fov=0.0, distance=None, **kwargs): + def __init__(self, fov=0.0, distance=None, translate_speed=1.0, **kwargs): super(ArcballCamera, self).__init__(fov=fov, **kwargs) # Set camera attributes self._quaternion = Quaternion() self.distance = distance # None means auto-distance + self.translate_speed = translate_speed def _update_rotation(self, event): """Update rotation parmeters based on mouse movement""" @@ -73,7 +76,8 @@ def _dist_to_trans(self, dist): rot, x, y, z = self._quaternion.get_axis_angle() tr = MatrixTransform() tr.rotate(180 * rot / np.pi, (x, y, z)) - dx, dz, dy = np.dot(tr.matrix[:3, :3], (dist[0], dist[1], 0.)) + dx, dz, dy = np.dot(tr.matrix[:3, :3], + (dist[0], dist[1], 0.)) * self.translate_speed return dx, dy, dz def _get_dim_vectors(self): diff --git a/vispy/scene/cameras/turntable.py b/vispy/scene/cameras/turntable.py --- a/vispy/scene/cameras/turntable.py +++ b/vispy/scene/cameras/turntable.py @@ -34,6 +34,8 @@ class TurntableCamera(Base3DRotationCamera): The distance of the camera from the rotation point (only makes sense if fov > 0). If None (default) the distance is determined from the scale_factor and fov. + translate_speed : float + Scale factor on translation speed when moving the camera center point. **kwargs : dict Keyword arguments to pass to `BaseCamera`. @@ -52,7 +54,7 @@ class TurntableCamera(Base3DRotationCamera): 'azimuth', 'roll') def __init__(self, fov=0.0, elevation=30.0, azimuth=30.0, roll=0.0, - distance=None, **kwargs): + distance=None, translate_speed=1.0, **kwargs): super(TurntableCamera, self).__init__(fov=fov, **kwargs) # Set camera attributes @@ -60,6 +62,7 @@ def __init__(self, fov=0.0, elevation=30.0, azimuth=30.0, roll=0.0, self.elevation = elevation self.roll = roll # interaction not implemented yet self.distance = distance # None means auto-distance + self.translate_speed = translate_speed @property def elevation(self): @@ -142,9 +145,10 @@ def _dist_to_trans(self, dist): rae = np.array([self.roll, self.azimuth, self.elevation]) * np.pi / 180 sro, saz, sel = np.sin(rae) cro, caz, cel = np.cos(rae) - dx = (+ dist[0] * (cro * caz + sro * sel * saz) - + dist[1] * (sro * caz - cro * sel * saz)) - dy = (+ dist[0] * (cro * saz - sro * sel * caz) - + dist[1] * (sro * saz + cro * sel * caz)) - dz = (- dist[0] * sro * cel + dist[1] * cro * cel) + d0, d1 = dist[0], dist[1] + dx = (+ d0 * (cro * caz + sro * sel * saz) + + d1 * (sro * caz - cro * sel * saz)) * self.translate_speed + dy = (+ d0 * (cro * saz - sro * sel * caz) + + d1 * (sro * saz + cro * sel * caz)) * self.translate_speed + dz = (- d0 * sro * cel + d1 * cro * cel) * self.translate_speed return dx, dy, dz
Add support for "TurntableCamera" translate speed. I have some issues when using a `vispy.scene.cameras.TurntableCamera` with user defined distance. In my application the camera is sometime set quite close of the origin and I suspect the combination of that distance and the large scene bounding box is enough to generate values in `vispy.scene.cameras.TurntableCamera._dist_to_trans` that predate correct traveling as you can see in this video: https://drive.google.com/file/d/0B_IQZQdc4Vy8S0dTNEd5Q1hLWE0/view?usp=sharing For now I have created a new camera that inherits from `TurntableCamera` and overrides `_dist_to_trans` as follows: ``` python def _dist_to_trans(self, distance): translate = np.asarray(TurntableCamera._dist_to_trans(self, distance)) translate *= self.__translate_speed return translate ```
I had a pull request (#714) that implemented a consistent panning speed for cameras, but the camera code changed so much before it was merged that it didn't work anymore. It worked like this: if you imagine a flat surface in front of the camera, as if there is a glass window in front of you, then panning the view is like grabbing a part of that window and moving yourself. That is, the point under your mouse when you start panning stays under your mouse. The advantage of this is the camera speed scales with distance. The disadvantage is if you move your origin (like when you are using the flying camera), it will feel like the camera is panning too fast or too slow versus what a user would intuitively think. I kind of don't like the current panning system because it feels a little "slippery". What you have shown here is an extreme case. In an ideal world, I think it would be awesome to implement camera panning by picking a visual to "grab on to" while the camera moves, as if you are moving the scene by using that object as a handle. This would make panning very intuitive and scale-independent. This might be possible once picking is implemented, but it might also be a huge pain to implement. In order to reimplement the PR, I would have to sit down and really understand the camera changes (the camera code is more complex so it could be more general). However, I do explain the concept inside the PR. That looked great and seems to be perfect in my context. I don't see a problem with having some multiplicative parameter like you have @KelSolaar. @campagnola what did you and @almarklein have in mind for this sort of thing? @jdreaver yeah we want picking, hopefully one day the "handle" thing will be possible. But for now we might have to go for a less ideal but more easily workable solution. It would be good if you could try to reimplement your changes in the new system at some point, but that will probably take some work. > @jdreaver yeah we want picking, hopefully one day the "handle" thing will be possible. But for now we might have to go for a less ideal but more easily workable solution. It would be good if you could try to reimplement your changes in the new system at some point, but that will probably take some work. Agreed. Simple is definitely best for now. I agree that the mouse should stay in the same spot. What's shown in the video is just wrong :) Should I create a PR with an attribute like in my first message? Probably best to wait until #928 is in before starting on this. @jdreaver we are going to try to merge #928 very soon, will you have time to try to translate your camera changes using the new system? It should be fairly stable once that is merged. If not, I can implement the simpler solution of just adding a native multiplicative factor for the `dist_to_trans` to solve @KelSolaar's case. Cool! I am on vacation for the next few weeks, so I won't have time until I'm back. On Jul 5, 2015 2:27 PM, "Eric Larson" [email protected] wrote: > @jdreaver https://github.com/jdreaver we are going to try to merge #928 > https://github.com/vispy/vispy/pull/928 very soon, will you have time > to try to translate your camera changes using the new system? It should be > fairly stable once that is merged. > > If not, I can implement the simpler solution of just adding a native > multiplicative factor for the dist_to_trans to solve @KelSolaar > https://github.com/KelSolaar's case. > > — > Reply to this email directly or view it on GitHub > https://github.com/vispy/vispy/issues/914#issuecomment-118617764. Okay, in the meantime I'll add a simple parameter to allow manual adjustment then. If you could come back to your PR whenever you get time, it would be very helpful. @jdreaver @Eric89GXL - any updates on this? This would be very useful to me too! I don't think anyone's worked on this :/ I never got around to figuring out the new camera code (well, I guess it isn't so new anymore haha).
2019-04-19T22:49:46
vispy/vispy
1,654
vispy__vispy-1654
[ "1651" ]
e0834f0f942d145bea8bae92fc2cea9eb48ac4be
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -43,7 +43,6 @@ from setuptools.command.build_ext import build_ext as _build_ext from setuptools.command.egg_info import egg_info from subprocess import check_call -import numpy as np try: @@ -305,7 +304,6 @@ def run(self): }, packages=find_packages(), ext_modules=cythonize(extensions), - include_dirs=[np.get_include()], package_dir={'vispy': 'vispy'}, data_files=[ ('share/jupyter/nbextensions/vispy', [
setup.py attempts to import numpy before installing it On master `setup.py` imports numpy on line 46 even though numpy is a dependency of vispy so it is not guaranteed it will be installed yet. This causes `pip install git+https://github.com/vispy/vispy.git` to fail unless you already have numpy installed.
What is the current best practice for getting around this? I think I use this in other projects. I'll have to look it up later. @djhoese PEP 518 was suggested for one of my projects. Works good so far. > @djhoese PEP 518 was suggested for one of my projects. Works good so far. Yes. We had been struggling with this forever too in projects. To use that put a `pyproject.toml` in your project root. Pip will then install the dependencies specified in there in an isolated environment and call the build tool to produce a wheel to install in the environment where pip was called from. This has some implications if you produce binary wheels for people to install that should not be ignored. Edit: Example for the toml file: https://github.com/pymor/pymor/blob/master/pyproject.toml Agreed `pyproject.toml` should work, see also for example how SciPy does it: https://github.com/scipy/scipy/blob/master/pyproject.toml I actually don't think we need to go that far unless we want cython to be installed and rebuild every extension. If this is only about the `numpy` issue I looked at how we do it in pyresample and it looks like I just copied and pasted things poorly in to vispy. In pyresample we defined this special `build_ext` class: https://github.com/pytroll/pyresample/blob/master/setup.py#L70-L84 We have that in vispy too: https://github.com/vispy/vispy/blob/master/setup.py#L113 But then ignore it and manually add the numpy include directories: https://github.com/vispy/vispy/blob/master/setup.py#L308 I think we could just remove this `include_dirs` and the numpy import at the top of setup.py. I think if vispy is used as a dependency in a project that installs with PEP 518 mechanics, then vispy itself will be installed with build isolation in that build process. So adding the pyproject.toml would make vispy easier to use in those downstream projects. @renefritze You are absolutely right and not doing a pyproject.toml file is just me being stubborn. I'll see if I can make a pull request today for it. I don't fully know everything about the PEP and anything special we need, but our build process should be simpler than scipy.
2019-06-29T20:09:53
vispy/vispy
1,660
vispy__vispy-1660
[ "1250" ]
aa9c01dae0c45afae6d177c1ab014c9e34bc6fc0
diff --git a/vispy/gloo/framebuffer.py b/vispy/gloo/framebuffer.py --- a/vispy/gloo/framebuffer.py +++ b/vispy/gloo/framebuffer.py @@ -250,12 +250,14 @@ def read(self, mode='color', alpha=True, crop=None): """ _check_valid('mode', mode, ['color', 'depth', 'stencil']) + buffer = getattr(self, mode + '_buffer') + if buffer is None: + raise ValueError("Can't read pixels for buffer {}, " + "buffer does not exist.".format(mode)) if crop is None: - buffer = getattr(self, mode+'_buffer') h, w = buffer.shape[:2] crop = (0, 0, w, h) # todo: this is ostensibly required, but not available in gloo.gl #gl.glReadBuffer(buffer._target) - - return read_pixels(crop, alpha=alpha) + return read_pixels(crop, alpha=alpha, mode=mode) diff --git a/vispy/gloo/wrappers.py b/vispy/gloo/wrappers.py --- a/vispy/gloo/wrappers.py +++ b/vispy/gloo/wrappers.py @@ -602,7 +602,7 @@ def glir(self): ## Functions that do not use the glir queue -def read_pixels(viewport=None, alpha=True, out_type='unsigned_byte'): +def read_pixels(viewport=None, alpha=True, mode='color', out_type='unsigned_byte'): """Read pixels from the currently selected buffer. Under most circumstances, this function reads from the front buffer. @@ -616,7 +616,10 @@ def read_pixels(viewport=None, alpha=True, out_type='unsigned_byte'): the current GL viewport will be queried and used. alpha : bool If True (default), the returned array has 4 elements (RGBA). - If False, it has 3 (RGB). + If False, it has 3 (RGB). This only effects the color mode. + mode : str + Type of buffer data to read. Can be one of 'colors', 'depth', + or 'stencil'. See returns for more information. out_type : str | dtype Can be 'unsigned_byte' or 'float'. Note that this does not use casting, but instead determines how values are read from @@ -627,9 +630,13 @@ def read_pixels(viewport=None, alpha=True, out_type='unsigned_byte'): ------- pixels : array 3D array of pixels in np.uint8 or np.float32 format. - The array shape is (h, w, 3) or (h, w, 4), with the top-left corner - of the framebuffer at index [0, 0] in the returned array. + The array shape is (h, w, 3) or (h, w, 4) for colors mode, + with the top-left corner of the framebuffer at index [0, 0] in the + returned array. If 'mode' is depth or stencil then the last dimension + is 1. """ + _check_valid('mode', mode, ['color', 'depth', 'stencil']) + # Check whether the GL context is direct or remote context = get_current_canvas().context if context.shared.parser.is_remote(): @@ -649,7 +656,18 @@ def read_pixels(viewport=None, alpha=True, out_type='unsigned_byte'): % (viewport,)) x, y, w, h = viewport gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 1) # PACK, not UNPACK - fmt = gl.GL_RGBA if alpha else gl.GL_RGB + if mode == 'depth': + fmt = gl.GL_DEPTH_COMPONENT + shape = (h, w, 1) + elif mode == 'stencil': + fmt = gl.GL_STENCIL_INDEX8 + shape = (h, w, 1) + elif alpha: + fmt = gl.GL_RGBA + shape = (h, w, 4) + else: + fmt = gl.GL_RGB + shape = (h, w, 3) im = gl.glReadPixels(x, y, w, h, fmt, type_) gl.glPixelStorei(gl.GL_PACK_ALIGNMENT, 4) # reshape, flip, and return @@ -657,8 +675,8 @@ def read_pixels(viewport=None, alpha=True, out_type='unsigned_byte'): np_dtype = np.uint8 if type_ == gl.GL_UNSIGNED_BYTE else np.float32 im = np.frombuffer(im, np_dtype) - im.shape = h, w, (4 if alpha else 3) # RGBA vs RGB - im = im[::-1, :, :] # flip the image + im.shape = shape + im = im[::-1, ...] # flip the image return im
diff --git a/vispy/gloo/tests/test_wrappers.py b/vispy/gloo/tests/test_wrappers.py --- a/vispy/gloo/tests/test_wrappers.py +++ b/vispy/gloo/tests/test_wrappers.py @@ -211,13 +211,14 @@ def test_wrappers(): 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) + vPosition = np.array( + [[-1, 1, 0.0], [0, 1, 0.5], # For drawing a square to top left + [-1, 0, 0.0], [0, 0, 0.5]], np.float32) VERT_SHADER = """ // simple vertex shader - attribute vec2 a_position; + attribute vec3 a_position; void main (void) { - gl_Position = vec4(a_position, 0., 1.0); + gl_Position = vec4(a_position, 1.0); } """ @@ -231,6 +232,7 @@ def test_read_pixels(): with Canvas() as c: c.set_current() gloo.set_viewport(0, 0, *c.size) + gloo.set_state(depth_test=True) c._program = gloo.Program(VERT_SHADER, FRAG_SHADER) c._program['a_position'] = gloo.VertexBuffer(vPosition) gloo.clear(color='black') @@ -247,5 +249,15 @@ def test_read_pixels(): gloo.flush() gloo.finish() + # Check that we can read the depth buffer + img = read_pixels(mode='depth') + assert_equal(img.shape[:2], c.size[::-1]) + assert_equal(img.shape[2], 1) + unique_img = np.unique(img) + # we should have quite a few different depth values + assert unique_img.shape[0] > 50 + assert unique_img.max() == 255 + assert unique_img.min() > 0 + run_tests_if_main()
Impossible to read the depth buffer According to the document http://vispy.org/gloo.html, `vispy.gloo.FrameBuffer.read` supports read the depth buffer. However in practice it always returns an numpy array whose shape is either `(w, h, 3)` or `(w, h, 4)`, which is not the depth buffer.
May be the read pixels function in https://github.com/vispy/vispy/blob/master/vispy/gloo/framebuffer.py is wrong. The code for `vispy.gloo.FrameBuffer.read` is ``` def read(self, mode='color', alpha=True): _check_valid('mode', mode, ['color', 'depth', 'stencil']) buffer = getattr(self, mode+'_buffer') h, w = buffer.shape[:2] # todo: this is ostensibly required, but not available in gloo.gl #gl.glReadBuffer(buffer._target) return read_pixels((0, 0, w, h), alpha=alpha) ``` which does not uses the `mode` parameter at all. Do either of you have example/test code that I could use to test this and know that I'm testing it correctly? It seems that as the comment said, the blocker is `gl.glReadBuffer`. I will try to provide a working test code. @zhou13 Any updates on this? ```python from vispy import gloo from vispy import app import numpy as np import matplotlib.pyplot as plt # Create vetices vPosition = np.array([[-0.8, -0.8, 0.0], [+0.7, -0.7, 0.0], [-0.7, +0.7, 0.0], [+0.8, +0.8, 0.0, ]], np.float32) vPosition_full = np.array([[-1.0, -1.0, 0.0], [+1.0, -1.0, 0.0], [-1.0, +1.0, 0.0], [+1.0, +1.0, 0.0, ]], np.float32) vTexcoord = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]], np.float32) # For initial quad VERT_SHADER1 = """ attribute vec3 a_position; void main (void) { gl_Position = vec4(a_position, 1.0); } """ FRAG_SHADER1 = """ uniform vec4 u_color; void main() { gl_FragColor = u_color; } """ # To render the result of the FBO VERT_SHADER2 = """ attribute vec3 a_position; attribute vec2 a_texcoord; varying vec2 v_texcoord; void main (void) { // Pass tex coords v_texcoord = a_texcoord; // Calculate position gl_Position = vec4(a_position.x, a_position.y, a_position.z, 1.0); } """ FRAG_SHADER2 = """ uniform sampler2D u_texture1; varying vec2 v_texcoord; const float c_zero = 0.0; const int c_sze = 5; void main() { float scalefactor = 1.0 / float(c_sze * c_sze * 4 + 1); gl_FragColor = vec4(c_zero, c_zero, c_zero, 1.0); for (int y=-c_sze; y<=c_sze; y++) { for (int x=-c_sze; x<=c_sze; x++) { vec2 step = vec2(x,y) * 0.01; vec3 color = texture2D(u_texture1, v_texcoord.st+step).rgb; gl_FragColor.rgb += color * scalefactor; } } } """ SIZE = 50 class Canvas(app.Canvas): def __init__(self): app.Canvas.__init__(self, keys='interactive', size=(560, 420)) # Create texture to render to shape = self.physical_size[1], self.physical_size[0] self._rendertex = gloo.Texture2D((shape + (3,))) # Create FBO, attach the color buffer and depth buffer self._fbo = gloo.FrameBuffer(self._rendertex, gloo.RenderBuffer(shape)) # Create program to render a shape self._program1 = gloo.Program(VERT_SHADER1, FRAG_SHADER1) self._program1['u_color'] = 0.9, 1.0, 0.4, 1 self._program1['a_position'] = gloo.VertexBuffer(vPosition) # Create program to render FBO result self._program2 = gloo.Program(VERT_SHADER2, FRAG_SHADER2) self._program2['a_position'] = gloo.VertexBuffer(vPosition) self._program2['a_texcoord'] = gloo.VertexBuffer(vTexcoord) self._program2['u_texture1'] = self._rendertex self.show() def on_resize(self, event): width, height = event.physical_size gloo.set_viewport(0, 0, width, height) def on_draw(self, event): # Draw the same scene as as in hello_quad.py, but draw it to the FBO with self._fbo: gloo.set_clear_color((0.0, 0.0, 0.5, 1)) gloo.clear(color=True, depth=True) gloo.set_viewport(0, 0, *self.physical_size) self._program1.draw('triangle_strip') image = self._fbo.read(mode="color") depth = self._fbo.read(mode="depth") plt.figure() plt.imshow(image) plt.figure() plt.imshow(depth) plt.show() app.quit() # Now draw result to a full-screen quad # Init gloo.set_clear_color('white') gloo.clear(color=True, depth=True) self._program2.draw('triangle_strip') if __name__ == '__main__': c = Canvas() app.run() ``` This is definitely bug and I think I have a fix. For the record, here is the version of your code that I've adjusted to work properly. Mainly I enabled depth_test which wasn't being done before. Otherwise I just rearranged the plotting stuff to make it easier to analyze. <details> ``` from vispy import gloo from vispy import app import numpy as np import matplotlib.pyplot as plt # Create vetices vPosition = np.array([[-0.8, -0.8, 0.8], [+0.7, -0.7, 0.2], [-0.7, +0.7, 0.5], [+0.8, +0.8, 0.9, ]], np.float32) vPosition_full = np.array([[-1.0, -1.0, 0.8], [+1.0, -1.0, 0.2], [-1.0, +1.0, 0.5], [+1.0, +1.0, 0.9, ]], np.float32) vTexcoord = np.array([[0.0, 0.0], [0.0, 1.0], [1.0, 0.0], [1.0, 1.0]], np.float32) # For initial quad VERT_SHADER1 = """ attribute vec3 a_position; void main (void) { gl_Position = vec4(a_position, 1.0); } """ FRAG_SHADER1 = """ uniform vec4 u_color; void main() { gl_FragColor = u_color; } """ # To render the result of the FBO VERT_SHADER2 = """ attribute vec3 a_position; attribute vec2 a_texcoord; varying vec2 v_texcoord; void main (void) { // Pass tex coords v_texcoord = a_texcoord; // Calculate position gl_Position = vec4(a_position.x, a_position.y, a_position.z, 1.0); } """ FRAG_SHADER2 = """ uniform sampler2D u_texture1; varying vec2 v_texcoord; const float c_zero = 0.0; const int c_sze = 5; void main() { float scalefactor = 1.0 / float(c_sze * c_sze * 4 + 1); gl_FragColor = vec4(c_zero, c_zero, c_zero, 1.0); for (int y=-c_sze; y<=c_sze; y++) { for (int x=-c_sze; x<=c_sze; x++) { vec2 step = vec2(x,y) * 0.01; vec3 color = texture2D(u_texture1, v_texcoord.st+step).rgb; gl_FragColor.rgb += color * scalefactor; } } } """ SIZE = 50 class Canvas(app.Canvas): def __init__(self): app.Canvas.__init__(self, keys='interactive', size=(560, 420)) # Create texture to render to shape = self.physical_size[1], self.physical_size[0] self._rendertex = gloo.Texture2D((shape + (3,))) # Create FBO, attach the color buffer and depth buffer self._fbo = gloo.FrameBuffer(self._rendertex, gloo.RenderBuffer(shape)) # Create program to render a shape self._program1 = gloo.Program(VERT_SHADER1, FRAG_SHADER1) self._program1['u_color'] = 0.9, 1.0, 0.4, 1 self._program1['a_position'] = gloo.VertexBuffer(vPosition) # Create program to render FBO result self._program2 = gloo.Program(VERT_SHADER2, FRAG_SHADER2) self._program2['a_position'] = gloo.VertexBuffer(vPosition) self._program2['a_texcoord'] = gloo.VertexBuffer(vTexcoord) self._program2['u_texture1'] = self._rendertex gloo.set_state(depth_test=True) self.show() def on_resize(self, event): width, height = event.physical_size gloo.set_viewport(0, 0, width, height) def on_draw(self, event): # Draw the same scene as as in hello_quad.py, but draw it to the FBO with self._fbo: gloo.set_clear_color((0.0, 0.0, 0.5, 1)) gloo.clear(color=True, depth=True) gloo.set_viewport(0, 0, *self.physical_size) self._program1.draw('triangle_strip') image = self._fbo.read(mode="color") depth = self._fbo.read(mode="depth")[:, :, 0] print(image.shape, depth.shape) fig = plt.figure() ax = plt.subplot(1, 2, 1) ax.imshow(image) ax.set_title('Image') ax = plt.subplot(1, 2, 2) img = ax.imshow(depth) ax.set_title('Depth') fig.colorbar(img, ax=ax) plt.show() app.quit() # Now draw result to a full-screen quad # Init gloo.set_clear_color('white') gloo.clear(color=True, depth=True) self._program2.draw('triangle_strip') if __name__ == '__main__': c = Canvas() app.run() ``` </details> Produces (with my fixes): ![image](https://user-images.githubusercontent.com/1828519/60928723-14c6f500-a274-11e9-9c8c-6d3b38ecf01a.png)
2019-07-09T23:10:43
vispy/vispy
1,671
vispy__vispy-1671
[ "1667" ]
bfe96648fb50ec1eec56568aff93a302473a2e6f
diff --git a/examples/demo/gloo/primitive_mesh_viewer_qt.py b/examples/demo/gloo/primitive_mesh_viewer_qt.py --- a/examples/demo/gloo/primitive_mesh_viewer_qt.py +++ b/examples/demo/gloo/primitive_mesh_viewer_qt.py @@ -315,7 +315,8 @@ def __init__(self): # FPS message in statusbar: self.status = self.statusBar() - self.status.showMessage("...") + self.status_label = QtWidgets.QLabel('...') + self.status.addWidget(self.status_label) self.mesh = MyMeshData() self.update_view(self.props_widget.param) @@ -333,7 +334,11 @@ def list_objectChanged(self): def show_fps(self, fps): nbr_tri = self.mesh.n_faces - self.status.showMessage("FPS - %.2f and nbr Tri %s " % (fps, nbr_tri)) + msg = "FPS - %0.2f and nbr Tri %s " % (float(fps), int(nbr_tri)) + # NOTE: We can't use showMessage in PyQt5 because it causes + # a draw event loop (show_fps for every drawing event, + # showMessage causes a drawing event, and so on). + self.status_label.setText(msg) def update_view(self, param): cols = param.props['cols'] diff --git a/examples/demo/visuals/wiggly_bar.py b/examples/demo/visuals/wiggly_bar.py --- a/examples/demo/visuals/wiggly_bar.py +++ b/examples/demo/visuals/wiggly_bar.py @@ -263,7 +263,8 @@ def __init__(self, d1=None, d2=None, little_m=None, big_m=None, """ - app.Canvas.__init__(self, title='Wiggly Bar', size=(800, 800)) + app.Canvas.__init__(self, title='Wiggly Bar', size=(800, 800), + create_native=False) # Some initialization constants that won't change self.standard_length = 0.97 + 0.55 @@ -288,10 +289,10 @@ def __init__(self, d1=None, d2=None, little_m=None, big_m=None, # Put up a text visual to display time info self.font_size = 24. if font_size is None else font_size - self.text = visuals.TextVisual('0:00.00', - color='white', + self.text = visuals.TextVisual('0:00.00', + color='white', pos=[50, 250, 0], - anchor_x='left', + anchor_x='left', anchor_y='bottom') self.text.font_size = self.font_size @@ -299,17 +300,17 @@ def __init__(self, d1=None, d2=None, little_m=None, big_m=None, # update this self.method_text = visuals.TextVisual( 'Method: {}'.format(self.method), - color='white', - pos=[50, 250 + 2/3*font_size, 0], - anchor_x='left', + color='white', + pos=[50, 250, 0], + anchor_x='left', anchor_y='top' ) self.method_text.font_size = 2/3 * self.font_size # Get the pivoting bar ready - self.rod = visuals.BoxVisual(width=self.px_len/40, - height=self.px_len/40, - depth=self.px_len, + self.rod = visuals.BoxVisual(width=self.px_len/40, + height=self.px_len/40, + depth=self.px_len, color='white') self.rod.transform = transforms.MatrixTransform() self.rod.transform.scale( @@ -371,7 +372,6 @@ def __init__(self, d1=None, d2=None, little_m=None, big_m=None, # Set up a timer to update the image and give a real-time rendering self._timer = app.Timer('auto', connect=self.on_timer, start=True) - self.show() def on_draw(self, ev): # Stolen from previous - just clears the screen and redraws stuff @@ -379,7 +379,7 @@ def on_draw(self, ev): self.context.set_viewport(0, 0, *self.physical_size) self.context.clear() for vis in self.visuals: - if vis == self.center_point and not self.show_pivot: + if vis is self.center_point and not self.show_pivot: continue else: vis.draw() @@ -453,7 +453,7 @@ def on_timer(self, ev): self.s2_loc + np.asarray([delta_x, 0])) - # Redraw and rescale the lower spring + # Redraw and rescale the lower spring # (the hardest part to get, mathematically) self.spring_1.transform.reset() self.spring_1.transform.rotate(90, (0, 1, 0)) @@ -469,8 +469,8 @@ def on_timer(self, ev): self.mass.transform.translate(self.center + self.mass_loc) # Update the timer with how long it's been - self.text.text = '{:0>2d}:{:0>2d}.{:0>2d}'.format(min_passed, - sec_passed, + self.text.text = '{:0>2d}:{:0>2d}.{:0>2d}'.format(min_passed, + sec_passed, millis_passed) # Trigger all of the drawing and updating
Error drawing visual vispy visuals mesh.MeshVisual and vispy visuals tube.TubeVisual I have upgraded vispy today to 0.6.0 and now I am not able to run this example I am getting empty canvas screen and widgets box window. https://github.com/vispy/vispy/blob/master/examples/demo/visuals/wiggly_bar.py I got this error WARNING: Error drawing visual <vispy.visuals.mesh.MeshVisual object at 0x7ff6540694a8> WARNING:vispy:Error drawing visual <vispy.visuals.mesh.MeshVisual object at 0x7ff6540694a8> WARNING: Traceback (most recent call last): File "wiggly_vispy.py", line 855, in <module> main() File "wiggly_vispy.py", line 851, in main win.show() File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/app/backends/_qt.py", line 501, in event out = super(QtBaseCanvasBackend, self).event(ev) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/app/backends/_qt.py", line 501, in event out = super(QtBaseCanvasBackend, self).event(ev) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/app/backends/_qt.py", line 818, in paintGL self._vispy_canvas.events.draw(region=None) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/util/event.py", line 455, in __call__ self._invoke_callback(cb, event) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/util/event.py", line 475, in _invoke_callback self, cb_event=(cb, event)) << caught exception here: >> File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/util/event.py", line 471, in _invoke_callback cb(event) File "wiggly_vispy.py", line 344, in on_draw vis.draw() File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/visuals/visual.py", line 595, in draw v.draw() File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/visuals/mesh.py", line 519, in draw Visual.draw(self, *args, **kwds) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/visuals/visual.py", line 443, in draw self._vshare.index_buffer) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/visuals/shaders/program.py", line 101, in draw Program.draw(self, *args, **kwargs) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/program.py", line 533, in draw canvas.context.flush_commands() File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/context.py", line 176, in flush_commands self.glir.flush(self.shared.parser) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/glir.py", line 572, in flush self._shared.flush(parser) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/glir.py", line 494, in flush parser.parse(self._filter(self.clear(), parser)) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/glir.py", line 819, in parse self._parse(command) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/glir.py", line 779, in _parse ob.draw(*args) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/glir.py", line 1322, in draw gl.check_error('Check before draw') File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/gl/__init__.py", line 207, in check_error raise err RuntimeError: OpenGL got errors (Check before draw): GL_INVALID_VALUE WARNING:vispy:Traceback (most recent call last): File "wiggly_vispy.py", line 855, in <module> main() File "wiggly_vispy.py", line 851, in main win.show() File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/app/backends/_qt.py", line 501, in event out = super(QtBaseCanvasBackend, self).event(ev) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/app/backends/_qt.py", line 501, in event out = super(QtBaseCanvasBackend, self).event(ev) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/app/backends/_qt.py", line 818, in paintGL self._vispy_canvas.events.draw(region=None) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/util/event.py", line 455, in __call__ self._invoke_callback(cb, event) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/util/event.py", line 475, in _invoke_callback self, cb_event=(cb, event)) << caught exception here: >> File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/util/event.py", line 471, in _invoke_callback cb(event) File "wiggly_vispy.py", line 344, in on_draw vis.draw() File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/visuals/visual.py", line 595, in draw v.draw() File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/visuals/mesh.py", line 519, in draw Visual.draw(self, *args, **kwds) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/visuals/visual.py", line 443, in draw self._vshare.index_buffer) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/visuals/shaders/program.py", line 101, in draw Program.draw(self, *args, **kwargs) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/program.py", line 533, in draw canvas.context.flush_commands() File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/context.py", line 176, in flush_commands self.glir.flush(self.shared.parser) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/glir.py", line 572, in flush self._shared.flush(parser) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/glir.py", line 494, in flush parser.parse(self._filter(self.clear(), parser)) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/glir.py", line 819, in parse self._parse(command) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/glir.py", line 779, in _parse ob.draw(*args) File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/glir.py", line 1322, in draw gl.check_error('Check before draw') File "/home/kunnal/.local/lib/python3.5/site-packages/vispy/gloo/gl/__init__.py", line 207, in check_error raise err RuntimeError: OpenGL got errors (Check before draw): GL_INVALID_VALUE ERROR: Invoking <bound method WigglyBar.on_draw of <WigglyBar (PyQt5) at 0x7ff65455d9e8>> for DrawEvent ERROR:vispy:Invoking <bound method WigglyBar.on_draw of <WigglyBar (PyQt5) at 0x7ff65455d9e8>> for DrawEvent WARNING: Error drawing visual <vispy.visuals.mesh.MeshVisual object at 0x7ff6540694a8> WARNING:vispy:Error drawing visual <vispy.visuals.mesh.MeshVisual object at 0x7ff6540694a8> ERROR: Invoking <bound method WigglyBar.on_draw of <WigglyBar (PyQt5) at 0x7ff65455d9e8>> repeat 2 ERROR:vispy:Invoking <bound method WigglyBar.on_draw of <WigglyBar (PyQt5) at 0x7ff65455d9e8>> repeat 2 WARNING: Error drawing visual <vispy.visuals.tube.TubeVisual object at 0x7ff654048dd8> Thanks for help
@kunnalparihar Thanks for the report. I got similar traceback using python 3.7. Unfortunately this demo isn't tested within the CI Framework. @djhoese Seems that also other Apps which use PyQt are broken (eg https://github.com/vispy/vispy/blob/master/examples/demo/gloo/primitive_mesh_viewer_qt.py) Hm, I get the same results. For the mesh viewer example: ``` $ python examples/demo/gloo/primitive_mesh_viewer_qt.py WARNING: Traceback (most recent call last): File "/Users/davidh/repos/git/vispy/vispy/app/backends/_qt.py", line 818, in paintGL self._vispy_canvas.events.draw(region=None) File "/Users/davidh/repos/git/vispy/vispy/util/event.py", line 428, in __call__ raise RuntimeError('EventEmitter loop detected!') RuntimeError: EventEmitter loop detected! Abort trap: 6 ``` For info, on my side, same error as the first one reported above for: ``` examples/demo/visuals/wiggly_bar.py examples/demo/gloo/two_qt_widgets.py ``` However, `examples/demo/gloo/primitive_mesh_viewer_qt.py` seems to work without error. Linux/Python 3.7 Yes, In my case also examples/demo/gloo/primitive_mesh_viewer_qt.py seems to work without error. Actual problem comes when I am using vispy.visuals with PyQt5 in latest version (0.6.0) of vispy. @asnt @kunnalparihar @djhoese the output of `vispy.sys_info` would be interesting. And, we should try to narrow it down by simplifying the examples. @asnt @djhoese the output when I run vispy.sys_info. I have made it short. Do you need full output ? "Platform: Linux-4.15.0-54-generic-x86_64-with-Ubuntu-16.04-xenial Python: 3.5.2 (default, Nov 12 2018, 13:43:14) [GCC 5.4.0 20160609] NumPy: 1.16.2 Backend: PyQt5 pyqt4: None pyqt5: ('PyQt5', '5.12.2', '5.12.3') pyside: None pyside2: None pyglet: None glfw: glfw (3, 1, 2) sdl2: None wx: None egl: EGL 1.4 (DRI2) Mesa Project: OpenGL OpenGL_ES osmesa: OSMesa _test: None GL version: '3.0 Mesa 18.0.5' MAX_TEXTURE_SIZE: 16384 Extensions: 'GL_3DFX_texture_compression_FXT1 GL_AMD_conservative_depth...... @kunnalparihar No, that will be sufficient. I doubt, that the Extensions have anything to do with it. My current setup with vispy 0.6.0 from conda-forge. ``` Platform: Linux-4.12.14-lp150.12.64-default-x86_64-with-glibc2.10 Python: 3.7.3 | packaged by conda-forge | (default, Jul 1 2019, 21:52:21) [GCC 7.3.0] NumPy: 1.16.4 Backend: PyQt5 pyqt4: None pyqt5: ('PyQt5', '5.9.2', '5.9.7') pyside: None pyside2: None pyglet: None glfw: None sdl2: None wx: None egl: None osmesa: OSMesa _test: None GL version: '4.6.0 NVIDIA 390.87' MAX_TEXTURE_SIZE: 16384 ``` @djhoese For the meshviewer demo (https://github.com/vispy/vispy/blob/master/examples/demo/gloo/primitive_mesh_viewer_qt.py) it seems that vispy app event handling collides with pyqt event handling. If I change the canvas to scene.SceneCanvas then there is at least some output and the different meshes can be altered. I do not have the time to dig deeper, but something is fishy with the eventhandling. On my side: ``` Platform: Linux-5.1.15-arch1-1-ARCH-x86_64-with-arch Python: 3.7.3 (default, Jun 24 2019, 04:54:02) [GCC 9.1.0] NumPy: 1.16.4 Backend: PyQt5 pyqt4: None pyqt5: ('PyQt5', '5.12.3', '5.13.0') pyside: None pyside2: None pyglet: pyglet 1.4.0b1 glfw: glfw (3, 3, 0) sdl2: None wx: None egl: EGL 1.4 Mesa Project: OpenGL OpenGL_ES osmesa: OSMesa _test: None GL version: '3.0 Mesa 19.1.1' MAX_TEXTURE_SIZE: 16384 ``` Ok major improvement on the mesh viewer: commenting out the fps measurement makes it work 100%. With it, on my newest python 3.7 conda-forge based environment with PyQt5 5.9, I get a lot of issues where the GL canvas won't draw and most times even the Qt widgets won't draw. This makes me think the FPS measurement is corrupting the GL context in some way or stopping Qt from drawing things (since all Widgets in Qt5 are GL based iirc). Will investigate further... @kmuehlbauer I messaged you on gitter to see if you could look at the mesh viewer example for me and see if you see the same results. If you comment out the `showMessage` call in the `show_fps` method you should see that everything works as expected. If you print the FPS that's fine. If you use `showMessage` though it causes a recursive repaint event where `showMessage` starts a draw, which calls the measure fps callback, which results in `showMessage`, and so on. If you give it a message that doesn't change (a static string), Qt will "debounce" it and it works fine. I tried to see if it was something specific to the QStatusBar that comes with the main widget by adding a QLabel to the widgets on the left of the Window and set the text on it instead of the status bar. This "works" but it causes a weird drawing effect where the mesh goes back and forth from the right size in the center of the canvas to a smaller size in the lower left. This may be a problem related to me having a HiDPI display (which makes me a little scared). Basically, I can't tell if this is a bug in PyQt or bad practice by this example. I *think* it makes sense that `showMessage` repaints *everything*, especially given the little I understand about PyQt5 using OpenGL for all widgets. I'm wondering if we maybe put the measure fps callback *before* the regular draw callbacks (not sure we can do that with the way it disconnects/connects repeatedly) if that will fix things. I haven't tested that. Here are my QLabel changes I tried as a test: ``` Index: examples/demo/gloo/primitive_mesh_viewer_qt.py IDEA additional info: Subsystem: com.intellij.openapi.diff.impl.patch.CharsetEP <+>UTF-8 =================================================================== --- examples/demo/gloo/primitive_mesh_viewer_qt.py (revision bfe96648fb50ec1eec56568aff93a302473a2e6f) +++ examples/demo/gloo/primitive_mesh_viewer_qt.py (date 1563848654247) @@ -177,6 +177,8 @@ # Signal self.sp[pos].valueChanged.connect(self.update_param) + self.fps_label = QtWidgets.QLabel("FPS: ...") + gb_c_lay.addWidget(self.fps_label, pos + 1, 0) self.gb_c.setLayout(gb_c_lay) vbox = QtWidgets.QVBoxLayout() @@ -333,7 +335,9 @@ def show_fps(self, fps): nbr_tri = self.mesh.n_faces - self.status.showMessage("FPS - %.2f and nbr Tri %s " % (fps, nbr_tri)) + msg = "FPS - %0.2f and nbr Tri %s " % (float(fps), int(nbr_tri)) + # self.status.showMessage(msg) + self.props_widget.fps_label.setText(msg) def update_view(self, param): cols = param.props['cols'] ``` Oh and on the wiggly bar: so far if I comment out `on_draw` then it at least opens and shows the Qt widgets. I'm not a huge fan of the low level clear/draw calls in a higher level "visual" demo, but maybe it should still work. @djhoese Your patch works fine for me too. While tracing the qt-docs I found [this](https://doc.qt.io/qt-5/qstatusbar.html#permanent-message): _Normal and Permanent messages are displayed by creating a small widget (QLabel, QProgressBar or even QToolButton) and then adding it to the status bar using the addWidget() or the addPermanentWidget() function. Use the removeWidget() function to remove such messages from the status bar._ I tested this with the `self.status` on the main window and it worked like your implementation within the widget. Basically I'm almost sure that using "showMessage" doesn't work because of roundtripping event queue and using it in this example might be bad. We should just change to the above advertised method using widgets in the statusbar. > Oh and on the wiggly bar: so far if I comment out `on_draw` then it at least opens and shows the Qt widgets. Same here, but no idea so far what to do and where to look. @kmuehlbauer For the status bar, when you do either the extra widget (`addWidget`) or my patch, do you see the same flickering effect between a small mesh then a full size mesh? @djhoese What do you mean by small mesh vs. full size mesh.? > This "works" but it causes a weird drawing effect where the mesh goes back and forth from the right size in the center of the canvas to a smaller size in the lower left. This may be a problem related to me having a HiDPI display (which makes me a little scared). The mesh is drawn correctly for one or two frames, then it is shown as half the size and in the lower left, then back to proper size in the center, and so on. OK, no, I do not experience these issues.
2019-07-25T02:19:40
vispy/vispy
1,673
vispy__vispy-1673
[ "1672" ]
c3b4d6cb04bfd548e920bdd763508202956dd38d
diff --git a/examples/demo/gloo/shadertoy.py b/examples/demo/gloo/shadertoy.py deleted file mode 100644 --- a/examples/demo/gloo/shadertoy.py +++ /dev/null @@ -1,442 +0,0 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -# vispy: gallery 2, testskip -# Copyright (c) Vispy Development Team. All Rights Reserved. -# Distributed under the (new) BSD License. See LICENSE.txt for more info. - -""" -Shadertoy demo. You can copy-paste shader code from an example on -www.shadertoy.com and get the demo. - -TODO: support cubes and videos as channel inputs (currently, only images -are supported). - -""" - -# NOTE: This example throws warnings about variables not being used; -# this is normal because only some shadertoy examples make use of all -# variables, and the GPU may compile some of them away. - -import sys -from datetime import datetime, time -import numpy as np -from vispy import gloo -from vispy import app - - -vertex = """ -#version 120 - -attribute vec2 position; -void main() -{ - gl_Position = vec4(position, 0.0, 1.0); -} -""" - -fragment = """ -#version 120 - -uniform vec3 iResolution; // viewport resolution (in pixels) -uniform float iGlobalTime; // shader playback time (in seconds) -uniform vec4 iMouse; // mouse pixel coords -uniform vec4 iDate; // (year, month, day, time in seconds) -uniform float iSampleRate; // sound sample rate (i.e., 44100) -uniform sampler2D iChannel0; // input channel. XX = 2D/Cube -uniform sampler2D iChannel1; // input channel. XX = 2D/Cube -uniform sampler2D iChannel2; // input channel. XX = 2D/Cube -uniform sampler2D iChannel3; // input channel. XX = 2D/Cube -uniform vec3 iChannelResolution[4]; // channel resolution (in pixels) -uniform float iChannelTime[4]; // channel playback time (in sec) - -%s -""" - - -def get_idate(): - now = datetime.now() - utcnow = datetime.utcnow() - midnight_utc = datetime.combine(utcnow.date(), time(0)) - delta = utcnow - midnight_utc - return (now.year, now.month, now.day, delta.seconds) - - -def noise(resolution=64, nchannels=1): - # Random texture. - return np.random.randint(low=0, high=256, - size=(resolution, resolution, nchannels) - ).astype(np.uint8) - - -class Canvas(app.Canvas): - - def __init__(self, shadertoy=None): - app.Canvas.__init__(self, keys='interactive') - if shadertoy is None: - shadertoy = """ - void main(void) - { - vec2 uv = gl_FragCoord.xy / iResolution.xy; - gl_FragColor = vec4(uv,0.5+0.5*sin(iGlobalTime),1.0); - }""" - self.program = gloo.Program(vertex, fragment % shadertoy) - - self.program["position"] = [(-1, -1), (-1, 1), (1, 1), - (-1, -1), (1, 1), (1, -1)] - self.program['iMouse'] = 0, 0, 0, 0 - - self.program['iSampleRate'] = 44100. - for i in range(4): - self.program['iChannelTime[%d]' % i] = 0. - self.program['iGlobalTime'] = 0. - - self.activate_zoom() - - self._timer = app.Timer('auto', connect=self.on_timer, start=True) - - self.show() - - def set_channel_input(self, img, i=0): - tex = gloo.Texture2D(img) - tex.interpolation = 'linear' - tex.wrapping = 'repeat' - self.program['iChannel%d' % i] = tex - self.program['iChannelResolution[%d]' % i] = img.shape - - def on_draw(self, event): - self.program.draw() - - def on_mouse_click(self, event): - # BUG: DOES NOT WORK YET, NO CLICK EVENT IN VISPY FOR NOW... - imouse = event.pos + event.pos - self.program['iMouse'] = imouse - - def on_mouse_move(self, event): - if event.is_dragging: - x, y = event.pos - px, py = event.press_event.pos - imouse = (x, self.size[1] - y, px, self.size[1] - py) - self.program['iMouse'] = imouse - - def on_timer(self, event): - self.program['iGlobalTime'] = event.elapsed - self.program['iDate'] = get_idate() # used in some shadertoy exs - self.update() - - def on_resize(self, event): - self.activate_zoom() - - def activate_zoom(self): - gloo.set_viewport(0, 0, *self.physical_size) - self.program['iResolution'] = (self.physical_size[0], - self.physical_size[1], 0.) - -# ------------------------------------------------------------------------- -# COPY-PASTE SHADERTOY CODE BELOW -# ------------------------------------------------------------------------- -SHADERTOY = """ -// From: https://www.shadertoy.com/view/MdX3Rr - -// Created by inigo quilez - iq/2013 -// License Creative Commons Attribution-NonCommercial-ShareAlike 3.0 -// Unported License. - -//stereo thanks to Croqueteer -//#define STEREO - -// value noise, and its analytical derivatives -vec3 noised( in vec2 x ) -{ - vec2 p = floor(x); - vec2 f = fract(x); - - vec2 u = f*f*(3.0-2.0*f); - - float a = texture2D(iChannel0,(p+vec2(0.5,0.5))/256.0,-100.0).x; - float b = texture2D(iChannel0,(p+vec2(1.5,0.5))/256.0,-100.0).x; - float c = texture2D(iChannel0,(p+vec2(0.5,1.5))/256.0,-100.0).x; - float d = texture2D(iChannel0,(p+vec2(1.5,1.5))/256.0,-100.0).x; - - return vec3(a+(b-a)*u.x+(c-a)*u.y+(a-b-c+d)*u.x*u.y, - 6.0*f*(1.0-f)*(vec2(b-a,c-a)+(a-b-c+d)*u.yx)); -} - -const mat2 m2 = mat2(0.8,-0.6,0.6,0.8); - -float terrain( in vec2 x ) -{ - vec2 p = x*0.003; - float a = 0.0; - float b = 1.0; - vec2 d = vec2(0.0); - for( int i=0; i<6; i++ ) - { - vec3 n = noised(p); - d += n.yz; - a += b*n.x/(1.0+dot(d,d)); - b *= 0.5; - p = m2*p*2.0; - } - - return 140.0*a; -} - -float terrain2( in vec2 x ) -{ - vec2 p = x*0.003; - float a = 0.0; - float b = 1.0; - vec2 d = vec2(0.0); - for( int i=0; i<14; i++ ) - { - vec3 n = noised(p); - d += n.yz; - a += b*n.x/(1.0+dot(d,d)); - b *= 0.5; - p=m2*p*2.0; - } - - return 140.0*a; -} - -float terrain3( in vec2 x ) -{ - vec2 p = x*0.003; - float a = 0.0; - float b = 1.0; - vec2 d = vec2(0.0); - for( int i=0; i<4; i++ ) - { - vec3 n = noised(p); - d += n.yz; - a += b*n.x/(1.0+dot(d,d)); - b *= 0.5; - p = m2*p*2.0; - } - - return 140.0*a; -} - -float map( in vec3 p ) -{ - float h = terrain(p.xz); - return p.y - h; -} - -float map2( in vec3 p ) -{ - float h = terrain2(p.xz); - return p.y - h; -} - -float interesct( in vec3 ro, in vec3 rd ) -{ - float h = 1.0; - float t = 1.0; - for( int i=0; i<120; i++ ) - { - if( h<0.01 || t>2000.0 ) break; - t += 0.5*h; - h = map( ro + t*rd ); - } - - if( t>2000.0 ) t = -1.0; - return t; -} - -float sinteresct(in vec3 ro, in vec3 rd ) -{ -#if 0 - // no shadows - return 1.0; -#endif - -#if 0 - // fake shadows - vec3 nor; - vec3 eps = vec3(20.0,0.0,0.0); - nor.x = terrain3(ro.xz-eps.xy) - terrain3(ro.xz+eps.xy); - nor.y = 1.0*eps.x; - nor.z = terrain3(ro.xz-eps.yx) - terrain3(ro.xz+eps.yx); - nor = normalize(nor); - return clamp( 4.0*dot(nor,rd), 0.0, 1.0 ); -#endif - -#if 1 - // real shadows - float res = 1.0; - float t = 0.0; - for( int j=0; j<48; j++ ) - { - vec3 p = ro + t*rd; - float h = map( p ); - res = min( res, 16.0*h/t ); - t += h; - if( res<0.001 ||p.y>300.0 ) break; - } - - return clamp( res, 0.0, 1.0 ); -#endif -} - -vec3 calcNormal( in vec3 pos, float t ) -{ - float e = 0.001; - e = 0.001*t; - vec3 eps = vec3(e,0.0,0.0); - vec3 nor; -#if 0 - nor.x = map2(pos+eps.xyy) - map2(pos-eps.xyy); - nor.y = map2(pos+eps.yxy) - map2(pos-eps.yxy); - nor.z = map2(pos+eps.yyx) - map2(pos-eps.yyx); -#else - nor.x = terrain2(pos.xz-eps.xy) - terrain2(pos.xz+eps.xy); - nor.y = 2.0*e; - nor.z = terrain2(pos.xz-eps.yx) - terrain2(pos.xz+eps.yx); -#endif - return normalize(nor); -} - -vec3 camPath( float time ) -{ - vec2 p = 1100.0*vec2( cos(0.0+0.23*time), cos(1.5+0.21*time) ); - - return vec3( p.x, 0.0, p.y ); -} - - -float fbm( vec2 p ) -{ - float f = 0.0; - - f += 0.5000*texture2D( iChannel0, p/256.0 ).x; p = m2*p*2.02; - f += 0.2500*texture2D( iChannel0, p/256.0 ).x; p = m2*p*2.03; - f += 0.1250*texture2D( iChannel0, p/256.0 ).x; p = m2*p*2.01; - f += 0.0625*texture2D( iChannel0, p/256.0 ).x; - - return f/0.9375; -} - - -void main(void) -{ - vec2 xy = -1.0 + 2.0*gl_FragCoord.xy / iResolution.xy; - - vec2 s = xy*vec2(iResolution.x/iResolution.y,1.0); - - #ifdef STEREO - float isCyan = mod(gl_FragCoord.x + mod(gl_FragCoord.y,2.0),2.0); - #endif - - float time = iGlobalTime*0.15 + 0.3 + 4.0*iMouse.x/iResolution.x; - - vec3 light1 = normalize( vec3(-0.8,0.4,-0.3) ); - - - - vec3 ro = camPath( time ); - vec3 ta = camPath( time + 3.0 ); - ro.y = terrain3( ro.xz ) + 11.0; - ta.y = ro.y - 20.0; - - float cr = 0.2*cos(0.1*time); - vec3 cw = normalize(ta-ro); - vec3 cp = vec3(sin(cr), cos(cr),0.0); - vec3 cu = normalize( cross(cw,cp) ); - vec3 cv = normalize( cross(cu,cw) ); - vec3 rd = normalize( s.x*cu + s.y*cv + 2.0*cw ); - - #ifdef STEREO - ro += 2.0*cu*isCyan; - #endif - - float sundot = clamp(dot(rd,light1),0.0,1.0); - vec3 col; - float t = interesct( ro, rd ); - if( t<0.0 ) - { - // sky - col = vec3(0.3,.55,0.8)*(1.0-0.8*rd.y); - col += 0.25*vec3(1.0,0.7,0.4)*pow( sundot,5.0 ); - col += 0.25*vec3(1.0,0.8,0.6)*pow( sundot,64.0 ); - col += 0.2*vec3(1.0,0.8,0.6)*pow( sundot,512.0 ); - vec2 sc = ro.xz + rd.xz*(1000.0-ro.y)/rd.y; - col = mix( col, vec3(1.0,0.95,1.0), - 0.5*smoothstep(0.5,0.8,fbm(0.0005*sc)) ); - } - else - { - // mountains - vec3 pos = ro + t*rd; - - vec3 nor = calcNormal( pos, t ); - - float r = texture2D( iChannel0, 7.0*pos.xz/256.0 ).x; - - col = (r*0.25+0.75)*0.9*mix( vec3(0.08,0.05,0.03), - vec3(0.10,0.09,0.08), texture2D(iChannel0,0.00007*vec2( - pos.x,pos.y*48.0)).x ); - col = mix( col, 0.20*vec3(0.45,.30,0.15)*(0.50+0.50*r), - smoothstep(0.70,0.9,nor.y) ); - col = mix( col, 0.15*vec3(0.30,.30,0.10)*(0.25+0.75*r), - smoothstep(0.95,1.0,nor.y) ); - - // snow - float h = smoothstep(55.0,80.0,pos.y + 25.0*fbm(0.01*pos.xz) ); - float e = smoothstep(1.0-0.5*h,1.0-0.1*h,nor.y); - float o = 0.3 + 0.7*smoothstep(0.0,0.1,nor.x+h*h); - float s = h*e*o; - col = mix( col, 0.29*vec3(0.62,0.65,0.7), smoothstep( - 0.1, 0.9, s ) ); - - // lighting - float amb = clamp(0.5+0.5*nor.y,0.0,1.0); - float dif = clamp( dot( light1, nor ), 0.0, 1.0 ); - float bac = clamp( 0.2 + 0.8*dot( normalize( - vec3(-light1.x, 0.0, light1.z ) ), nor ), 0.0, 1.0 ); - float sh = 1.0; if( dif>=0.0001 ) sh = sinteresct( - pos+light1*20.0,light1); - - vec3 lin = vec3(0.0); - lin += dif*vec3(7.00,5.00,3.00)*vec3( sh, sh*sh*0.5+0.5*sh, - sh*sh*0.8+0.2*sh ); - lin += amb*vec3(0.40,0.60,0.80)*1.5; - lin += bac*vec3(0.40,0.50,0.60); - col *= lin; - - - float fo = 1.0-exp(-0.0005*t); - vec3 fco = 0.55*vec3(0.55,0.65,0.75) + 0.1*vec3(1.0,0.8,0.5)*pow( - sundot, 4.0 ); - col = mix( col, fco, fo ); - - col += 0.3*vec3(1.0,0.8,0.4)*pow( sundot, - 8.0 )*(1.0-exp(-0.002*t)); - } - - col = pow(col,vec3(0.4545)); - - // vignetting - col *= 0.5 + 0.5*pow( (xy.x+1.0)*(xy.y+1.0)*(xy.x-1.0)*(xy.y-1.0), - 0.1 ); - - #ifdef STEREO - col *= vec3( isCyan, 1.0-isCyan, 1.0-isCyan ); - #endif - -// col *= smoothstep( 0.0, 2.0, iGlobalTime ); - - gl_FragColor=vec4(col,1.0); -} -""" -# ------------------------------------------------------------------------- - -canvas = Canvas(SHADERTOY) -# Input data. -canvas.set_channel_input(noise(resolution=256, nchannels=1), i=0) - -if __name__ == '__main__': - - canvas.show() - if sys.flags.interactive == 0: - canvas.app.run()
shadertoy example non-free license `examples/demo/gloo/shadertoy.py` has code under a [non-free license](https://www.gnu.org/licenses/license-list.html#CC-BY-NC), "Creative Commons Attribution-NonCommercial-ShareAlike 3.0", which means a wide variety of open-source projects cannot ship vispy since they cannot restrict their users from using software for commercial purposes.
IANAL, but this is an example how to use shader toy examples within vispy, not code which is needed to run vispy. We might just use something from shader toy without non-free license. Obligatory I am not a lawyer. I'm not sure this should be a problem for commercial purposes. My thinking is mainly that this is an example script and is not part of the `vispy` library. So there is no way to do `import vispy` or `from vispy import *` where you would possibly import this `shadertoy` example. The only way to do that is to specify the path to the example exactly when running python (`python /path/to/examples/shadertoy.py`). As an example it is not meant to be imported or copied in to any user code beyond being an example of how to use vispy. That said, in the vispy 0.6 release we included all examples in our source distribution (a.k.a sdist), the `.tar.gz` file that is on PyPI. This means that when you download this file you are also downloading this `shadertoy.py` file. **However**, even though it is in the `.tar.gz` it is **not** installed in to your python environment. They are only there for completeness. If you install the binary wheels from PyPI or the binary builds from conda-forge these also do **not** include the examples. Edit: Add example call to python example. The problem is that lots of groups, for example Linux distributions, distribute the sources for all the compiled packages they provide, something a lot of open-source licenses require. Those sources will include the non-free code because the whole point of providing sources is to allow others to rebuild the package from the pristine sources, meaning they can no longer distribute vispy. I am packaging it for openSUSE, for example, and we simply cannot distribute the package anymore. And binary wheels are not an option, either, for security reasons. My vote is just to get rid of it, it is not crucial to VisPy and these legal things require too much effort to sort out properly Ok I'll remove it. I have no problem with that. I copied it to a gist just to have it in one other location if people want it and don't want to go through the git history: https://gist.github.com/djhoese/f4dfa3b423a88739636dc9a95e58e177
2019-07-25T17:51:05
vispy/vispy
1,676
vispy__vispy-1676
[ "1642" ]
cbc68e8675cdf442d00639abbea35cf09f1f76c7
diff --git a/examples/demo/gloo/molecular_viewer.py b/examples/demo/gloo/molecular_viewer.py --- a/examples/demo/gloo/molecular_viewer.py +++ b/examples/demo/gloo/molecular_viewer.py @@ -87,8 +87,8 @@ // GPU drivers... float specular = clamp(pow(abs(dot(normal, K)), 40.), 0.0, 1.0); vec3 v_light = vec3(1., 1., 1.); - gl_FragColor.rgb = (.15*v_color + .55*diffuse * v_color - + .35*specular * v_light); + gl_FragColor.rgba = vec4(.15*v_color + .55*diffuse * v_color + + .35*specular * v_light, 1.0); } """
Window transparency issue in molecular_viewer.py On my Windows 10 machine with a GeForce GTX 1080 Ti (Driver version 430.39) there are serious issues in the visualization of the molecular_viewer.py example code (/examples/demo/gloo/molecular_viewer.py). The background of the image is black no matter what; but wherever there is any color, the color takes on a strange transparency, where you can see through the display window if the window is superimposed over non-black backgrounds. Additionally, if you introduce code to take screenshots, the screenshots always show a black background with pure white molecule images. ![image](https://user-images.githubusercontent.com/1059029/58190470-d18bd500-7c79-11e9-89f7-4b26cb0abac6.png) The image exhibits the undesirable behavior. You can see the shape of my (black) console window placed *behind* the display window.
This is a known issue for past versions of vispy. This should be fixed in vispy 0.6.0+ but it has yet to be released. Please try installing vispy from github (may require a valid C compiler) and see if this changes anything for you. Installing and using 0.6.0 does resolve the issue with the active display, but the saved _screenshot images still display the molecules as being completely white with a black background. ``` res = _screenshot() vispy_file.write_png('test_screenshot.png', res) ``` This results in black&white images. Can you take a screenshot with your system (not vispy) and show me what the window looks like for you? It looks broken for me too where all of the molecules look mostly white. @kmuehlbauer if you have a couple minutes if you could also run this on your system and let me know how it looks. Here's mine on OSX with PyQt5 and Python 3.7: ![image](https://user-images.githubusercontent.com/1828519/58253259-a236a000-7d2d-11e9-9d7d-9ff9564f1c46.png) @djhoese This is a screenshot with my OpenSuse LEAP15 system and latest vispy github master. ![Screenshot_20190523_144315](https://user-images.githubusercontent.com/5821660/58253707-4d187f80-7d69-11e9-9ffc-af484142944f.png) ``` Platform: Linux-4.12.14-lp150.12.61-default-x86_64-with-glibc2.10 Python: 3.7.1 | packaged by conda-forge | (default, Feb 18 2019, 01:42:00) [GCC 7.3.0] NumPy: 1.16.2 Backend: PyQt5 pyqt4: None pyqt5: ('PyQt5', '5.6', '5.6.2') pyside: None pyside2: None pyglet: None glfw: glfw (3, 2, 1) sdl2: sdl2 0.9.6 wx: None egl: None osmesa: OSMesa _test: None GL version: '4.6.0 NVIDIA 390.87' MAX_TEXTURE_SIZE: 16384 ``` conda-forge environment @kmuehlbauer what version of python? PyQt5? numpy? On the latest version of master, I obtain the following by system screenshot: ![image](https://user-images.githubusercontent.com/18143289/58253636-2e19ed80-7d69-11e9-9c68-f965f6a24d0f.png) ``` Platform: Linux-4.19.42-1-MANJARO-x86_64-with-arch-Manjaro-Linux Python: 3.6.8 |Anaconda, Inc.| (default, Dec 30 2018, 01:22:34) [GCC 7.3.0] NumPy: 1.16.2 Backend: PyQt5 pyqt4: None pyqt5: ('PyQt5', '5.12.1', '5.12.2') pyside: None pyside2: None pyglet: pyglet 1.3.2 glfw: None sdl2: None wx: None egl: None osmesa: OSMesa _test: None GL version: '3.0 Mesa 19.0.4' MAX_TEXTURE_SIZE: 16384 ``` *kmuehlbauer was faster for the screenshot!* Added `vispy.sys_info()` output below my screenshot... I get the proper results with PyQt4 on OSX. With PyQt5 I get the super faded results I showed above with Python 3.6 or 3.7. Hhhmmm great. The following I get when using vispy's `_screenshot` and `write_png`. ![test_screenshot](https://user-images.githubusercontent.com/5821660/58254284-b64cc280-7d6a-11e9-8d48-29175c7a044b.png) With `_screenshot` and `write_png`: ```py if __name__ == '__main__': mvc = Canvas() from vispy.gloo.util import _screenshot from vispy.io import write_png res = _screenshot() write_png('test_screenshot.png', res) app.run() ``` I obtain the following: ![image](https://user-images.githubusercontent.com/18143289/58255520-720ef180-7d6d-11e9-999a-1cb00d210945.png) **EDIT:** Now I use `_screenshot()` instead of `render()` @GuillaumeFavelier `render` is not recommended. There is an example of `_screenshot` further up, but I'm not sure where people are putting it in the example code. It comes from `from vispy.gloo.util import _screenshot` (we really need to make this public). @GuillaumeFavelier Do you have an Nvidia GPU? @moridinamael Same question. I have indeed an Nvidia GTX960M but I don't use it. ```sh $ lspci | grep VGA $ 00:02.0 VGA compatible controller: Intel Corporation Skylake GT2 [HD Graphics 520] (rev 07) ``` Ok, I have an AMD/ATI GPU in my mid-2015 macbook: ``` GL version: '2.1 ATI-2.9.26' ``` I'm going to ask a coworker to try this example on their newer macbook and see what they get. Edit: But it definitely seems like something wrong with the new PyQt5 usage (or maybe PyQt5 was always a problem with this). Bizarrely, if I manually modify the image captured by _screenshot by setting all of the 4th entries in the arrays to 255, then the captured and saved screenshot looks good. Thought this information might be useful. @moridinamael Very interesting. If I change the shader in the code to: ``` $ git diff diff --git a/examples/demo/gloo/molecular_viewer.py b/examples/demo/gloo/molecular_viewer.py index 0a424b32..e6576736 100644 --- a/examples/demo/gloo/molecular_viewer.py +++ b/examples/demo/gloo/molecular_viewer.py @@ -87,8 +87,8 @@ void main() // GPU drivers... float specular = clamp(pow(abs(dot(normal, K)), 40.), 0.0, 1.0); vec3 v_light = vec3(1., 1., 1.); - gl_FragColor.rgb = (.15*v_color + .55*diffuse * v_color - + .35*specular * v_light); + gl_FragColor.rgba = vec4(.15*v_color + .55*diffuse * v_color + + .35*specular * v_light, 1.0); } """ ``` Then mine works fine (haven't tried screenshot yet). I verify that the problem is entirely solved by your modification to the shader code. Both screenshots and realtime display are now perfect. @moridinamael Great! Now I just need to make a pull request. However, I have very little time the next 3 weeks and if I do have time it is unlikely that I'll fix this issue specifically. If anyone else has time to make a pull request for this I'll gladly merge it.
2019-07-25T21:47:25
vispy/vispy
1,682
vispy__vispy-1682
[ "1681" ]
28447f06d6a5ea5bd6a2d99949f3833c894c060f
diff --git a/vispy/scene/cameras/panzoom.py b/vispy/scene/cameras/panzoom.py --- a/vispy/scene/cameras/panzoom.py +++ b/vispy/scene/cameras/panzoom.py @@ -49,6 +49,7 @@ def __init__(self, rect=(0, 0, 1, 1), aspect=None, **kwargs): super(PanZoomCamera, self).__init__(**kwargs) self.transform = STTransform() + self.tf_mat = MatrixTransform() # Set camera attributes self.aspect = aspect @@ -151,7 +152,8 @@ def rect(self, args): @property def center(self): rect = self._rect - return 0.5 * (rect.left+rect.right), 0.5 * (rect.top+rect.bottom), 0 + return 0.5 * (rect.left + rect.right), 0.5 * (rect.top + + rect.bottom), 0 @center.setter def center(self, center): @@ -206,7 +208,7 @@ def viewbox_mouse_event(self, event): if event.type == 'mouse_wheel': center = self._scene_transform.imap(event.pos) - self.zoom((1 + self.zoom_factor) ** (-event.delta[1] * 30), center) + self.zoom((1 + self.zoom_factor)**(-event.delta[1] * 30), center) event.handled = True elif event.type == 'mouse_move': @@ -223,14 +225,14 @@ def viewbox_mouse_event(self, event): p2 = np.array(event.pos)[:2] p1s = self._transform.imap(p1) p2s = self._transform.imap(p2) - self.pan(p1s-p2s) + self.pan(p1s - p2s) event.handled = True elif 2 in event.buttons and not modifiers: # Zoom p1c = np.array(event.last_event.pos)[:2] p2c = np.array(event.pos)[:2] - scale = ((1 + self.zoom_factor) ** - ((p1c-p2c) * np.array([1, -1]))) + scale = ((1 + self.zoom_factor)**((p1c - p2c) * + np.array([1, -1]))) center = self._transform.imap(event.press_event.pos[:2]) self.zoom(scale, center) event.handled = True @@ -252,8 +254,8 @@ def _update_transform(self): # apply scale ratio constraint if self._aspect is not None: # Aspect ratio of the requested range - requested_aspect = (rect.width / rect.height - if rect.height != 0 else 1) + requested_aspect = (rect.width / + rect.height if rect.height != 0 else 1) # Aspect ratio of the viewbox view_aspect = vbr.width / vbr.height if vbr.height != 0 else 1 # View aspect ratio needed to obey the scale constraint @@ -273,7 +275,7 @@ def _update_transform(self): # Apply mapping between viewbox and cam view self.transform.set_mapping(self._real_rect, vbr, update=False) # Scale z, so that the clipping planes are between -alot and +alot - self.transform.zoom((1, 1, 1/d)) + self.transform.zoom((1, 1, 1 / d)) # We've now set self.transform, which represents our 2D # transform When up is +z this is all. In other cases, @@ -281,12 +283,10 @@ def _update_transform(self): # for the scene we need a different (3D) mapping. When there # is a minus in up, we simply look at the scene from the other # side (as if z was flipped). - if self.up == '+z': - thetransform = self.transform + self.tf_mat.matrix = self.transform.as_matrix().matrix else: rr = self._real_rect - tr = MatrixTransform() d = d if (self.up[0] == '+') else -d pp1 = [(vbr.left, vbr.bottom, 0), (vbr.left, vbr.top, 0), (vbr.right, vbr.bottom, 0), (vbr.left, vbr.bottom, 1)] @@ -300,9 +300,9 @@ def _update_transform(self): elif self.up[1] == 'x': pp2 = [(0, rr.left, rr.bottom), (0, rr.left, rr.top), (0, rr.right, rr.bottom), (d, rr.left, rr.bottom)] + # Apply - tr.set_mapping(np.array(pp2), np.array(pp1)) - thetransform = tr + self.tf_mat.set_mapping(np.array(pp2), np.array(pp1)) # Set on viewbox - self._set_scene_transform(thetransform) + self._set_scene_transform(self.tf_mat)
PanZoom camera interaction becomes unusable if the up parameter is changed from "+z" Here is a minimal working example. Try changing the `+z` to `-z` in the line `view.camera.up = "+z"` to see the difference in performance: ``` import numpy as np import vispy.scene from vispy.scene import visuals canvas = vispy.scene.SceneCanvas(keys='interactive', show=True) view = canvas.central_widget.add_view() epsilon = 0.01 # Make Data n_markers = 3 p1 = np.zeros((n_markers, 3)) p2 = np.zeros((n_markers, 3)) p1[:, 0] = np.linspace(0.0, 1.0, n_markers) + 0.0 p2[:, 0] = np.linspace(0.0, 1.0, n_markers) + 0.1 # Make Visuals m1 = visuals.Markers(parent=view.scene) m2 = visuals.Markers(parent=view.scene) axis = visuals.XYZAxis(parent=view.scene) p1[:, 2] += 0 * epsilon p2[:, 2] += 1 * epsilon m1.order = 1 m2.order = 2 # Set Data m1.set_data( p1, face_color=[1.0, 0.0, 0.0, 0.5], edge_color=[1, 0, 0, 1], size=80, edge_width=15 ) m2.set_data( p2, face_color=[0.0, 1.0, 0.0, 0.5], edge_color=[0, 1, 0, 1], size=80, edge_width=15 ) view.camera = 'panzoom' view.camera.up = "+z" # <- This fixes occlusion/ordering/transparency but breaks refresh rate # view.camera = 'arcball' if __name__ == '__main__': import sys if sys.flags.interactive != 1: vispy.app.run() ```
The issue is in the branching logic starting around line 286 of `panzoom.py`. It results in passing a different instance of a transform into `self._set_scene_transform` which then triggers updating the full transform system of the scene. I have a very simple fix that I'll open a PR for. I don't see this issue on my local machine. I was going to point to the same code you pointed to. That said, if you can remove the asymmetric behavior between +/-z handling in that method then I'm all for it. That is a little curious that you don't see it. When I use `"-z"` panning and zooming become incredibly laggy. I'm running linux with the non-nvidia graphics driver so maybe I'm just suffering the performance hit much more than you.
2019-07-29T18:30:02
vispy/vispy
1,702
vispy__vispy-1702
[ "1166" ]
75d8bfb9c3fb9241147713591bfae95a42d35920
diff --git a/vispy/visuals/markers.py b/vispy/visuals/markers.py --- a/vispy/visuals/markers.py +++ b/vispy/visuals/markers.py @@ -620,7 +620,8 @@ def _prepare_draw(self, view): view.view_program['u_px_scale'] = view.transforms.pixel_scale if self.scaling: tr = view.transforms.get_transform('visual', 'document').simplified - scale = np.linalg.norm((tr.map([1, 0]) - tr.map([0, 0]))[:2]) + mat = tr.map(np.eye(3)) - tr.map(np.zeros((3, 3))) + scale = np.linalg.norm(mat[:, :3]) view.view_program['u_scale'] = scale else: view.view_program['u_scale'] = 1
Scaling not working correctly for markers When I set `scaling=True` when setting the data in `MarkersVisual#set_data()`, only rotating around the scene (no zooming) makes the points' sizes to vary. I hope this is not the expected behaviour. Here is a snippet which demonstrates this. Run it and rotate the camera around. ``` python import sys import numpy as np from vispy import scene from vispy.scene import visuals # create data cloud pos = np.random.normal(size=(1000, 3), scale=0.2) # # Make a canvas and add simple view # canvas = scene.SceneCanvas(keys='interactive', show=True, bgcolor='w') view = canvas.central_widget.add_view() view.camera = 'turntable' view.camera.fov = 60 scatter = visuals.Markers(parent=view.scene) scatter.antialias = 0 scatter.set_data(pos=pos, edge_color=(0.0, 0.0, 0.0, 1.0), face_color=(0.6, 0.5, 0.4, 1.0), size=.03, scaling=True) scatter.set_gl_state(depth_test=True, blend=True, blend_func=('src_alpha', 'one_minus_src_alpha')) # Add axes axis = visuals.XYZAxis(parent=view.scene) if __name__ == '__main__' and sys.flags.interactive == 0: canvas.app.run() ```
Over three years later and I just encountered the same bug. Would be awesome if this could be fixed :-) The starting point is right here: https://github.com/vispy/vispy/blob/master/vispy/visuals/markers.py#L621-L624 I'm not sure what has to change for this but seeing as the calculation only uses `x` and `y` coordinates I'm sure that's not helping. I don't have the time to look in to this, but pull requests are always welcome. @mbrieske since you are the latest person to be effected by this, maybe you could try some things out? @djhoese thanks for the hint, I'll see what I can do! Okay, so I found that if I replace that line you directed me to by: `scale = 1000 / np.linalg.norm(tr.map([0, 0, 0])[:2])` it works for me. I have no idea if this solves the issue or if this is just a working solution for me though. To verify it for the example above you also need to change the size of the markers to something that makes more sense, i.e. "3" or so. Cheers, Malte Glad that works, but does it still adjust them properly when you zoom in and out? I think you've removed the part of this calculation that is supposed to see how "wide" our current display is and scale the markers accordingly. The calculation as it is right now is taking the difference between the edges/corners of the canvas. You're right, resizing doesn't work anymore. It scales actually in the wrong direction, when I make the window smaller, the circles become bigger. That sucks. Any idea? So right now the calculation is using two corners of the canvas to come up with a "distance". The problem is that for a 3D Scene the x/y coordinates corresponding to the corners of the canvas change as you rotate the Scene so this calculation doesn't make sense. I wonder if a better calculation could be done with the center of the canvas. Like if the center of the canvas doesn't change then no need to update the scale factor. Wait, that won't work because if you zoomed in to the exact center of the canvas you'd still want the size to scale. I'm not sure. I'm pretty sure that this can be fixed by using the norm of the whole transformation matrix instead of the norm of one or two of the projections. I was able to get the above example working with the following code snip-it modifying the lines @djhoese pointed to above: ```python def _prepare_draw(self, view): if self._symbol is None: return False view.view_program['u_px_scale'] = view.transforms.pixel_scale if self.scaling: tr = view.transforms.get_transform('visual', 'document').simplified mat = (tr.map(np.eye(3)) - tr.map(np.zeros((3, 3))))[:, :2] scale = np.linalg.norm(mat) view.view_program['u_scale'] = scale else: view.view_program['u_scale'] = 1 ``` If you compare the before and after gifs, you'll see the size changes on rotation are now gone, as the norm of the matrix is invariant to rotations of the underlying 3D coordinate system Before: ![before_fix](https://user-images.githubusercontent.com/6531703/64068613-55494c00-cbef-11e9-90fb-acd8f77728d5.gif) After: ![after_fix](https://user-images.githubusercontent.com/6531703/64068616-5b3f2d00-cbef-11e9-9015-409a5c6db582.gif) I'm happy to make a PR to add this change, though it may cause absolute changes in the marker size from before the PR that could throw some people off. I also havn't tested this in the 2D case (where you might want to use `np.eye(2)` and `np.zeros((2, 2))`, but where it should would in the same way in principle). Please let me know what the best way to proceed is. Awesome work @sofroniewn! I think a PR would be great. You could try testing a "2D" environment by switching to a 'panzoom' camera and see how that works. Theoretically this should work with `(3, 3)` in a 2D scene since typically a 2D scene is just one where the `z` dimension is ignored. Could you explain why you `simplified` the transform instead of `get_transform()`? I'm unfamiliar with what `simplified` does. I'm also unfamiliar with all the different types of norms that can be done with `np.linalg.norm`, should we maybe be using one of the other formats/orders `norm` accepts (one that uses X/Y/Z instead of cutting off the Z with `[:2]`)? Thanks @djhoese. The code currently uses `simplified` so I just stuck with it, I'm not familiar with what it does either or if it should be dropped. Dropping it causes no noticeable change in performance in my simple example, so I'm happy to drop it. The `[:, :2]` isn't really cutting off the `z` dimension of the axis with the markers - that would be achieved by `[:2, :]` which is more similar to code there now. I'm not quite sure how to interpret the last two dimensions of the 4-vectors outputted by the `.map` method, but I think they relate more to the coordinate system of the screen which is why I was just keeping the first two, `x` and `y`. Including all of 3 or 4 of them doesn't really change anything as the vectors corresponding to them have norms very close to 1. i.e. ```python mat = (tr.map(np.eye(3)) - tr.map(np.zeros((3, 3)))) scale = np.linalg.norm(mat) ``` gives me basically identical performance (where mat used to be `3 x 2` but is now `3 x 4`) and will still be rotation invariant, so I'm happy to keep them in there. Everything still works fine switching the camera to `panzoom` and making the points 2d or 3d. I'm going to make a PR with the following change ```python def _prepare_draw(self, view): if self._symbol is None: return False view.view_program['u_px_scale'] = view.transforms.pixel_scale if self.scaling: tr = view.transforms.get_transform('visual', 'document') mat = tr.map(np.eye(3)) - tr.map(np.zeros((3, 3))) scale = np.linalg.norm(mat) view.view_program['u_scale'] = scale else: view.view_program['u_scale'] = 1 ``` I'll get to work on that soon and we can continue the discussion on the PR
2019-09-04T05:00:30
vispy/vispy
1,714
vispy__vispy-1714
[ "1708" ]
ef982591e223fff09d91d8c2697489c7193a85aa
diff --git a/vispy/app/_detect_eventloop.py b/vispy/app/_detect_eventloop.py new file mode 100644 --- /dev/null +++ b/vispy/app/_detect_eventloop.py @@ -0,0 +1,148 @@ +# Taken from Matplotlib to automatically detect any event loop currently +# in use. +# This code is copyright of Matplotlib, and their license is inlcuded at the +# bottom of this file. + +import sys +import os + + +def _get_running_interactive_framework(): + """ + Return the interactive framework whose event loop is currently running, if + any, or "headless" if no event loop can be started, or None. + Returns + ------- + Optional[str] + One of the following values: "qt5", "qt4", "gtk3", "wx", "tk", + "macosx", "headless", ``None``. + """ + QtWidgets = (sys.modules.get("PyQt5.QtWidgets") + or sys.modules.get("PySide2.QtWidgets")) + if QtWidgets and QtWidgets.QApplication.instance(): + return "qt5" + QtGui = (sys.modules.get("PyQt4.QtGui") + or sys.modules.get("PySide.QtGui")) + if QtGui and QtGui.QApplication.instance(): + return "qt4" + Gtk = sys.modules.get("gi.repository.Gtk") + if Gtk and Gtk.main_level(): + return "gtk3" + wx = sys.modules.get("wx") + if wx and wx.GetApp(): + return "wx" + tkinter = sys.modules.get("tkinter") + if tkinter: + for frame in sys._current_frames().values(): + while frame: + if frame.f_code == tkinter.mainloop.__code__: + return "tk" + frame = frame.f_back + if 'matplotlib.backends._macosx' in sys.modules: + if sys.modules["matplotlib.backends._macosx"].event_loop_is_running(): + return "macosx" + if sys.platform.startswith("linux") and not os.environ.get("DISPLAY"): + return "headless" + return None + +""" +License agreement for matplotlib versions 1.3.0 and later +========================================================= + +1. This LICENSE AGREEMENT is between the Matplotlib Development Team +("MDT"), and the Individual or Organization ("Licensee") accessing and +otherwise using matplotlib software in source or binary form and its +associated documentation. + +2. Subject to the terms and conditions of this License Agreement, MDT +hereby grants Licensee a nonexclusive, royalty-free, world-wide license +to reproduce, analyze, test, perform and/or display publicly, prepare +derivative works, distribute, and otherwise use matplotlib +alone or in any derivative version, provided, however, that MDT's +License Agreement and MDT's notice of copyright, i.e., "Copyright (c) +2012- Matplotlib Development Team; All Rights Reserved" are retained in +matplotlib alone or in any derivative version prepared by +Licensee. + +3. In the event Licensee prepares a derivative work that is based on or +incorporates matplotlib or any part thereof, and wants to +make the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to matplotlib . + +4. MDT is making matplotlib available to Licensee on an "AS +IS" basis. MDT MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, MDT MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB +WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. + +5. MDT SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB + FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR +LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING +MATPLOTLIB , OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF +THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between MDT and +Licensee. This License Agreement does not grant permission to use MDT +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using matplotlib , +Licensee agrees to be bound by the terms and conditions of this License +Agreement. + +License agreement for matplotlib versions prior to 1.3.0 +======================================================== + +1. This LICENSE AGREEMENT is between John D. Hunter ("JDH"), and the +Individual or Organization ("Licensee") accessing and otherwise using +matplotlib software in source or binary form and its associated +documentation. + +2. Subject to the terms and conditions of this License Agreement, JDH +hereby grants Licensee a nonexclusive, royalty-free, world-wide license +to reproduce, analyze, test, perform and/or display publicly, prepare +derivative works, distribute, and otherwise use matplotlib +alone or in any derivative version, provided, however, that JDH's +License Agreement and JDH's notice of copyright, i.e., "Copyright (c) +2002-2011 John D. Hunter; All Rights Reserved" are retained in +matplotlib alone or in any derivative version prepared by +Licensee. + +3. In the event Licensee prepares a derivative work that is based on or +incorporates matplotlib or any part thereof, and wants to +make the derivative work available to others as provided herein, then +Licensee hereby agrees to include in any such work a brief summary of +the changes made to matplotlib. + +4. JDH is making matplotlib available to Licensee on an "AS +IS" basis. JDH MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR +IMPLIED. BY WAY OF EXAMPLE, BUT NOT LIMITATION, JDH MAKES NO AND +DISCLAIMS ANY REPRESENTATION OR WARRANTY OF MERCHANTABILITY OR FITNESS +FOR ANY PARTICULAR PURPOSE OR THAT THE USE OF MATPLOTLIB +WILL NOT INFRINGE ANY THIRD PARTY RIGHTS. + +5. JDH SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF MATPLOTLIB + FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR +LOSS AS A RESULT OF MODIFYING, DISTRIBUTING, OR OTHERWISE USING +MATPLOTLIB , OR ANY DERIVATIVE THEREOF, EVEN IF ADVISED OF +THE POSSIBILITY THEREOF. + +6. This License Agreement will automatically terminate upon a material +breach of its terms and conditions. + +7. Nothing in this License Agreement shall be deemed to create any +relationship of agency, partnership, or joint venture between JDH and +Licensee. This License Agreement does not grant permission to use JDH +trademarks or trade name in a trademark sense to endorse or promote +products or services of Licensee, or any third party. + +8. By copying, installing or otherwise using matplotlib, +Licensee agrees to be bound by the terms and conditions of this License +Agreement. +""" diff --git a/vispy/app/application.py b/vispy/app/application.py --- a/vispy/app/application.py +++ b/vispy/app/application.py @@ -16,6 +16,7 @@ from .backends import CORE_BACKENDS, BACKEND_NAMES, BACKENDMAP, TRIED_BACKENDS from .. import config from .base import BaseApplicationBackend as ApplicationBackend # noqa +from ._detect_eventloop import _get_running_interactive_framework from ..util import logger from ..ext import six @@ -128,7 +129,17 @@ def is_notebook(self): # 'get_ipython' is available in globals when running from # IPython/Jupyter ip = get_ipython() - return ip.has_trait('kernel') + if ip.has_trait('kernel'): + # There doesn't seem to be an easy way to detect the frontend + # That said, if using a kernel, the user can choose to have an + # event loop, we therefore make sure the event loop isn't + # specified before assuming it is a notebook + # https://github.com/vispy/vispy/issues/1708 + # https://github.com/ipython/ipython/issues/11920 + return _get_running_interactive_framework() is None + else: + # `jupyter console` is used + return False except NameError: return False
Vispy wrongly detects Spyder as Jupyter notebook https://github.com/vispy/vispy/blob/a6ec64bb7b56739b463e3c16245a31940ca4f5f7/vispy/app/application.py#L131 ```python Python 3.7.3 | packaged by conda-forge | (default, Jul 1 2019, 21:52:21) Type "copyright", "credits" or "license" for more information. IPython 7.8.0 -- An enhanced Interactive Python. ip = get_ipython() ip.has_trait('kernel') Out[2]: True ip Out[3]: <ipykernel.zmqshell.ZMQInteractiveShell at 0x7f8c103ec2b0> ip.config Out[4]: {'InteractiveShell': {'xmode': 'Plain'}, 'IPCompleter': {'use_jedi': False, 'greedy': False}, 'IPKernelApp': {'exec_lines': ['', "import sys;sys.argv = [''];del sys", 'get_ipython().kernel._load_autoreload_magic()', 'get_ipython().kernel._load_wurlitzer()', "get_ipython().kernel._set_mpl_backend('qt5', False)"], 'connection_file': '/run/user/1000/jupyter/kernel-7c84aada0ff3.json'}, 'InlineBackend': {'rc': {'figure.figsize': (6.0, 4.0), 'figure.dpi': 72, 'font.size': 10, 'figure.subplot.bottom': 0.125, 'figure.facecolor': 'white', 'figure.edgecolor': 'white'}}, 'ZMQInteractiveShell': {'autocall': 0, 'banner1': ''}} ``` ![image](https://user-images.githubusercontent.com/90008/64825685-225a6d00-d58c-11e9-9a06-b2740b3209c7.png) ```python vispy.__version__ Out[6]: '0.6.1' ``` @ccordoba12 any ideas? @jni because I think you are using vispy these days????
The workaround is to have ``` import vispy vispy.use('pyqt5') ``` but that only happens if you remember to use this before starting any kind of application. Potentially use `get_ipython().kernel.app` ??? <details> <summary>On Spyder</summary> ```python kernel = get_ipython().kernel kernel Out[9]: <spyder_kernels.console.kernel.SpyderKernel at 0x7f8c0ee309e8> kernel.app Out[11]: <PyQt5.QtWidgets.QApplication at 0x7f8c0c0bb3a8> ``` </details> <details> <summary> Jupyter Notebook </summary> ![image](https://user-images.githubusercontent.com/90008/64827302-a8c57d80-d591-11e9-8341-a8f7c28c9c1f.png) </details> We use vispy at napari but we use %gui=qt in notebooks, and I presume also in Spyder. (I have the equivalent command in my ipython config.) @hmaarrfk In your original post, was that ipython output or spyder? On my linux system in ipython: ``` In [3]: ip Out[3]: <IPython.terminal.interactiveshell.TerminalInteractiveShell at 0x7f7b02118dd8> ``` On same linux system with jupyter notebook and jupyter lab: ``` <ipykernel.zmqshell.ZMQInteractiveShell at 0x7f7f8cd46080> ``` Is there a jupyter dev that we can ask for the most reliable way of doing this? Maybe the ipywidgets folks know, I'll ping their gitter. Edit: https://stackoverflow.com/a/39662359 That's all from Spyder. Spyder, like the jupyter software, builds ontop of the ipython kernel. I saw those posts, their suggestions end up converging to what you did, but that doesn't seem to detect the difference too well. Maybe `%gui qt` is the only reliable way to specify the backend. That said, I thought that is what selecting the graphics backend from the settings in Spyder did. Maybe that is a bad assumption Does `%gui qt` work in spyder with vispy? I wouldn't expect it to unless it is changing that kernel trait. I don't *think* there is anything in vispy that is checking the ipython configuration for what graphics backend it was told to use. The `%gui qt` magic command, if I remember correctly, is hooking a Qt event loop in to IPython in a background thread so you can run Qt applications while still having access to the REPL. Edit: ...work in spyder with vispy to set the default vispy backend? > @ccordoba12 any ideas? This is a limitation of the Jupyter architecture: there's no way to tell what frontend (notebook or Spyder) is requesting an evaluation in the kernel. Besides, since several frontends can be connected to same kernel (e.g. Spyder can easily create a console for a kernel started by the notebook), things are even harder because each request should be handled separately. However, you could check for the presence of several environment variables that are only present in our kernels ([this](https://github.com/spyder-ide/spyder/blob/59eded5422a0c00f6f384600f82f16ee1dfd7a40/spyder/plugins/ipythonconsole/utils/kernelspec.py#L97-L124) is the list of env vars we send to the kernel) to give better support for Spyder. That will fail for a Spyder console connected to a notebook kernel and also for our third-party [notebook plugin](https://github.com/spyder-ide/spyder-notebook), but it'll work for every console started normally in Spyder. > Does %gui qt work in spyder with vispy? Yes. Spyder uses the [qtconsole](https://github.com/jupyter/qtconsole) package, which provides an interface very similar to IPython's terminal version but developed in Qt, which can evaluate any command IPython (or more specifically `ipykernel`) can run. Pinging @impact27 and @mwcraig about this: * @impact27, do you think we could improve the detection of a kernel being called by Spyder using the new Comms architecture you developed? * @mwcraig, I don't know if you're using a similar procedure to what I described above in VPython or you came up with a better solution to distinguish between notebook and Spyder there. I was more wondering if doing it caused vispy to say "ah we should use Qt instead of webgl" even though vispy was not called in any way. I don't think vispy checks anything that `%gui qt` is affecting. Yep, we are just checking for an environment variable with the string "SPYDER" in it in vpython. > * @impact27, do you think we could improve the detection of a kernel being called by Spyder using the new Comms architecture you developed? I am not sure I understand what the problem is. can't you just call `get_ipython().kernel.__class__`? With Jupyter notebook: ``` get_ipython().kernel.__class__ ipykernel.ipkernel.IPythonKernel ``` With spyder: ```get_ipython().kernel.__class__ Out[4]: spyder_kernels.console.kernel.SpyderKernel``` If the kernel is not a `SpyderKernel`, the comms will not be connected, and you can't communicate. So you need to know that you are using spyder to use the comm. @impact27 The issue, if you can consider it one, is that vispy defaults to a specific webgl backend if it detects it is being used in a notebook. The way it does this was based on stackoverflow answers which said `get_ipython().kernel` should only exist for a notebook. However, that assumed the only alternative was an ipython terminal (where kernel isn't defined) or that `get_ipython` doesn't exist in which case it is being run by the normal python interpreter. So when importing vispy in a spyder environment, vispy will default to this webgl backend because it sees that a jupyter kernel is being used. As far as the current checks go it only checks for the existence of a kernel, not what type of kernel it is. I think the best long term solution is to do an isinstance check right after the `kernel` check. It will be `IPythonKernel` in a notebook, otherwise don't assume it is a notebook. @hmaarrfk Do you have time to make a PR for this? Short term workaround is to explicitly say what backend you want to use as @hmaarrfk pointed out above. > I am not sure I understand what the problem is. can't you just call get_ipython().kernel.__class__? The thing is Spyder can connect to an IPythonKernel without problems. I mean, you can start a kernel in a terminal with ipython kernel then pass its connection file to our "Connect to an existing kernel" dialog and keep working with it just fine. But your solution will work for all kernels started by Spyder directly (which I guess are most kernels started by our users anyway). It seems the correct way is to understand what `%gui qt` and check for the existence of that state. That magic seems applicable even in the case of somebody using a notebook to launch local QT applications. (I believe that is what @jni is doing with napari). Second, it would be to understand if there is any difference between using the `%gui qt` magic and setting the graphics backend in spyder. The comms could work if spyder registers a target to open comms and sends back informations when a comm is opened. This is the opposite way as to what is happening in spyder and you wouldn't be sure that a frontend is already connected when you send the message. > Second, it would be to understand if there is any difference between using the %gui qt magic and setting the graphics backend in spyder. We `%matplotlib <backend>` to set backends in Spyder instead of `%gui <backend>`. That's because we want to give users an out of the box experience for Matplotlib. hmm it seems that both `%gui qt` and `%matplotlib qt` create a variable `app`. This `app` seems to depend on what graphics backend you choose to have. Maybe that is the variable we should be checking for? Note that if you simply run the `%gui` magic, it seems to close the app. I'm not a QT expert, so I'm not too sure what variable to check to know if hte app is still running or not <details> ``` Python 3.7.3 | packaged by conda-forge | (default, Jul 1 2019, 21:52:21) Type "copyright", "credits" or "license" for more information. IPython 7.8.0 -- An enhanced Interactive Python. %gui tk get_ipython().kernel.app Out[2]: <tkinter.Tk object .> %gui qt ERROR:root:Cannot activate multiple GUI eventloops %gui get_ipython().kernel.app Out[5]: <tkinter.Tk object .> %gui qt get_ipython().kernel.app Out[7]: <PyQt5.QtWidgets.QApplication at 0x7f8891e90ee8> app = get_ipython().kernel.app app.destroyed Out[9]: <bound PYQT_SIGNAL destroyed of QApplication object at 0x7f8891e90ee8> %gui %gui tk app = get_ipython().kernel.app app Out[13]: <tkinter.Tk object .> ``` </details> That's an interesting idea. However, on my ipython terminal with same version of python and ipython from conda-forge (on Ubuntu) my `get_ipython()` doesn't have a kernel. Or is your above output from a spyder session? yeah, sorry, it is from a spyder session. Ok I think I like this. Just tested the `%gui qt` stuff in a notebook just to make sure and the behavior is similar. Even if you do `%gui notebook` or `%gui ipympl` it doesn't create the `app` attribute because I'm guessing it isn't needed (we're already using the javascript/browser event loop). So if we check that a kernel attribute exists that means we are running on some "remote" kernel. If that `kernel` has an `app` attribute then that means the user or some other system (spyder) has explicitly set what GUI backend to use (for matplotlib or other GUI tools) and vispy can safely assume it shouldn't use the webgl widget/backend. If this `app` has a different behavior/existence when multiple frontends are connected to the same kernel then we can deal with that at a later time. At that point people should be explicitly setting their backends anyway. Maybe we need to add a secondary check: First check for the kernel, then check if the kernel has an active graphical backend, through the app attribute I guess the problem with checking `get_ipython().kernel.app` is that `kernel` doesnt' exist for ipython consoles. That said, they can still use the `%gui qt` line magic, and likely should to get hooked into the event loop. One could check `get_ipython().active_eventloop`, which seems to have the following values: | Environment | Configuration | get_ipython().active_eventloop | Usecase | |-------------|----------------|--------------------------------|----------| | console | none | None | djhoese | | console | `%gui qt` | 'qt' | djhoese | | spyder | inline backend | 'inline' | hmaarrfk | | spyder | qt5 | 'qt5' | hmaarrfk | | notebook | none | None | djhoese | | notebook | `%gui qt` | 'qt' | jni | I mostly put the name of the interested parties next to them so that they may chime in the testing phase should it be necessary.
2019-09-29T17:45:59
vispy/vispy
1,728
vispy__vispy-1728
[ "1727" ]
4e269188c440ae92c9b13b343d292de3e321a086
diff --git a/vispy/visuals/volume.py b/vispy/visuals/volume.py --- a/vispy/visuals/volume.py +++ b/vispy/visuals/volume.py @@ -448,7 +448,7 @@ def __init__(self, vol, clim=None, method='mip', threshold=None, self.threshold = threshold if (threshold is not None) else vol.mean() self.freeze() - def set_data(self, vol, clim=None): + def set_data(self, vol, clim=None, copy=True): """ Set the volume data. Parameters @@ -457,6 +457,8 @@ def set_data(self, vol, clim=None): The 3D volume. clim : tuple | None Colormap limits to use. None will use the min and max values. + copy : bool | True + Whether to copy the input volume prior to applying clim normalization. """ # Check volume if not isinstance(vol, np.ndarray): @@ -473,8 +475,8 @@ def set_data(self, vol, clim=None): if self._clim is None: self._clim = vol.min(), vol.max() - # Apply clim - vol = np.array(vol, dtype='float32', copy=False) + # Apply clim (copy data by default... see issue #1727) + vol = np.array(vol, dtype='float32', copy=copy) if self._clim[1] == self._clim[0]: if self._clim[0] != 0.: vol *= 1.0 / self._clim[0]
diff --git a/vispy/visuals/tests/test_volume.py b/vispy/visuals/tests/test_volume.py --- a/vispy/visuals/tests/test_volume.py +++ b/vispy/visuals/tests/test_volume.py @@ -57,4 +57,26 @@ def test_volume_draw(): assert_image_approved(c.render(), 'visuals/volume.png') +@requires_pyopengl() +def test_set_data_does_not_change_input(): + # Create volume + V = scene.visuals.Volume(np.zeros((20, 20, 20))) + + # calling Volume.set_data() should NOT alter the values of the input array + # regardless of data type + vol = np.random.randint(0, 200, (20, 20, 20)) + for dtype in ['uint8', 'int16', 'uint16', 'float32', 'float64']: + vol_copy = np.array(vol, dtype=dtype, copy=True) + # setting clim so that normalization would otherwise change the data + V.set_data(vol_copy, clim=(0, 200)) + assert np.allclose(vol, vol_copy) + + # for those using float32 who want to avoid the copy operation, + # using set_data() with `copy=False` should be expected to alter the data. + vol2 = np.array(vol, dtype='float32', copy=True) + assert np.allclose(vol, vol2) + V.set_data(vol2, clim=(0, 200), copy=False) + assert not np.allclose(vol, vol2) + + run_tests_if_main()
VolumeVisual.set_data method and copy=False may lead to unexpected behavior An issue recently arose in the napari repo (see napari/napari#575) in which calling the `VolumeVisual.set_data()` method was altering the input data and causing unexpected results (but only with float32 input data). We eventually realized it was caused by line 477 below in the `set_data()` method, in which the data is converted to float32 with `copy=False`. https://github.com/vispy/vispy/blob/8b61cd439076aa3f50ac5f6dacb4c0af8c1d0684/vispy/visuals/volume.py#L477-L483 I realize we can simply copy the data on our end before calling the `VolumeVisual.set_data()` method, but I'm wondering whether the default behavior shouldn't be to copy the volume before applying the clim normalizations, so as to avoid unexpectedly overwriting the input data)? (it was particularly hard to find due to the fact that the memory address of the input volume is unchanged _only_ for float32 data)
Just to add a +1 here. imho a visualisation library should never modify its input data. Short term, changing to `copy=True` would be a good fix. Longer term, should it not be possible to do the clim adjustment in the shader? Apologies for the naive question as I know very little about shaders! Wow, what a bug. My initial feeling is that the user should be responsible for copying so we at least allow for the fast no-copy version of the code. That is only coming from a performance point of view and not one concerned about user experience. As you pointed out, only **not** copying when it is float32 data is not very useful and is strange. I vote for an explicit copy but I'd like to hear the arguments from @larsoner and @kmuehlbauer too. I don't have a lot of experience with the VolumeVisual but do with the ImageVisual which has similar logic. Looking at the source code now it looks like the ImageVisual starts with an out of place operation so it copies the data: https://github.com/vispy/vispy/blob/61fcfe17c6eaa6cbb7657ba4ae9cfe07957ff85f/vispy/visuals/image.py#L406 @jni You are right that shaders could do this logic. The main issue is that OpenGL 2.0 (ES 2) do not support 32-bit float textures. This means that you end up getting something equivalent to an 8-bit integer in the GPU (even though they are represented as 0-1 floats in the GL shaders) and storing 32-bit or 64-bit floats in to an 8-bit float loses you a lot of precision. By doing the clim scaling in the CPU we can reduce the amount of lost precision/data. I think because vispy was originally written with this backwards and mobile compatibility as a main goal, it did not allow the user to do things that weren't compatible. In my own work I've made a custom version of the ImageVisual which does exactly as you propose, it takes the clims, gives them to the shader, and then stores the data on the GPU as a 32-bit float (iirc). The shader then does the scaling and gets the benefit of having all of the original data locally in the GPU. I would be open to the VolumeVisual and ImageVisual getting the functionality to declare their textures in a way to support this. @djhoese an explicit copy with the option of turning that off for performance would be good. Then the option in the keyword argument could have a fat warning that the data would me modified in-place. Thank you for the background info. From long experience, indeed most choices make much more sense when framed in the historical context of the library! Agreed we should have a `copy=True` parameter, silently changing people's values (and doing so by default) is dangerous @tlambert03 or @jni Interested in making a pull request (for that sweet sweet hacktoberfest shirt)?
2019-10-22T15:21:23
vispy/vispy
1,730
vispy__vispy-1730
[ "1729" ]
4e269188c440ae92c9b13b343d292de3e321a086
diff --git a/vispy/app/canvas.py b/vispy/app/canvas.py --- a/vispy/app/canvas.py +++ b/vispy/app/canvas.py @@ -245,6 +245,7 @@ def toggle_fs(): if not isinstance(keys, dict): raise TypeError('keys must be a dict, str, or None') if len(keys) > 0: + lower_keys = {} # ensure all are callable for key, val in keys.items(): if isinstance(val, string_types): @@ -256,9 +257,8 @@ def toggle_fs(): if not hasattr(val, '__call__'): raise TypeError('Entry for key %s is not callable' % key) # convert to lower-case representation - keys.pop(key) - keys[key.lower()] = val - self._keys_check = keys + lower_keys[key.lower()] = val + self._keys_check = lower_keys def keys_check(event): if event.key is not None:
Python 3.8 RuntimeError: dictionary keys changed during iteration `windows`, `vispy 0.6.1`, `x64` When I have installed python 3.7, vispy 0.6.1 was built successfully with minimal Microsoft Visual C++ 14.0 Build Tools during pip install. And my application ran great. Now I have python 3.8, and vispy pip installation process fails with the errors. OK, I downloaded .whl from https://www.lfd.uci.edu/~gohlke/pythonlibs and installed successfully. Then I started my app and it crashed with the following: ``` File "C:\Python38\lib\site-packages\vispy\scene\canvas.py", line 134, in __init__ super(SceneCanvas, self).__init__( File "C:\Python38\lib\site-packages\vispy\app\canvas.py", line 194, in __init__ self._set_keys(keys) File "C:\Python38\lib\site-packages\vispy\app\canvas.py", line 249, in _set_keys for key, val in keys.items(): RuntimeError: dictionary keys changed during iteration ```
Looks like you're right. This should probably be updated to create a new dictionary. Pull requests welcome! Wow, I'm afraid, I have no enough qualification for pull request... although might I will try later. For now I solved the problem in easy mode. My app called `scene.SceneCanvas.__init__` with `keys='interactive'` and if I remove this argument, it's works as fine as before. Let me know if you need any help (github has some nice guides somewhere). Otherwise, I've marked this as "hacktoberfest" so anyone needing some last minute pull requests to get their t-shirt will find this more easily.
2019-10-24T13:44:20
vispy/vispy
1,748
vispy__vispy-1748
[ "1742" ]
612776584a195aefd6369b5bde0a1799f3cfad27
diff --git a/vispy/plot/plotwidget.py b/vispy/plot/plotwidget.py --- a/vispy/plot/plotwidget.py +++ b/vispy/plot/plotwidget.py @@ -122,14 +122,6 @@ def _configure_2d(self, fg_color=None): yaxis_widget = self.grid.add_widget(self.yaxis, row=2, col=3) yaxis_widget.width_max = 40 - self.view = self.grid.add_view(row=2, col=4, - border_color='grey', bgcolor="#efefef") - self.view.camera = 'panzoom' - self.camera = self.view.camera - - self.cbar_right = self.grid.add_widget(None, row=2, col=5) - self.cbar_right.width_max = 1 - # row 3 # xaxis - column 4 self.xaxis = scene.AxisWidget(orientation='bottom', text_color=fg, @@ -137,6 +129,9 @@ def _configure_2d(self, fg_color=None): xaxis_widget = self.grid.add_widget(self.xaxis, row=3, col=4) xaxis_widget.height_max = 40 + self.cbar_right = self.grid.add_widget(None, row=2, col=5) + self.cbar_right.width_max = 1 + # row 4 # xlabel - column 4 self.xlabel = scene.Label("") @@ -147,6 +142,12 @@ def _configure_2d(self, fg_color=None): self.cbar_bottom = self.grid.add_widget(None, row=5, col=4) self.cbar_bottom.height_max = 1 + # This needs to be added to the grid last (to fix #1742) + self.view = self.grid.add_view(row=2, col=4, + border_color='grey', bgcolor="#efefef") + self.view.camera = 'panzoom' + self.camera = self.view.camera + self._configured = True self.xaxis.link_view(self.view) self.yaxis.link_view(self.view)
diff --git a/vispy/plot/tests/test_plot.py b/vispy/plot/tests/test_plot.py --- a/vispy/plot/tests/test_plot.py +++ b/vispy/plot/tests/test_plot.py @@ -5,6 +5,12 @@ import vispy.plot as vp from vispy.testing import (assert_raises, requires_application, run_tests_if_main) +from vispy.visuals.axis import AxisVisual + +try: + from unittest import mock +except ImportError: + import mock @requires_application() @@ -18,4 +24,28 @@ def test_figure_creation(): # collision assert_raises(ValueError, fig.__getitem__, (slice(1, 3), 1)) + +@requires_application() +def test_plot_widget_axes(): + """Test that the axes domains are updated correctly when a figure is first drawn""" + + fig = vp.Fig(size=(800, 800), show=False) + point = (0, 100) + fig[0, 0].plot((point, point)) + # mocking the AxisVisual domain.setter + domain_setter = mock.Mock(wraps=AxisVisual.domain.fset) + mock_property = AxisVisual.domain.setter(domain_setter) + + with mock.patch.object(AxisVisual, "domain", mock_property): + # note: fig.show() must be called for this test to work... otherwise + # Grid._update_child_widget_dim is not triggered and the axes aren't updated + fig.show(run=False) + # currently, the AxisWidget adds a buffer of 5% of the + # full range to either end of the axis domain + buffer = (point[1] - point[0]) * 0.05 + expectation = [point[0] - buffer, point[1] + buffer] + for call in domain_setter.call_args_list: + assert [round(x, 2) for x in call[0][1]] == expectation + + run_tests_if_main()
axis labels problem I was using the plot.py example and I got the following problems: 1. the xaxis labels are overlapped to the x axis 2. the xaxis labels values do not correspond to the actual x axis domain; they are adjusted to the correct values after resizing the window. 3. some other problems with yaxis labels and title (see attached picture) ![plot_py_screenshot](https://user-images.githubusercontent.com/50824984/68126482-34191a80-ff14-11e9-9690-9885c0ddc735.JPG)
Some of this seems like the default font size is too large. We've seen the ticks not updating issue before, but I thought we fixed it. What backend are you using? Here is what it looks like with the current master branch on my Ubuntu system with PyQt5: ![image](https://user-images.githubusercontent.com/1828519/68128912-3ceef980-fede-11e9-9442-3f34bbb2685c.png) I am using PyQt5 on Windows 10. Yes there is also a font size problem. It would be better if the axis_font_size and the tick_font_size could be set from the user application. Your plot is better than mine, but, as you can see, the x axis labels are wrong (they should be from 0 to 10) and they touch the tick marks. You're right about the ticks being wrong. I guess this is still an issue. The tick labels touching the tick marks may be something that has always existed and was never completely made to look "perfect". @larsoner may remember more. I could get a better plot modifying the font size of the labels and adding some margins. ![plot_py_screenshot2](https://user-images.githubusercontent.com/50824984/68214527-e963d500-ffdd-11e9-901a-fce005734eed.jpg) ```fig[0,0].xlabel._text_visual.font_size=8 fig[0,0].ylabel._text_visual.font_size=8 fig[0,0].ylabel.width_min = fig[0,0].ylabel.width_max = 80 fig[0,0].title._text_visual.font_size=8 fig[0,0].xaxis.axis.tick_label_margin=35 fig[0,0].yaxis.axis.axis_label_margin=50 As I noticed that if you move the plot the xaxis is updated with the correct tick labels, I was trying to force an xaxis update setting _need_update=True and calling the update() method, but it didn't work. ``` fig[0,0].xaxis.axis._need_update = True fig[0,0].xaxis.axis.update() ``` If I remember correctly, the last time this came up it was caused by a race condition where the ticks would be updated to the correct values and then immediately set back to the incorrect (initial) values. I'm sorry I don't have time to look in to it more right now. Thank you for the link to the bug fixes related to AxisVisual. They seem to concern some other problems. In my Qt application I found that the x axis domain is correct until the show() method is called. After, it gets wrong. If I update the plot after the show() method is executed, the x axis domain is correct. Something happens while executing the show() method. A strange thing is that only the x axis has this kind of problems. Yeah, I think I've tried to fix this bug in the past, but never found the real problem or maybe it was that it didn't have an easy solution. Like I mentioned I think it has to do with a basic default x range being set *after* the real data's x range is already set. Solving this bug will require walking through the code and finding when the domain is updated and from where (is it a default value, is it from the data, did the user set it, etc). I won't have time to look in to this any time soon though. This is the code ``` print('(plot-1) xaxis domain:', self.plot.ax.xaxis.axis.domain) print('(plot-1) yaxis domain:', self.plot.ax.yaxis.axis.domain) self.show() print('(plot-2) xaxis domain:', self.plot.ax.xaxis.axis.domain) print('(plot-2) yaxis domain:', self.plot.ax.yaxis.axis.domain) self.plot.update_view() print('(plot-3) xaxis domain:', self.plot.ax.xaxis.axis.domain) print('(plot-3) yaxis domain:', self.plot.ax.yaxis.axis.domain) ``` This is the output: ``` (plot-1) xaxis domain: (-3.435610274790101, 3.098064060261222) (plot-1) yaxis domain: (-0.8999991856813033, 18.900001782059757) (plot-2) xaxis domain: (-5.046775266898924, -4.957760627687946) (plot-2) yaxis domain: (-0.8999998271748488, 18.900000467268093) (plot-3) xaxis domain: (-3.435610297180214, 3.0980642209056075) (plot-3) yaxis domain: (-0.8999998271748488, 18.900000467268093) ``` The plot-2 x axis domain is the wrong one. The solution I found for my application is not so elegant, but I am satisfied with it. The user will not see the bug anyway.
2019-11-10T16:41:59
vispy/vispy
1,756
vispy__vispy-1756
[ "1755" ]
2c3ab163b7e90eddb14c2cd98e91dec615acae57
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -209,7 +209,7 @@ def run(self): 'jsdeps': NPM, }, python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*', - install_requires=['numpy', 'freetype-py'], + install_requires=['numpy', 'freetype-py', 'setuptools'], setup_requires=['numpy', 'cython', 'setuptools_scm', 'setuptools_scm_git_archive'], extras_require={ 'ipython-static': ['ipython'], diff --git a/vispy/gloo/glir.py b/vispy/gloo/glir.py --- a/vispy/gloo/glir.py +++ b/vispy/gloo/glir.py @@ -582,7 +582,7 @@ def _convert_es2_shader(shader): for line in shader.lstrip().splitlines(): line_strip = line.lstrip() if line_strip.startswith('#version'): - has_version = True + # has_version = True continue if line_strip.startswith('#extension'): extensions.append(line_strip)
diff --git a/vispy/gloo/tests/test_glir.py b/vispy/gloo/tests/test_glir.py --- a/vispy/gloo/tests/test_glir.py +++ b/vispy/gloo/tests/test_glir.py @@ -46,7 +46,21 @@ def test_queue(): # Convert for es2 shader3 = glir.convert_shader('es2', shader2) + # make sure precision float is still in the shader + # it may not be the first (precision int might be there) assert 'precision highp float;' in shader3 + # precisions must come before code + assert shader3.startswith('precision') + + # Define shader with version number + shader4 = """ + #version 100; precision highp float;uniform mediump vec4 u_foo;uniform vec4 u_bar; + """.strip().replace(';', ';\n') + shader5 = glir.convert_shader('es2', shader4) + assert 'precision highp float;' in shader5 + # make sure that precision is first (version is removed) + # precisions must come before code + assert shader3.startswith('precision') @requires_application()
Some visuals doesn't show in notebooks Hello @djhoese , following the discussion on gitter, here's a small example illustrating an image that is properly plotted and markers that doesn't show. Same behavior inside jupyter notebook and jupyter lab. Can you please telle me how to get the log? Because in the terminal I've no errors. # Displaying the image ```python import numpy as np from vispy import scene from vispy import app from vispy.scene.cameras import PanZoomCamera # camera and scene canvas cam = PanZoomCamera(rect=(-1, -1, 7, 7)) sc = scene.SceneCanvas(bgcolor='black', show=True) wc = sc.central_widget.add_view(camera=cam) # image scene.visuals.Image(np.arange(25).reshape(5, 5), parent=wc.scene) sc.show() ``` ![Screenshot_20191116_094906](https://user-images.githubusercontent.com/15892073/68990696-600e9700-0856-11ea-9860-b7b37d88af12.png) # Markers are not plotted ```python # camera and scene canvas cam_2 = PanZoomCamera(rect=(-1, -1, 7, 7)) sc_2 = scene.SceneCanvas(bgcolor='black', show=True) wc_2 = sc_2.central_widget.add_view(camera=cam_2) # markers pos = np.random.uniform(0, 5, (1000, 2)) scene.visuals.Markers(pos=pos, parent=wc_2.scene, face_color='red') sc_2.show() ``` ![Screenshot_20191116_095115](https://user-images.githubusercontent.com/15892073/68990712-a5cb5f80-0856-11ea-9965-eb4256ae4313.png)
2019-11-16T17:25:15
vispy/vispy
1,780
vispy__vispy-1780
[ "1779" ]
ded293841c6438ab54af10c561f372155bb77edc
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -178,7 +178,7 @@ def run(self): readme = open('README.rst', 'r').read() setup( name=name, - use_scm_version=True, + use_scm_version={'write_to': 'vispy/version.py'}, author='Vispy contributors', author_email='[email protected]', license='(new) BSD', @@ -209,7 +209,7 @@ def run(self): 'jsdeps': NPM, }, python_requires='>=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*', - install_requires=['numpy', 'freetype-py', 'setuptools'], + install_requires=['numpy', 'freetype-py'], setup_requires=['numpy', 'cython', 'setuptools_scm', 'setuptools_scm_git_archive'], extras_require={ 'ipython-static': ['ipython'], @@ -223,7 +223,7 @@ def run(self): 'wx': ['wxPython'], 'doc': ['sphinx_bootstrap_theme', 'numpydoc'], }, - packages=find_packages(), + packages=find_packages(exclude=['make']), ext_modules=cythonize(extensions), package_dir={'vispy': 'vispy'}, data_files=[ diff --git a/vispy/__init__.py b/vispy/__init__.py --- a/vispy/__init__.py +++ b/vispy/__init__.py @@ -18,13 +18,12 @@ """ from __future__ import division -from pkg_resources import get_distribution, DistributionNotFound __all__ = ['use', 'sys_info', 'set_log_level', 'test'] try: - __version__ = get_distribution(__name__).version -except DistributionNotFound: + from .version import version as __version__ # noqa +except ImportError: # package is not installed pass
diff --git a/vispy/util/tests/test_import.py b/vispy/util/tests/test_import.py --- a/vispy/util/tests/test_import.py +++ b/vispy/util/tests/test_import.py @@ -16,7 +16,7 @@ # minimum that will be imported when importing vispy -_min_modules = ['vispy', 'vispy.util', 'vispy.ext', 'vispy.ipython', 'vispy.testing'] +_min_modules = ['vispy', 'vispy.util', 'vispy.ext', 'vispy.ipython', 'vispy.testing', 'vispy.version'] def loaded_vispy_modules(import_module, depth=None, all_modules=False):
Slow import On my Windows workstation with >1200 of Python packages installed, `import vispy` takes about 3.4 seconds. 98% of that time is spend at https://github.com/vispy/vispy/blob/ded293841c6438ab54af10c561f372155bb77edc/vispy/__init__.py#L26 On this system, more than half of `napari`'s import time is spent on determining the vispy version. Please consider not using `pkg_resources` during runtime. Loosely related to https://github.com/napari/napari/pull/745 https://github.com/pypa/setuptools/issues/510
Oh, wow, great catch! The reason pkg_resources is used is because we are using `setuptools_scm` to automatically determine the version number from the git history of the package. I figured this would be a performance hit, but I think we all (@kmuehlbauer @larsoner) decided it wouldn't be that bad and it is recommended ways of using setuptools_scm from their documentation. There is an option with setuptools_scm to write the version to a file (ex. `vispy/version.py`) but some maintainers were worried this would cause confusion or complications when new contributors were doing a dev installation and saw a new version.py file get created. After the last couple versions experience with setuptools_scm I'm starting to lean towards adding this version.py file the way I originally planned on doing it. I agree that this 3s import is just ridiculous. I thought it would be good if you understood why `pkg_resources` was being used rather than assuming we were doing something just because we wanted to. This is the default way setuptools_scm works. @kmuehlbauer @larsoner Feel free to chime in on concerns about using `vispy/version.py` (it is generated by setuptools_scm when you install the package from source). To be fair, fixing this issue is not enough to speed up napari loading. There are other packages that are using `pkg_resources`: triangle, docutils, and sphinx. @cgohlke for `napari` is it reasonable to nest the `triangle`, `docutils`, and `sphinx` imports? Or at least make it so that the submodules that use them are only loaded on demand? Then `vispy` would still be the bottleneck. > I'm starting to lean towards adding this version.py file the way I originally planned on doing it. I agree that this 3s import is just ridiculous. Agreed this is too much and we should avoid it. Writing `version.py` seems better in light of this overhead. Better to let `vispy` devs doing editable installs go through some confusion rather than all end users suffer through 3 sec imports. @cgohlke Any idea, why `pkg_resources` needs that much time? For me it's only 0.2 sec to `time python -c "import pkg_resources"`. I'm going to guess it's because of the 1200+ packages installed on that system (see top comment), and `pkg_resources` doing some parsing of installed packages on import. @larsoner I think the better test would be to do the `get_distribution` call for `vispy`. I think pkg_resources is having trouble finding the metadata for the vispy package among all the installed packages. Once it finds it then it should be parsing the metadata and pulling out the version number. Ahh that would be better. 0.24 sec for `import vispy` for me, 0.20 for `python -c "import pkg_resources; pkg_resources.get_distribution('vispy')"` > Any idea, why pkg_resources needs that much time? On this system, `import pkg_resources` causes over 93,000 file system operations (CreateFile, CloseFile, QueryInformation...). > suffer through 3 sec imports That is for a Python installation on a fast SSD with huge cache. Importing from a network drive takes in the order of 30 seconds. Code for `get_distribution` if anyone is interested: https://bitbucket.org/pypa/pkg_resources/src/33e56f318f5086158de8bb2827acb55db2dbc153/pkg_resources.py?fileviewer=file-view-default#pkg_resources.py-368 Not that we are going to convince any changes that haven't been considered on the setuptools side. I'll just have to switch to using the version.py static file method. @cgohlke If I get this implemented in a pull request would you be able to test it on your system with the 1200 packages? Also: https://github.com/pypa/setuptools/issues/510#issuecomment-463667124 > If I get this implemented in a pull request would you be able to test it on your system with the 1200 packages? sure
2019-12-03T19:49:57
vispy/vispy
1,784
vispy__vispy-1784
[ "1783" ]
5fa85e0e9e639ce4282d04718fcd4c17de4d8e8d
diff --git a/vispy/app/backends/_ipynb_vnc.py b/vispy/app/backends/_ipynb_vnc.py --- a/vispy/app/backends/_ipynb_vnc.py +++ b/vispy/app/backends/_ipynb_vnc.py @@ -52,7 +52,7 @@ def _set_config(c): _app.backend_module._set_config(c) -# Init dummy objects needed to import this module withour errors. +# Init dummy objects needed to import this module without errors. # These are all overwritten with imports from IPython (on success) DOMWidget = object Unicode = Int = Float = Bool = lambda *args, **kwargs: None
Fix simple typo: withour -> without There is a small typo in vispy/app/backends/_ipynb_vnc.py. Should read without rather than withour.
2019-12-07T08:46:47
vispy/vispy
1,794
vispy__vispy-1794
[ "1793" ]
779e601589f9be20e4c1c9719445475012aa3fdc
diff --git a/vispy/color/_color_dict.py b/vispy/color/_color_dict.py --- a/vispy/color/_color_dict.py +++ b/vispy/color/_color_dict.py @@ -190,4 +190,5 @@ def get_color_dict(): "tomato": "#ff6347", "white": "#ffffff", "yellow": "#ffff00", + "transparent": "#00000000", }
Add transparent color to internal color dictionary Hi, I've been working extending and improving `napari`'s color support (mostly [here](https://github.com/napari/napari/pull/782)) and we'd be very happy to have a "transparent" color in your internal `color_dict`, which simply corresponds to `#00000000`. This modification is very minimal (I'd be happy to do it myself) and can provide us with the bare-bones support we'd like to see. Is that possible? Thanks. _Originally posted by @HagaiHargil in https://github.com/vispy/vispy/issues/1345#issuecomment-566884858_
@hagaihargil I'm not super familiar with the internals of napari, but why is this needed? I am not against a "transparent" color being added in principal. It looks like the colors in https://github.com/vispy/vispy/blob/master/vispy/color/_color_dict.py are mostly CSS colors. Any idea if CSS has an idea of a transparent color name? I don't see it in the json file our list was originally created from. https://stackoverflow.com/a/26538388/433202 Looks like `transparent` can be used in CSS. Hi, I didn't see it as well in existing online lists. The idea behind it is pretty straight-forward - a user can choose to display a group of points in napari's viewer, for example. The user can then choose individual points and change their features - color, size, etc. It could be nice to allow our users to make a point's face color transparent, while keeping it's edge color colored, to help with viewing data located "underneath" that point. Ok, that's fine, but why does the name have to exist in vispy for this to work? Couldn't napari send an RGBA color tuple or even a full ColorArray object with whatever colors it wants? I can see how letting vispy handle this would be easier, just curious. We're currently completely reliant on your color pallette when interpreting named colors. This means that if a user gives napari a list or a `ColorArray` of colors, napari hands the parsing of these color arrays straight to vispy. This is done so that the list of colors will be traversed only once - by vispy. If we were to add our own "transparent" keyword, then when a color list is passed we'd need to: 1. Iterate over the list and check whether there are any "transparent" colors in it. 2. Change these colors into their hex repr. 3. Pass the modified list back to vispy for actual parsing and rendering. This iteration is done in pure Python, and color lists can contain tens of thousands of elements, so performance might be an issue. Vispy already traverses this list at least twice in pure Python, and possibly a few times more (the `any` call, recursion). It's obviously possible, and we might decide to follow that pipeline I just described in the mean time, but it definitely seems much cleaner and clearer to add a single "transparent" key to vispy's color dictionary from our perspective. I hope things are a bit clearer. Makes sense. I guess I didn't realize people would be providing a list of names of colors for a color map in napari. Anyway, feel free to make the PR.
2019-12-18T17:36:40
vispy/vispy
1,824
vispy__vispy-1824
[ "1817" ]
f809ad4fbc35a8a6e2e0b951b927e7838a6d0ddc
diff --git a/setup.py b/setup.py --- a/setup.py +++ b/setup.py @@ -222,6 +222,7 @@ def run(self): 'sdl2': ['PySDL2'], 'wx': ['wxPython'], 'doc': ['sphinx_bootstrap_theme', 'numpydoc'], + 'io': ['meshio'], }, packages=find_packages(exclude=['make']), ext_modules=cythonize(extensions), diff --git a/vispy/io/mesh.py b/vispy/io/mesh.py --- a/vispy/io/mesh.py +++ b/vispy/io/mesh.py @@ -5,6 +5,7 @@ """ Reading and writing of data like images and meshes. """ +import os from os import path as op from .wavefront import WavefrontReader, WavefrontWriter @@ -46,14 +47,26 @@ def read_mesh(fname): normals = mesh['face_normals'] texcoords = None return vertices, faces, normals, texcoords - elif not format: - raise ValueError('read_mesh needs could not determine format.') else: - raise ValueError('read_mesh does not understand format %s.' % fmt) + try: + import meshio + except ImportError: + raise ValueError('read_mesh does not understand format %s.' % fmt) + + try: + mesh = meshio.read(fname) + except meshio.ReadError: + raise ValueError('read_mesh does not understand format %s.' % fmt) + + triangles = mesh.get_cells_type("triangle") + if len(triangles) == 0: + raise ValueError('mesh file does not contain triangles.') + + return mesh.points, triangles, None, None def write_mesh(fname, vertices, faces, normals, texcoords, name='', - format='obj', overwrite=False, reshape_faces=True): + format=None, overwrite=False, reshape_faces=True): """ Write mesh data to file. Parameters @@ -82,8 +95,29 @@ def write_mesh(fname, vertices, faces, normals, texcoords, name='', if op.isfile(fname) and not overwrite: raise IOError('file "%s" exists, use overwrite=True' % fname) + if format is None: + format = os.path.splitext(fname)[1][1:] + # Check format - if format not in ('obj'): - raise ValueError('Only "obj" format writing currently supported') - WavefrontWriter.write(fname, vertices, faces, - normals, texcoords, name, reshape_faces) + if format == 'obj': + WavefrontWriter.write(fname, vertices, faces, + normals, texcoords, name, reshape_faces) + return + + try: + import meshio + except ImportError: + raise ValueError('write_mesh does not understand format %s.' % format) + + cell_data = {} + if normals is not None: + cell_data["normals"] = [normals] + if texcoords is not None: + cell_data["texcoords"] = [texcoords] + + mesh = meshio.Mesh(vertices, [("triangle", faces)], cell_data=cell_data) + + try: + mesh.write(fname, file_format=format) + except meshio.WriteError: + raise ValueError('write_mesh does not understand format %s.' % format)
diff --git a/vispy/io/tests/test_io.py b/vispy/io/tests/test_io.py --- a/vispy/io/tests/test_io.py +++ b/vispy/io/tests/test_io.py @@ -64,6 +64,26 @@ def test_wavefront_non_triangular(): assert lines[-2].startswith('f 2 1 8 7 6 4') +def test_meshio(): + '''Test meshio i/o''' + vertices = np.array([[0.0, 0.0, 0.0], + [1.0, 0.0, 0.], + [-.0, 1.0, 0.], + [1.0, 1.0, 0.]]) + + faces = np.array([[0, 1, 3], + [1, 2, 3]]) + fname_out = op.join(temp_dir, 'temp.vtk') + write_mesh(fname_out, vertices=vertices, + faces=faces, normals=None, + texcoords=None, overwrite=True, + reshape_faces=False) + out_vertices, out_faces, _, _ = read_mesh(fname_out) + + assert np.all(np.abs(out_vertices - vertices) < 1.0e-14) + assert np.all(out_faces == faces) + + def _slow_calculate_normals(rr, tris): """Efficiently compute vertex normals for triangulated surface""" # first, compute triangle normals
meshio for i/o Main author of [meshio](https://github.com/nschloe/meshio) here. meshio can read a large number of formats which are applicable for vispy, I think it would be a good match for meshio.
Great! Glad to have you here. Do you have specific interfaces in mind? How do you see VisPy users using meshio? Right now we have a couple utility functions that use other libraries like: https://github.com/vispy/vispy/blob/master/vispy/io/mesh.py Which uses some functions created for reading STL files which was copied from the trimesh project: https://github.com/vispy/vispy/blob/master/vispy/io/stl.py There are also some wavefront readers and writers: https://github.com/vispy/vispy/blob/master/vispy/io/wavefront.py > How do you see VisPy users using meshio? Well, how do users use `load_stl` right now? _Edit:_ Via `read_mesh` it seems: ```python import vispy.io mesh = vispy.io.read_mesh("out.stl") print(mesh) ``` So, I imagine the same thing with the difference that you can put just about anything for `out.stl`. One difficulty I do see is the fact that your reader always returns outward normals and "texture coordinates". Is this a strict requirement? Also, do you _need_ triangles or can you handle other shapes are well? @larsoner or @kmuehlbauer might know more, otherwise there may be existing pull requests or issues that have users who are more familiar with this. I don't really use meshes and am not familiar with the various ways (common or not) that they are described. I believe we read things this way because it is directly passed to our MeshVisual object. I wouldn't be surprised if this is limited to triangles. The texture coordinates might be flexible, but it really depends on what the [MeshVisual](https://github.com/vispy/vispy/blob/master/vispy/visuals/mesh.py#L150) and its lower-level object [MeshData](https://github.com/vispy/vispy/blob/master/vispy/geometry/meshdata.py#L24) can handle. Note: There are some very important changes being worked on in open PRs (https://github.com/vispy/vispy/pulls?utf8=%E2%9C%93&q=is%3Apr+is%3Aopen+mesh). They are missing a few changes, fixes, and tests before they can be merged but they may make some of this more possible. @nschloe There were quite some attempts to improve on mesh loading, afair. I'm too not involved too much into meshes in general. But it would be nice, if meshio could be used to serve MishVisual/MeshData the needed values. As @djhoese already mentioned, there are open PR which change Mesh Handling within vispy, ping @asnt. @nschloe Please have a look at #1665 which mentions some ides/wishes for improvement on loading meshes. I think that a loading mechanism that returns all the mesh info with a predictable and systematic data structure would be welcome. It seems meshio can provide some of that with `mesh.points`, `mesh.cells`... but I don't see support for other attribute arrays and data (texture images, texture coordinates...) in the [OBJ loader](https://github.com/nschloe/meshio/blob/3c12f1598e6a01ef26f9b12c94ebfa358d4c547f/meshio/obj/_obj.py#L22), for example. Did I miss it or is it planned? Is it implemented for other mesh formats maybe? > One difficulty I do see is the fact that your reader always returns outward normals and "texture coordinates". Is this a strict requirement? The current loaders return a tuple `(vertices, faces, normals, texcoords)`. This is restrictive to specific cases. A more flexible structure would be welcome. > Also, do you need triangles or can you handle other shapes are well? I am not sure but I think most of vispy assumes triangles as primitives. Being able to load quads would open the door to variations, though. (At least, we would be able to display quad meshes by converting them as triangle meshes internally. That might be OK for some applications.) > but I don't see support for other attribute arrays and data (texture images, texture coordinates...) There is `mesh.cell_data`, `mesh.point_data` etc. which host such things. It is possible that some readers haven't implemented support for this yet (e.g., obj files), but this would definitely be something we want are are going to have in meshio. > I am not sure but I think most of vispy assumes triangles as primitives. That's fair enough. meshio supports many more cell types (3D too, like tetrahedra, pyramids etc.), but it's easy to just single out the triangles in a file. I think VisPy's preference for triangles is that it tries to keep OpenGL 2.x and OpenGL ES support. I *think* older GPUs had a limitation on triangles only and quads were just made up of two triangles. As @asnt points out we could convert internally if needed. Is it a problem that meshio supports Python 3.5+ only? (Not Python 2.7.) The next release of vispy will be likely be 3.6+ (definitely not 2.7).
2020-02-20T17:32:42
vispy/vispy
1,859
vispy__vispy-1859
[ "1858" ]
f1de04c52269d4288030b641d652afdac8e77183
diff --git a/vispy/color/color_array.py b/vispy/color/color_array.py --- a/vispy/color/color_array.py +++ b/vispy/color/color_array.py @@ -47,7 +47,7 @@ def _user_to_rgba(color, expand=True, clip=False): color = color.rgba # We have to treat this specially elif isinstance(color, (list, tuple)): - if any(isinstance(c, string_types) for c in color): + if any(isinstance(c, (string_types, ColorArray)) for c in color): color = [_user_to_rgba(c, expand=expand, clip=clip) for c in color] if any(len(c) > 1 for c in color): raise RuntimeError('could not parse colors, are they nested?')
diff --git a/vispy/color/tests/test_color.py b/vispy/color/tests/test_color.py --- a/vispy/color/tests/test_color.py +++ b/vispy/color/tests/test_color.py @@ -61,6 +61,11 @@ def test_color_array(): x = ColorArray(color_space="hsv") assert_array_equal(x.rgba[0], [0, 0, 0, 1]) + x = ColorArray([Color((0, 0, 0)), Color((1, 1, 1))]) + assert len(x.rgb) == 2 + x = ColorArray([ColorArray((0, 0, 0)), ColorArray((1, 1, 1))]) + assert len(x.rgb) == 2 + def test_color_interpretation(): """Test basic color interpretation API"""
Initialize ColorArray from list of color fail When initialising `CollorArray` from list of `Colors` it fails. It works if on list there is at least one definition color with string. This works: ```python array1 = ColorArray(["b", "w"]) array2 = ColorArray(["black", "white"]) array3 = ColorArray(["black", Color((1, 1, 1))]) ``` This fails: ```python array4 = ColorArray([Color((0,0,0)), Color((1, 1, 1))]) ``` with: ``` TypeError: float() argument must be a string or a number, not 'ColorArray' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/home/czaki/Projekty/partseg/vispy_test.py", line 6, in <module> array4 = ColorArray([Color((0,0,0)), Color((1, 1, 1))]) File "/home/czaki/.pyenv/versions/partseg3.6-pyside/lib/python3.6/site-packages/vispy/color/color_array.py", line 148, in __init__ rgba = _user_to_rgba(color, clip=clip) File "/home/czaki/.pyenv/versions/partseg3.6-pyside/lib/python3.6/site-packages/vispy/color/color_array.py", line 55, in _user_to_rgba color = np.atleast_2d(color).astype(np.float32) ValueError: setting an array element with a sequence. ```
Too many options in that if-else convolute: https://github.com/vispy/vispy/blob/f1de04c52269d4288030b641d652afdac8e77183/vispy/color/color_array.py#L40-L55 In line 50 we would need to add `ColorArray` in the isinstance-check, for that to work, AFAICS. PullRequest welcome :smiley:
2020-05-06T12:41:50
vispy/vispy
1,928
vispy__vispy-1928
[ "1922" ]
932d6e499791a423822513549ebd825601345c85
diff --git a/vispy/ext/_bundled/decorator.py b/vispy/ext/_bundled/decorator.py deleted file mode 100644 --- a/vispy/ext/_bundled/decorator.py +++ /dev/null @@ -1,426 +0,0 @@ -# ######################### LICENSE ############################ # - -# Copyright (c) 2005-2017, Michele Simionato -# All rights reserved. - -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are -# met: - -# Redistributions of source code must retain the above copyright -# notice, this list of conditions and the following disclaimer. -# Redistributions in bytecode form must reproduce the above copyright -# notice, this list of conditions and the following disclaimer in -# the documentation and/or other materials provided with the -# distribution. - -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -# HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, -# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS -# OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR -# TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE -# USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH -# DAMAGE. - -""" -Decorator module, see http://pypi.python.org/pypi/decorator -for the documentation. -""" -from __future__ import print_function - -import re -import sys -import inspect -import operator -import itertools -import collections - -__version__ = '4.1.2' - -if sys.version >= '3': - from inspect import getfullargspec - - def get_init(cls): - return cls.__init__ -else: - FullArgSpec = collections.namedtuple( - 'FullArgSpec', 'args varargs varkw defaults ' - 'kwonlyargs kwonlydefaults') - - def getfullargspec(f): - "A quick and dirty replacement for getfullargspec for Python 2.X" - return FullArgSpec._make(inspect.getargspec(f) + ([], None)) - - def get_init(cls): - return cls.__init__.__func__ - -try: - iscoroutinefunction = inspect.iscoroutinefunction -except AttributeError: - # let's assume there are no coroutine functions in old Python - def iscoroutinefunction(f): - return False - -# getargspec has been deprecated in Python 3.5 -ArgSpec = collections.namedtuple( - 'ArgSpec', 'args varargs varkw defaults') - - -def getargspec(f): - """A replacement for inspect.getargspec""" - spec = getfullargspec(f) - return ArgSpec(spec.args, spec.varargs, spec.varkw, spec.defaults) - - -DEF = re.compile(r'\s*def\s*([_\w][_\w\d]*)\s*\(') - - -# basic functionality -class FunctionMaker(object): - """ - An object with the ability to create functions with a given signature. - It has attributes name, doc, module, signature, defaults, dict and - methods update and make. - """ - - # Atomic get-and-increment provided by the GIL - _compile_count = itertools.count() - - # make pylint happy - args = varargs = varkw = defaults = kwonlyargs = kwonlydefaults = () - - def __init__(self, func=None, name=None, signature=None, - defaults=None, doc=None, module=None, funcdict=None): - self.shortsignature = signature - if func: - # func can be a class or a callable, but not an instance method - self.name = func.__name__ - if self.name == '<lambda>': # small hack for lambda functions - self.name = '_lambda_' - self.doc = func.__doc__ - self.module = func.__module__ - if inspect.isfunction(func): - argspec = getfullargspec(func) - self.annotations = getattr(func, '__annotations__', {}) - for a in ('args', 'varargs', 'varkw', 'defaults', 'kwonlyargs', - 'kwonlydefaults'): - setattr(self, a, getattr(argspec, a)) - for i, arg in enumerate(self.args): - setattr(self, 'arg%d' % i, arg) - if sys.version < '3': # easy way - self.shortsignature = self.signature = ( - inspect.formatargspec( - formatvalue=lambda val: "", *argspec[:-2])[1:-1]) - else: # Python 3 way - allargs = list(self.args) - allshortargs = list(self.args) - if self.varargs: - allargs.append('*' + self.varargs) - allshortargs.append('*' + self.varargs) - elif self.kwonlyargs: - allargs.append('*') # single star syntax - for a in self.kwonlyargs: - allargs.append('%s=None' % a) - allshortargs.append('%s=%s' % (a, a)) - if self.varkw: - allargs.append('**' + self.varkw) - allshortargs.append('**' + self.varkw) - self.signature = ', '.join(allargs) - self.shortsignature = ', '.join(allshortargs) - self.dict = func.__dict__.copy() - # func=None happens when decorating a caller - if name: - self.name = name - if signature is not None: - self.signature = signature - if defaults: - self.defaults = defaults - if doc: - self.doc = doc - if module: - self.module = module - if funcdict: - self.dict = funcdict - # check existence required attributes - assert hasattr(self, 'name') - if not hasattr(self, 'signature'): - raise TypeError('You are decorating a non function: %s' % func) - - def update(self, func, **kw): - "Update the signature of func with the data in self" - func.__name__ = self.name - func.__doc__ = getattr(self, 'doc', None) - func.__dict__ = getattr(self, 'dict', {}) - func.__defaults__ = self.defaults - func.__kwdefaults__ = self.kwonlydefaults or None - func.__annotations__ = getattr(self, 'annotations', None) - try: - frame = sys._getframe(3) - except AttributeError: # for IronPython and similar implementations - callermodule = '?' - else: - callermodule = frame.f_globals.get('__name__', '?') - func.__module__ = getattr(self, 'module', callermodule) - func.__dict__.update(kw) - - def make(self, src_templ, evaldict=None, addsource=False, **attrs): - "Make a new function from a given template and update the signature" - src = src_templ % vars(self) # expand name and signature - evaldict = evaldict or {} - mo = DEF.search(src) - if mo is None: - raise SyntaxError('not a valid function template\n%s' % src) - name = mo.group(1) # extract the function name - names = set([name] + [arg.strip(' *') for arg in - self.shortsignature.split(',')]) - for n in names: - if n in ('_func_', '_call_'): - raise NameError('%s is overridden in\n%s' % (n, src)) - - if not src.endswith('\n'): # add a newline for old Pythons - src += '\n' - - # Ensure each generated function has a unique filename for profilers - # (such as cProfile) that depend on the tuple of (<filename>, - # <definition line>, <function name>) being unique. - filename = '<decorator-gen-%d>' % (next(self._compile_count),) - try: - code = compile(src, filename, 'single') - exec(code, evaldict) - except: - print('Error in generated code:', file=sys.stderr) - print(src, file=sys.stderr) - raise - func = evaldict[name] - if addsource: - attrs['__source__'] = src - self.update(func, **attrs) - return func - - @classmethod - def create(cls, obj, body, evaldict, defaults=None, - doc=None, module=None, addsource=True, **attrs): - """ - Create a function from the strings name, signature and body. - evaldict is the evaluation dictionary. If addsource is true an - attribute __source__ is added to the result. The attributes attrs - are added, if any. - """ - if isinstance(obj, str): # "name(signature)" - name, rest = obj.strip().split('(', 1) - signature = rest[:-1] # strip a right parens - func = None - else: # a function - name = None - signature = None - func = obj - self = cls(func, name, signature, defaults, doc, module) - ibody = '\n'.join(' ' + line for line in body.splitlines()) - caller = evaldict.get('_call_') # when called from `decorate` - if caller and iscoroutinefunction(caller): - body = ('async def %(name)s(%(signature)s):\n' + ibody).replace( - 'return', 'return await') - else: - body = 'def %(name)s(%(signature)s):\n' + ibody - return self.make(body, evaldict, addsource, **attrs) - - -def decorate(func, caller): - """ - decorate(func, caller) decorates a function using a caller. - """ - evaldict = dict(_call_=caller, _func_=func) - fun = FunctionMaker.create( - func, "return _call_(_func_, %(shortsignature)s)", - evaldict, __wrapped__=func) - if hasattr(func, '__qualname__'): - fun.__qualname__ = func.__qualname__ - return fun - - -def decorator(caller, _func=None): - """decorator(caller) converts a caller function into a decorator""" - if _func is not None: # return a decorated function - # this is obsolete behavior; you should use decorate instead - return decorate(_func, caller) - # else return a decorator function - if inspect.isclass(caller): - name = caller.__name__.lower() - doc = 'decorator(%s) converts functions/generators into ' \ - 'factories of %s objects' % (caller.__name__, caller.__name__) - elif inspect.isfunction(caller): - if caller.__name__ == '<lambda>': - name = '_lambda_' - else: - name = caller.__name__ - doc = caller.__doc__ - else: # assume caller is an object with a __call__ method - name = caller.__class__.__name__.lower() - doc = caller.__call__.__doc__ - evaldict = dict(_call=caller, _decorate_=decorate) - return FunctionMaker.create( - '%s(func)' % name, 'return _decorate_(func, _call)', - evaldict, doc=doc, module=caller.__module__, - __wrapped__=caller) - - -# ####################### contextmanager ####################### # - -try: # Python >= 3.2 - from contextlib import _GeneratorContextManager -except ImportError: # Python >= 2.5 - from contextlib import GeneratorContextManager as _GeneratorContextManager - - -class ContextManager(_GeneratorContextManager): - def __call__(self, func): - """Context manager decorator""" - return FunctionMaker.create( - func, "with _self_: return _func_(%(shortsignature)s)", - dict(_self_=self, _func_=func), __wrapped__=func) - - -init = getfullargspec(_GeneratorContextManager.__init__) -n_args = len(init.args) -if n_args == 2 and not init.varargs: # (self, genobj) Python 2.7 - def __init__(self, g, *a, **k): - return _GeneratorContextManager.__init__(self, g(*a, **k)) - ContextManager.__init__ = __init__ -elif n_args == 2 and init.varargs: # (self, gen, *a, **k) Python 3.4 - pass -elif n_args == 4: # (self, gen, args, kwds) Python 3.5 - def __init__(self, g, *a, **k): - return _GeneratorContextManager.__init__(self, g, a, k) - ContextManager.__init__ = __init__ - -contextmanager = decorator(ContextManager) - - -# ############################ dispatch_on ############################ # - -def append(a, vancestors): - """ - Append ``a`` to the list of the virtual ancestors, unless it is already - included. - """ - add = True - for j, va in enumerate(vancestors): - if issubclass(va, a): - add = False - break - if issubclass(a, va): - vancestors[j] = a - add = False - if add: - vancestors.append(a) - - -# inspired from simplegeneric by P.J. Eby and functools.singledispatch -def dispatch_on(*dispatch_args): - """ - Factory of decorators turning a function into a generic function - dispatching on the given arguments. - """ - assert dispatch_args, 'No dispatch args passed' - dispatch_str = '(%s,)' % ', '.join(dispatch_args) - - def check(arguments, wrong=operator.ne, msg=''): - """Make sure one passes the expected number of arguments""" - if wrong(len(arguments), len(dispatch_args)): - raise TypeError('Expected %d arguments, got %d%s' % - (len(dispatch_args), len(arguments), msg)) - - def gen_func_dec(func): - """Decorator turning a function into a generic function""" - - # first check the dispatch arguments - argset = set(getfullargspec(func).args) - if not set(dispatch_args) <= argset: - raise NameError('Unknown dispatch arguments %s' % dispatch_str) - - typemap = {} - - def vancestors(*types): - """ - Get a list of sets of virtual ancestors for the given types - """ - check(types) - ras = [[] for _ in range(len(dispatch_args))] - for types_ in typemap: - for t, type_, ra in zip(types, types_, ras): - if issubclass(t, type_) and type_ not in t.mro(): - append(type_, ra) - return [set(ra) for ra in ras] - - def ancestors(*types): - """ - Get a list of virtual MROs, one for each type - """ - check(types) - lists = [] - for t, vas in zip(types, vancestors(*types)): - n_vas = len(vas) - if n_vas > 1: - raise RuntimeError( - 'Ambiguous dispatch for %s: %s' % (t, vas)) - elif n_vas == 1: - va, = vas - mro = type('t', (t, va), {}).mro()[1:] - else: - mro = t.mro() - lists.append(mro[:-1]) # discard t and object - return lists - - def register(*types): - """ - Decorator to register an implementation for the given types - """ - check(types) - - def dec(f): - check(getfullargspec(f).args, operator.lt, ' in ' + f.__name__) - typemap[types] = f - return f - return dec - - def dispatch_info(*types): - """ - An utility to introspect the dispatch algorithm - """ - check(types) - lst = [] - for anc in itertools.product(*ancestors(*types)): - lst.append(tuple(a.__name__ for a in anc)) - return lst - - def _dispatch(dispatch_args, *args, **kw): - types = tuple(type(arg) for arg in dispatch_args) - try: # fast path - f = typemap[types] - except KeyError: - pass - else: - return f(*args, **kw) - combinations = itertools.product(*ancestors(*types)) - next(combinations) # the first one has been already tried - for types_ in combinations: - f = typemap.get(types_) - if f is not None: - return f(*args, **kw) - - # else call the default implementation - return func(*args, **kw) - - return FunctionMaker.create( - func, 'return _f_(%s, %%(shortsignature)s)' % dispatch_str, - dict(_f_=_dispatch), register=register, default=func, - typemap=typemap, vancestors=vancestors, ancestors=ancestors, - dispatch_info=dispatch_info, __wrapped__=func) - - gen_func_dec.__name__ = 'dispatch_on' + dispatch_str - return gen_func_dec diff --git a/vispy/ext/decorator.py b/vispy/ext/decorator.py deleted file mode 100644 --- a/vispy/ext/decorator.py +++ /dev/null @@ -1,12 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) Vispy Development Team. All Rights Reserved. -# Distributed under the (new) BSD License. See LICENSE.txt for more info. - -""" -Handle loading decorator package from system or from the bundled copy -""" - -try: - from ._bundled.decorator import * # noqa -except ImportError: - from decorator import * # noqa diff --git a/vispy/visuals/transforms/_util.py b/vispy/visuals/transforms/_util.py --- a/vispy/visuals/transforms/_util.py +++ b/vispy/visuals/transforms/_util.py @@ -4,8 +4,9 @@ from __future__ import division +import functools + import numpy as np -from ...ext.decorator import decorator from ...util import logger @@ -82,8 +83,7 @@ def as_vec4(obj, default=(0, 0, 0, 1)): return obj -@decorator -def arg_to_vec4(func, self_, arg, *args, **kwargs): +def arg_to_vec4(func): """ Decorator for converting argument to vec4 format suitable for 4x4 matrix multiplication. @@ -105,21 +105,26 @@ def arg_to_vec4(func, self_, arg, *args, **kwargs): and returns a new (mapped) object. """ - if isinstance(arg, (tuple, list, np.ndarray)): - arg = np.array(arg) - flatten = arg.ndim == 1 - arg = as_vec4(arg) - - ret = func(self_, arg, *args, **kwargs) - if flatten and ret is not None: - return ret.flatten() - return ret - elif hasattr(arg, '_transform_in'): - arr = arg._transform_in() - ret = func(self_, arr, *args, **kwargs) - return arg._transform_out(ret) - else: - raise TypeError("Cannot convert argument to 4D vector: %s" % arg) + + @functools.wraps(func) + def wrapper(self_, arg, *args, **kwargs): + if isinstance(arg, (tuple, list, np.ndarray)): + arg = np.array(arg) + flatten = arg.ndim == 1 + arg = as_vec4(arg) + + ret = func(self_, arg, *args, **kwargs) + if flatten and ret is not None: + return ret.flatten() + return ret + elif hasattr(arg, '_transform_in'): + arr = arg._transform_in() + ret = func(self_, arr, *args, **kwargs) + return arg._transform_out(ret) + else: + raise TypeError("Cannot convert argument to 4D vector: %s" % arg) + + return wrapper class TransformCache(object):
Replace bundled "decorator" dependency We currently have a dependency on the "decorator" library, but include it as a bundled module here: `vispy/ext/_bundled/decorator.py` and then import it here: `vispy/ext/decorator.py` where the `decorator` decorator is only used once here: https://github.com/vispy/vispy/blob/397c3122d5644692e6e1ae6d281b7b72d741fae6/vispy/visuals/transforms/_util.py#L85-L86 I think this dependency could be removed if `arg_to_vec4` was rewritten to use https://docs.python.org/3/library/functools.html#functools.wraps or a similar standard library utility. @larsoner you probably know the most about this, any concerns? Otherwise I say we let a hacktoberfest participant handle this.
I can't remember why we went with `decorator` for this one. I'd say get rid of it, hopefully `functools.wraps` is enough nowadays. Hi, I am interested in this one. Thanks @sgaist. You have been assigned to this issue. Let me know if you change your mind. I'll try to check in later to check on your status (after we are in October for a bit).
2020-09-30T22:19:11
vispy/vispy
1,943
vispy__vispy-1943
[ "1923" ]
b416613084ef3e93ce8850b04c1587330d41a467
diff --git a/vispy/ext/gzip_open.py b/vispy/ext/gzip_open.py deleted file mode 100644 --- a/vispy/ext/gzip_open.py +++ /dev/null @@ -1,19 +0,0 @@ -# -*- coding: utf-8 -*- -# Copyright (c) Vispy Development Team. All Rights Reserved. -# Distributed under the (new) BSD License. See LICENSE.txt for more info. -from gzip import GzipFile - - -# Python < 2.7 doesn't have context handling -class gzip_open(GzipFile): - def __enter__(self): - if hasattr(GzipFile, '__enter__'): - return GzipFile.__enter__(self) - else: - return self - - def __exit__(self, exc_type, exc_value, traceback): - if hasattr(GzipFile, '__exit__'): - return GzipFile.__exit__(self, exc_type, exc_value, traceback) - else: - return self.close() diff --git a/vispy/io/wavefront.py b/vispy/io/wavefront.py --- a/vispy/io/wavefront.py +++ b/vispy/io/wavefront.py @@ -20,9 +20,9 @@ import numpy as np import time +from gzip import GzipFile from os import path as op -from ..ext.gzip_open import gzip_open from ..geometry import _calculate_normals from ..util import logger @@ -67,7 +67,7 @@ def read(cls, fname): # Open file fmt = op.splitext(fname)[1].lower() assert fmt in ('.obj', '.gz') - opener = open if fmt == '.obj' else gzip_open + opener = open if fmt == '.obj' else GzipFile with opener(fname, 'rb') as f: try: reader = WavefrontReader(f) @@ -251,7 +251,7 @@ def write(cls, fname, vertices, faces, normals, if fmt not in ('.obj', '.gz'): raise ValueError('Filename must end with .obj or .gz, not "%s"' % (fmt,)) - opener = open if fmt == '.obj' else gzip_open + opener = open if fmt == '.obj' else GzipFile f = opener(fname, 'wb') try: writer = WavefrontWriter(f)
Remove Python 2.7 wrapper around GzipFile This module: https://github.com/vispy/vispy/blob/9dbe751dcdbaaa1d17d0a5885f15872b9b0741a8/vispy/ext/gzip_open.py Is used in two places in vispy (one module) and only exists to be used by Python 2.7 environments which we no longer support. This module and it's usages should be replaced by `GzipFile`: https://docs.python.org/3/library/gzip.html#gzip.GzipFile Usage 1: https://github.com/vispy/vispy/blob/9dbe751dcdbaaa1d17d0a5885f15872b9b0741a8/vispy/io/wavefront.py#L70 Usage 2: https://github.com/vispy/vispy/blob/9dbe751dcdbaaa1d17d0a5885f15872b9b0741a8/vispy/io/wavefront.py#L254 And of course the import in that module should be removed.
Hello, I would like to contribute, may I be assigned to this issue? Done. Thanks. Hey, I would like to work on this too. If it is possible may I be assigned? Thank you. @Kartik-byte Only if @jyoungiv has decided not to do it. @jyoungiv do you plan on working on this still? Okay sure, I just saw that in my last PR ,by mistake, I took a issue that someone else was assigned to . I felt bad. Not gonna do that this time. Still trying to learn github. Sorry.
2020-10-25T17:41:02
vispy/vispy
1,968
vispy__vispy-1968
[ "1964" ]
7f3f6f60c8462bb8a3a8fa03344a2e6990b86eb2
diff --git a/vispy/app/backends/_qt.py b/vispy/app/backends/_qt.py --- a/vispy/app/backends/_qt.py +++ b/vispy/app/backends/_qt.py @@ -517,13 +517,16 @@ def event(self, ev): scale = gesture.scaleFactor() last_scale = gesture.lastScaleFactor() rotation = gesture.rotationAngle() - self._vispy_canvas.events.touch(type='pinch', - pos=(x, y), - last_pos=None, - scale=scale, - last_scale=last_scale, - rotation=rotation, - ) + self._vispy_canvas.events.touch( + type="pinch", + pos=(x, y), + last_pos=None, + scale=scale, + last_scale=last_scale, + rotation=rotation, + total_rotation_angle=gesture.totalRotationAngle(), + total_scale_factor=gesture.totalScaleFactor(), + ) # General touch event. elif (t == QtCore.QEvent.TouchUpdate): points = ev.touchPoints()
Expose totalRotationAngle and totalScaleFactor in touch event ? In [here](https://github.com/vispy/vispy/blob/7f3f6f60c8462bb8a3a8fa03344a2e6990b86eb2/vispy/app/backends/_qt.py#L509-L536), would it be ok to also expose the two above attributes; as well as maybe a reference to the native event (weak ref if you are concerned). `total*` contain the value since the begin touch event; we cna of course accumulating the current delta when pinching/rotating but this accumulate error; and can be error prone as you also have to catch the begin and end events as well. There might be reasons not to do that (have the same event struct across backend?) but I haven't found other code triggering `.touch()` events. And in that case I thin that a private fields `_native` that contain the raw even could be sufficient. Note that there is also totalChangeFlags I believe; but I do not have any thoughts on this one, though I guess it makes sens. Thanks.
I'm open to adding any extra properties that might make sense. I'm a little confused by the code though as I don't see a TouchEvent class anywhere in vispy except for a mention in a comment. Does this existing event handling work at all? Yes it does; they do register as simply `Event` though, and `self.canvas.connect(self.on_touch)` works. (took me 2h yesterday to figure that out, but I figured it !) There might be a short "MouseWheel" event sometime just before the touch even as two finger on touchpad is used for both on mac. My guess is there is not a lot of user of this (as mostly it work on mac touchpad), and the original author was not sure about the final structure of a potential "TouchEvent" so left it as is. I also tried to subclass `Canvas` and overwrite `def event(self, ev):` but that did not work I'm not sure why... If you can make a pull request for the additional properties on the Event, I'm ok with that. I'm a little hesitant on the `_native` idea, but if you **really** need it then I can be convinced. I don't think I _really_ need `_native`; I just saw it on MouseWheel; so though it was an escape hatch that was put there on purpose. Thanks, I'll likely make a PR, but probably not this week.
2020-12-21T18:14:47
vispy/vispy
1,975
vispy__vispy-1975
[ "1885" ]
8130a2229fcdf5e6a5f47190207d3fc948747d3a
diff --git a/vispy/ext/cocoapy.py b/vispy/ext/cocoapy.py --- a/vispy/ext/cocoapy.py +++ b/vispy/ext/cocoapy.py @@ -17,6 +17,27 @@ else: string_types = basestring, # noqa + +# handle dlopen cache changes in macOS 11 (Big Sur) +# ref https://stackoverflow.com/questions/63475461/unable-to-import-opengl-gl-in-python-on-macos +try: + import OpenGL.GL # noqa +except ImportError: + # print('Drat, patching for Big Sur') + orig_util_find_library = util.find_library + + def new_util_find_library(name): + res = orig_util_find_library(name) + if res: + return res + lut = { + 'objc': 'libobjc.dylib', + 'quartz': 'Quartz.framework/Quartz' + } + return lut.get(name, name+'.framework/'+name) + util.find_library = new_util_find_library + + # Based on Pyglet code ##############################################################################
Unable to import on macOS Big Sur From https://github.com/vispy/vispy/issues/1484#issuecomment-651875603: > [`vispy/ext/cocoapy.py`](https://github.com/vispy/vispy/blob/master/vispy/ext/cocoapy.py) calls `cdll.LoadLibrary(util.find_library('...'))` a bunch of times, but ctypes can't find these libraries on Big Sur. On Catalina, `util.find_library('objc')` returns `/usr/lib/libobjc.dylib` and on Big Sur, `util.find_library('objc')` returns `None`. These are all the libraries loaded in `cocoapy.py`: > - objc > - CoreFoundation > - AppKit > - quartz > - CoreText > - Foundation > > https://docs.python.org/3/library/ctypes.html#finding-shared-libraries > https://docs.python.org/3/library/ctypes.html#ctypes.LibraryLoader.LoadLibrary ## Reproduction 1. `python3 -m pip install vispy` 2. `python3 -c "import vispy"`; the output is: ``` Traceback (most recent call last): File "<string>", line 1, in <module> File "/private/tmp/venv/lib/python3.8/site-packages/vispy/__init__.py", line 30, in <module> from .util import config, set_log_level, keys, sys_info # noqa File "/private/tmp/venv/lib/python3.8/site-packages/vispy/util/__init__.py", line 14, in <module> from . import fonts # noqa File "/private/tmp/venv/lib/python3.8/site-packages/vispy/util/fonts/__init__.py", line 13, in <module> from ._triage import _load_glyph, list_fonts # noqa, analysis:ignore File "/private/tmp/venv/lib/python3.8/site-packages/vispy/util/fonts/_triage.py", line 14, in <module> from ._quartz import _load_glyph, _list_fonts File "/private/tmp/venv/lib/python3.8/site-packages/vispy/util/fonts/_quartz.py", line 12, in <module> from ...ext.cocoapy import cf, ct, quartz, CFRange, CFSTR, CGGlyph, UniChar, \ File "/private/tmp/venv/lib/python3.8/site-packages/vispy/ext/cocoapy.py", line 1126, in <module> NSEventTrackingRunLoopMode = c_void_p.in_dll( ValueError: dlsym(RTLD_DEFAULT, NSEventTrackingRunLoopMode): symbol not found ``` See https://github.com/napari/napari/issues/1393 and https://github.com/vispy/vispy/issues/1484.
According to https://developer.apple.com/documentation/macos-release-notes/macos-big-sur-11-beta-release-notes: > New in macOS Big Sur 11 beta, the system ships with a built-in dynamic linker cache of all system-provided libraries. As part of this change, copies of dynamic libraries are no longer present on the filesystem. Code that attempts to check for dynamic library presence by looking for a file at a path or enumerating a directory will fail. Instead, check for library presence by attempting to `dlopen()` the path, which will correctly check for the library in the cache. (62986286) Others have encountered this problem: - https://bugs.python.org/issue41116 (this is a build issue, but is related I think) - https://stackoverflow.com/questions/62587131/macos-big-sur-python-ctypes-find-library-does-not-find-libraries-ssl-corefou - https://www.reddit.com/r/MacOSBeta/comments/hfknpa/is_corefoundation_missing_for_everyone_on_big_sur/ - https://github.com/espressif/esptool/issues/540 --- It should be possible to patch [the relevant code](https://github.com/python/cpython/blob/1648c99932f39f1c60972bb114e6a7bd65523818/Lib/ctypes/util.py#L70-L81) in Python itself. Pros: - vispy and other libraries won't need to change anything Cons: - changes will only be reflected in the next Python version Wow nice job tracking this down. I assume this is big enough that a patch in python might be created and released as a bug release. So then we might get something working in a 3.7.x and 3.8.x release. I guess we'll keep this open for a couple more months and see what has happened by then. If you have any other updates on progress on this feel free to post it here. https://github.com/python/cpython/blob/master/Misc/NEWS.d/next/macOS/2020-06-24-13-51-57.bpo-41100.mcHdc5.rst says: > Big Sur is expected to be fully supported in a future bugfix release of Python 3.8.x and with 3.9.0. So I'm not sure if Big Sur fixes will be pushed to 3.7 :// Any ideas @sumanthratna if this has been fixed in newer versions of python? I just released vispy 0.6.5 which includes a Python 3.8 wheel so I'm hoping this works now. Hi @djhoese! This hasn't been fixed yet; here are the PRs: https://github.com/python/cpython/pull/21249, https://github.com/python/cpython/pull/21576, https://github.com/python/cpython/pull/21577, https://github.com/python/cpython/pull/21241, https://github.com/python/cpython/pull/21242, https://github.com/python/cpython/pull/21239 I pulled vispy 0.6.5 anyway and the `ValueError: dlsym(RTLD_DEFAULT, NSEventTrackingRunLoopMode): symbol not found` error still occurs While waiting for a fix you can replace https://github.com/vispy/vispy/blob/7f3f6f60c8462bb8a3a8fa03344a2e6990b86eb2/vispy/ext/cocoapy.py#L1123 with ```python appkit = cdll.LoadLibrary('/System/Library/Frameworks/AppKit.framework/Versions/Current/AppKit') ``` By the way, looks like the upstream cpython patch worked, and python 3.9.1_1 doesn't have this error (I can successfully install and import vispy on Big Sur). I don't think this has been resolved in Python 3.8 (the patch is being backported right now) so I'm leaving this issue open until 3.8 is fixed. @djhoese if you feel like Python 3.8 + Big Sur support is urgent for vispy, you could check the OS and python version and hard-code the paths to libraries (although I would probably just wait until the backport is finished) For the record, here's the output of `ctypes.util.find_library` on Python 3.9 and Big Sur: - `ctypes.util.find_library('AppKit')` -> `/System/Library/Frameworks/AppKit.framework/AppKit` - `ctypes.util.find_library('objc')` -> `/usr/lib/libobjc.dylib` @sumanthratna Thanks for all the info and @0x0L for the the example. Given the limited time I have right now and the small-ish user group that this effects, I think I'll wait for the Python 3.8 backport unless a large group of users requires it. I think hacking your own installation of vispy with the above paths is the simplest solution right now that doesn't require a short lived builtin workaround in vispy. If people disagree with this and think a workaround should be added to vispy and it is urgent then let me know and make a pull request with the fix. I'm ok leaving this open until the 3.8 backport is available. @sumanthratna If you are keeping up to date on this, please update this issue when the backport is available. Otherwise, thanks for your help so far. @djhoese Actually BigSur default /usr/bin/python3 looks ok. The easiest way may be to just copy over `/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.8/lib/python3.8/ctypes/macholib/dyld.py` into your python ctypes I'm running into this issue with the latest python 3.9.1 build from conda-forge (h1d169a7_2_cpython) - anyone know why that might be? I'm running into this issue with the latest python 3.9.1 build also `python 3.9.1 h1d169a7_3_cpython conda-forge` If someone can track down why the above mention patch on CPython isn't showing up in the version distributed by conda-forge it would be very much appreciated (download the source that conda-forge is building and find the exact patch for this)? If this isn't actually fixed then I guess we can add a workaround, but obviously it is unfortunate that we have to do it. Hi @djhoese I tried the patch to no avail :-(, it also looks like it does contain the patch. ```python elif os.name == "posix" and sys.platform == "darwin": from ctypes.macholib.dyld import dyld_find as _dyld_find def find_library(name): possible = ['@executable_path/../lib/lib%s.dylib' % name, 'lib%s.dylib' % name, '%s.dylib' % name, '%s.framework/%s' % (name, name)] for name in possible: try: return _dyld_find(name) except ValueError: continue return None ``` @goanpeca So with your above patch to the vispy source code you still see an issue? Are you seeing the exact same error as the original post? @sumanthratna Is it possible when you got this working you were using a patched version of vispy? @goanpeca What do you get on your system when you run the `find_library` calls that @sumanthratna mentioned in this comment: https://github.com/vispy/vispy/issues/1885#issuecomment-749164594 ``` ctypes.util.find_library('AppKit') -> /System/Library/Frameworks/AppKit.framework/AppKit ctypes.util.find_library('objc') -> /usr/lib/libobjc.dylib ``` Hi @djhoese, running `import vispy` yields: (I am actually trying to run `napari`) ```python Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/goanpeca/miniconda3/envs/napari/lib/python3.9/site-packages/vispy/__init__.py", line 30, in <module> from .util import config, set_log_level, keys, sys_info # noqa File "/Users/goanpeca/miniconda3/envs/napari/lib/python3.9/site-packages/vispy/util/__init__.py", line 14, in <module> from . import fonts # noqa File "/Users/goanpeca/miniconda3/envs/napari/lib/python3.9/site-packages/vispy/util/fonts/__init__.py", line 13, in <module> from ._triage import _load_glyph, list_fonts # noqa, analysis:ignore File "/Users/goanpeca/miniconda3/envs/napari/lib/python3.9/site-packages/vispy/util/fonts/_triage.py", line 14, in <module> from ._quartz import _load_glyph, _list_fonts File "/Users/goanpeca/miniconda3/envs/napari/lib/python3.9/site-packages/vispy/util/fonts/_quartz.py", line 12, in <module> from ...ext.cocoapy import cf, ct, quartz, CFRange, CFSTR, CGGlyph, UniChar, \ File "/Users/goanpeca/miniconda3/envs/napari/lib/python3.9/site-packages/vispy/ext/cocoapy.py", line 1126, in <module> NSEventTrackingRunLoopMode = c_void_p.in_dll( ValueError: dlsym(RTLD_DEFAULT, NSEventTrackingRunLoopMode): symbol not found ``` @djhoese they both return `None`, if I manually do this patch, it does work, so it seems the patch needs patching ? `appkit = cdll.LoadLibrary('/System/Library/Frameworks/AppKit.framework/Versions/Current/AppKit')` > @sumanthratna Is it possible when you got this working you were using a patched version of vispy? I just retried on a fresh install (new venv) of vispy and it works the same as before (fails on 3.8.7, works on 3.9.1). I am using conda and conda-forge 🙃 ... @sumanthratna Where/how did you install Python 3.9? If not using conda with conda-forge, would you mind checking it? > @sumanthratna Where/how did you install Python 3.9? If not using conda with conda-forge, would you mind checking it? I use homebrew, here's the output of `brew info [email protected]`: ``` [email protected]: stable 3.9.1 (bottled) Interpreted, interactive, object-oriented programming language https://www.python.org/ /usr/local/Cellar/[email protected]/3.9.1_6 (8,665 files, 129.0MB) * Built from source on 2021-01-10 at 20:57:51 ``` I don't use conda (and I don't have conda installed on my system) by the way, this seems to be an issue with conda-forge: https://github.com/conda-forge/python-feedstock/issues/436 I'm too busy to look into this deeply right now, but if I ever find anything interesting I'll update this thread. Let me know if you need any debugging output from me! I was able to at least `import vispy` under current-as-of-today conda-forge python 3.8.6 and 3.9.1 with this quick patch pieced together from above recommendations and observations, on macOS 11.1: ```patch diff --git a/vispy/ext/cocoapy.py b/vispy/ext/cocoapy.py index d510d1ae..600d1870 100644 --- a/vispy/ext/cocoapy.py +++ b/vispy/ext/cocoapy.py @@ -106,7 +106,7 @@ if sizeof(c_void_p) == 4: elif sizeof(c_void_p) == 8: c_ptrdiff_t = c_int64 -objc = cdll.LoadLibrary(util.find_library('objc')) +objc = cdll.LoadLibrary(util.find_library('objc') or 'libobjc.dylib') objc.class_addIvar.restype = c_bool objc.class_addIvar.argtypes = [c_void_p, c_char_p, c_size_t, c_uint8, c_char_p] @@ -920,7 +920,7 @@ class ObjCSubclass(object): ############################################################################## # cocoalibs.py -cf = cdll.LoadLibrary(util.find_library('CoreFoundation')) +cf = cdll.LoadLibrary(util.find_library('CoreFoundation') or 'CoreFoundation.framework/CoreFoundation') kCFStringEncodingUTF8 = 0x08000100 @@ -1120,7 +1120,7 @@ cf.CFShow.argtypes = [c_void_p] # Even though we don't use this directly, it must be loaded so that # we can find the NSApplication, NSWindow, and NSView classes. -appkit = cdll.LoadLibrary(util.find_library('AppKit')) +appkit = cdll.LoadLibrary(util.find_library('AppKit') or 'AppKit.framework/AppKit') NSDefaultRunLoopMode = c_void_p.in_dll(appkit, 'NSDefaultRunLoopMode') NSEventTrackingRunLoopMode = c_void_p.in_dll( @@ -1261,7 +1261,7 @@ NSApplicationActivationPolicyProhibited = 2 # QUARTZ / COREGRAPHICS -quartz = cdll.LoadLibrary(util.find_library('quartz')) +quartz = cdll.LoadLibrary(util.find_library('quartz') or 'Quartz.framework/Quartz') CGDirectDisplayID = c_uint32 # CGDirectDisplay.h CGError = c_int32 # CGError.h @@ -1431,7 +1431,7 @@ quartz.CGDisplayBounds.restype = CGRect ###################################################################### # CORETEXT -ct = cdll.LoadLibrary(util.find_library('CoreText')) +ct = cdll.LoadLibrary(util.find_library('CoreText') or 'CoreText.framework/CoreText') # Types CTFontOrientation = c_uint32 # CTFontDescriptor.h ``` @k30n1 So theoretically, from what I understand of that code, that should be backwards compatible? @goanpeca Do you think you could try the above changes in vispy and see if it fixes your issue? @astrofrog Does this work for you? Or (based on your other issue on conda-forge) do you see any issues with these patches? @k30n1 Any chance I can get you to make a PR for this?
2021-01-20T16:33:01
vispy/vispy
2,002
vispy__vispy-2002
[ "2001" ]
04d050564b91161b1f8d4949e61c1df3b44af90d
diff --git a/vispy/geometry/meshdata.py b/vispy/geometry/meshdata.py --- a/vispy/geometry/meshdata.py +++ b/vispy/geometry/meshdata.py @@ -411,7 +411,7 @@ def set_vertex_colors(self, colors, indexed=None): indexed : str | None Should be 'faces' if colors are indexed by faces. """ - colors = _fix_colors(np.asarray(colors)) + colors = _fix_colors(colors) if indexed is None: if colors.ndim != 2: raise ValueError('colors must be 2D if indexed is None') diff --git a/vispy/visuals/surface_plot.py b/vispy/visuals/surface_plot.py --- a/vispy/visuals/surface_plot.py +++ b/vispy/visuals/surface_plot.py @@ -54,36 +54,19 @@ def __init__(self, x=None, y=None, z=None, colors=None, **kwargs): MeshVisual.__init__(self, **kwargs) self.set_data(x, y, z, colors) - def set_data(self, x=None, y=None, z=None, colors=None): - """Update the data in this surface plot. - - Parameters - ---------- - x : ndarray | None - 1D/2D array of values specifying the x positions of vertices in - the grid. In case 1D array given as input, the values will be - replicated to fill the 2D array of size(z). If None, values will be - assumed to be integers. - y : ndarray | None - 1D/2D array of values specifying the x positions of vertices in - the grid. In case 1D array given as input, the values will be - replicated to fill the 2D array of size(z). If None, values will be - assumed to be integers. - z : ndarray - 2D array of height values for each grid vertex. - colors : ndarray - (width, height, 4) array of vertex colors. - """ + def _update_x_data(self, x): if x is not None: if self._x is None or len(x) != len(self._x): self.__vertices = None self._x = x + def _update_y_data(self, y): if y is not None: if self._y is None or len(y) != len(self._y): self.__vertices = None self._y = y + def _update_z_data(self, z): if z is not None: if self._x is not None and z.shape[0] != len(self._x): raise TypeError('Z values must have shape (len(x), len(y))') @@ -94,64 +77,106 @@ def set_data(self, x=None, y=None, z=None, colors=None): self._z.shape != self.__vertices.shape[:2]): self.__vertices = None - if self._z is None: - return - - update_mesh = False + def _update_mesh_vertices(self, x_is_new, y_is_new, z_is_new): new_vertices = False + update_vertices = False + update_faces = False # Generate vertex and face array if self.__vertices is None: - new_vertices = True self.__vertices = np.empty((self._z.shape[0], self._z.shape[1], 3), dtype=np.float32) - self.generate_faces() - self.__meshdata.set_faces(self.__faces) - update_mesh = True + self.__faces = self._generate_faces() + new_vertices = True + update_faces = True # Copy x, y, z data into vertex array - if new_vertices or x is not None: - if x is None: - if self._x is None: - x = np.arange(self._z.shape[0]) - else: - x = self._x + if new_vertices or x_is_new: + if not x_is_new and self._x is None: + x = np.arange(self._z.shape[0]) + else: + x = self._x if x.ndim == 1: x = x.reshape(len(x), 1) # Copy the 2D data into the appropriate slice self.__vertices[:, :, 0] = x - update_mesh = True - - if new_vertices or y is not None: - if y is None: - if self._y is None: - y = np.arange(self._z.shape[1]) - else: - y = self._y + update_vertices = True + if new_vertices or y_is_new: + if not y_is_new and self._y is None: + y = np.arange(self._z.shape[1]) + else: + y = self._y if y.ndim == 1: y = y.reshape(1, len(y)) - # Copy the 2D data into the appropriate slice self.__vertices[:, :, 1] = y - update_mesh = True + update_vertices = True - if new_vertices or z is not None: + if new_vertices or z_is_new: self.__vertices[..., 2] = self._z - update_mesh = True + update_vertices = True + return update_faces, update_vertices - if colors is not None: - self.__meshdata.set_vertex_colors(colors) - update_mesh = True + def _prepare_mesh_colors(self, colors): + if colors is None: + return + colors = np.asarray(colors) + if colors.ndim == 3: + # convert (width, height, 4) to (num_verts, 4) + vert_shape = self.__vertices.shape + num_vertices = vert_shape[0] * vert_shape[1] + colors = colors.reshape(num_vertices, 3) + return colors + + def set_data(self, x=None, y=None, z=None, colors=None): + """Update the data in this surface plot. + + Parameters + ---------- + x : ndarray | None + 1D/2D array of values specifying the x positions of vertices in + the grid. In case 1D array given as input, the values will be + replicated to fill the 2D array of size(z). If None, values will be + assumed to be integers. + y : ndarray | None + 1D/2D array of values specifying the x positions of vertices in + the grid. In case 1D array given as input, the values will be + replicated to fill the 2D array of size(z). If None, values will be + assumed to be integers. + z : ndarray + 2D array of height values for each grid vertex. + colors : ndarray + (width, height, 4) array of vertex colors. + """ + self._update_x_data(x) + self._update_y_data(y) + self._update_z_data(z) + + if self._z is None: + # no mesh data to plot so no need to update + return - # Update MeshData - if update_mesh: + update_faces, update_vertices = self._update_mesh_vertices( + x is not None, + y is not None, + z is not None + ) + + colors = self._prepare_mesh_colors(colors) + update_colors = colors is not None + if update_colors: + self.__meshdata.set_vertex_colors(colors) + if update_faces: + self.__meshdata.set_faces(self.__faces) + if update_vertices: self.__meshdata.set_vertices( self.__vertices.reshape(self.__vertices.shape[0] * self.__vertices.shape[1], 3)) + if update_faces or update_vertices or update_colors: MeshVisual.set_data(self, meshdata=self.__meshdata) - def generate_faces(self): + def _generate_faces(self): cols = self._z.shape[1] - 1 rows = self._z.shape[0] - 1 faces = np.empty((cols * rows * 2, 3), dtype=np.uint) @@ -164,4 +189,4 @@ def generate_faces(self): faces[start:start + cols] = rowtemplate1 + row * (cols + 1) faces[start + cols:start + (cols * 2)] =\ rowtemplate2 + row * (cols + 1) - self.__faces = faces + return faces
SurfacePlot color change slower with set_data versus mesh_data.set_vertex_colors Sample code below: a SurfacePlot whose color is updated when "O" is pressed using `mesh_data.set_vertex_colors`. Problem: the `mesh_data.set_vertex_colors` works if called before adding the surface to the view, but not in later calls. Temporary fix (thanks @djhoese ): add `surf.mesh_data_changed()` after changing the color. PS: using `surf.set_data(colors=c)` instead of `surf.mesh_data.set_vertex_colors(c); surf.mesh_data_changed()` also works, but for some reason is much slower ``` import vispy, vispy.scene import numpy as np shape = (200, 200) Z = np.random.random(shape)*5 B = np.random.random(shape) ## canvas = vispy.scene.SceneCanvas(keys='interactive', show=True) view = canvas.central_widget.add_view() surf = vispy.scene.visuals.SurfacePlot(z=Z, color=(1, 1, 1, 1)) # Add color def setColor(C): C = np.array(C) c = vispy.color.get_colormap("hsl").map(C/np.max(C)).reshape(C.shape + (-1,)) c = c.flatten().tolist() c=list(map(lambda x,y,z,w:(x,y,z,w), c[0::4],c[1::4],c[2::4],c[3::4])) surf.mesh_data.set_vertex_colors(c) setColor(B) # cycle colors on key press col_cycle_i = 0 def cycle_colors(event): key = event.key.name if key != "O": return global col_cycle_i col_cycle_i = (col_cycle_i+1)%2 print('Setting new coli', col_cycle_i) if col_cycle_i == 0: setColor(B) elif col_cycle_i == 1: setColor(Z) canvas.events.key_press.connect(cycle_colors) view.add(surf) axis = vispy.scene.visuals.XYZAxis(parent=view.scene) view.camera = 'fly' ```
Thanks for this. As mentioned on gitter, the `set_data(colors=c)` works but is much slower than touching the mesh_data directly. This is probably because the surface plot is recreating/re-setting the data for the mesh every time it is run. We should be able to optimize that away if we detect that only a color change is needed.
2021-03-01T16:16:20
vispy/vispy
2,040
vispy__vispy-2040
[ "1889" ]
081a1216e336e8c2c9aa4c61b926ba771bb5479f
diff --git a/vispy/app/backends/_qt.py b/vispy/app/backends/_qt.py --- a/vispy/app/backends/_qt.py +++ b/vispy/app/backends/_qt.py @@ -845,6 +845,16 @@ def paintGL(self): self._vispy_canvas.set_current() self._vispy_canvas.events.draw(region=None) + # Clear the alpha channel with QOpenGLWidget (Qt >= 5.4), otherwise the + # window is translucent behind non-opaque objects. + # Reference: MRtrix3/mrtrix3#266 + if QT5_NEW_API or QT6_NEW_API: + context = self._vispy_canvas.context + context.set_color_mask(False, False, False, True) + context.clear(color=True, depth=False, stencil=False) + context.set_color_mask(True, True, True, True) + context.flush() + # Select CanvasBackend if USE_EGL:
diff --git a/vispy/gloo/tests/test_glir.py b/vispy/gloo/tests/test_glir.py --- a/vispy/gloo/tests/test_glir.py +++ b/vispy/gloo/tests/test_glir.py @@ -25,16 +25,16 @@ def test_queue(): assert cmds[i] == ('FOO', 'BAR', i) # Test filter 1 - cmds1 = [('DATA', 1), ('SIZE', 1), ('FOO', 1), ('SIZE', 1), ('FOO', 1), + cmds1 = [('DATA', 1), ('SIZE', 1), ('FOO', 1), ('SIZE', 1), ('FOO', 1), ('DATA', 1), ('DATA', 1)] cmds2 = [c[0] for c in q._shared._filter(cmds1, parser)] assert cmds2 == ['FOO', 'SIZE', 'FOO', 'DATA', 'DATA'] # Test filter 2 - cmds1 = [('DATA', 1), ('SIZE', 1), ('FOO', 1), ('SIZE', 2), ('SIZE', 2), + cmds1 = [('DATA', 1), ('SIZE', 1), ('FOO', 1), ('SIZE', 2), ('SIZE', 2), ('DATA', 2), ('SIZE', 1), ('FOO', 1), ('DATA', 1), ('DATA', 1)] cmds2 = q._shared._filter(cmds1, parser) - assert cmds2 == [('FOO', 1), ('SIZE', 2), ('DATA', 2), ('SIZE', 1), + assert cmds2 == [('FOO', 1), ('SIZE', 2), ('DATA', 2), ('SIZE', 1), ('FOO', 1), ('DATA', 1), ('DATA', 1)] # Define shader @@ -94,11 +94,14 @@ def test_log_parser(): assert lines[i].startswith(expected[0]) assert lines[i].endswith(expected[1]) assert int(lines[i][len(expected[0]):-len(expected[1])]) is not None - i += 1 # The 'CURRENT' command may have been called multiple times - while lines[i] == lines[i - 1]: + while lines[i].startswith('["CURRENT",'): i += 1 + if lines[i] == json.dumps(['FUNC', 'colorMask', False, False, False, True]): + # Qt workaround, see #2040 + i += 4 + assert lines[i] == json.dumps(['FUNC', 'clearColor', 1.0, 1.0, 1.0, 1.0]) i += 1 assert lines[i] == json.dumps(['FUNC', 'clear', 17664])
Transparency issue resurfaced for PyQt5 on OSX A colleague noticed that our PyQt5 application that uses VisPy is showing a transparency issue that we used to see with the old version of vispy's pyqt5 backend but only on OSX (and maybe Windows). The issue is whenever you have something semi-transparent in the canvas on OSX it shows *through* the window allowing you to see the windows behind. Here is a minimal example: ``` from vispy.app import use_app from vispy.scene import SceneCanvas from vispy.scene.visuals import Polygon canvas = SceneCanvas() v = canvas.central_widget.add_view() v.bgcolor = 'gray' v.camera = 'panzoom' cx, cy = (0.5, 0.5) halfx, halfy = (0.1, 0.1) poly_coords = [(cx - halfx, cy - halfy), (cx + halfx, cy - halfy), (cx + halfx, cy + halfy), (cx - halfx, cy + halfy)] poly = Polygon(poly_coords, color=(1.0, 0.0, 0.0, 0.5), border_color=(1.0, 1.0, 1.0, 0.2), border_width=3, parent=v.scene) app = use_app('pyqt5') canvas.show() app.run() ``` Which produces something like: ![image (1)](https://user-images.githubusercontent.com/1828519/86391292-2f516580-bc5f-11ea-9680-f22a610d528c.png) Googling around shows that this should be related to the alpha buffer configured here: https://github.com/vispy/vispy/blob/77f016a0c6121e1b0c024bdf4e03d5bf84aa9879/vispy/app/backends/_qt.py#L233 However, setting this to -1 (default `alpha_size` is 8) or commenting out this line still produce the same results on OSX. I've had a coworker (CC @rayg-ssec) test this to confirm. On my Ubuntu laptop I don't see this issue at all. I'm wondering if any of the napari folks and other contributors have seen something like this (CC @tlambert03 @kmuehlbauer @larsoner @sofroniewn @kne42)?
I havn't seen that in napari, but I am able to reproduce the error using your standalone script on my mac, so it's definitely very repeatable. I'd need to look in a little deeper to see why we havn't seen in napari as I know we have shown mesh objects with alpha transparency. @djhoese I can't reproduce this on my kubuntu. I can check on OpenSuse after the weekend, but I can't remember having issues with that on OpenSuse. @kmuehlbauer I don't think testing on various unix-ish environments is needed. The main culprit is OSX with Windows being another possibility. > I havn't seen that in napari @sofroniewn That's why I wanted to check with the napari folks. I figured you have the most examples of these different visualizations. Is it possible that this is a PyQt-specific issue and you usually use PySide2? Or maybe this has only been introduced in a semi-recent version of Qt/PyQt? @sofroniewn Any update on if you've seen this issue in napari? I havn't been able to create a napari example yet and no one has reported the issue, but I can confirm that the issue is PyQt5 specific. When I run your vispy example script above with PyQt5 I get the error, when I run it with PySide2 I don't get the error, both on my mac. I imagine I could make a napari specific example with PyQt5 that would show the same problem. @sofroniewn Can you double check the pyside versus pyqt5 behavior? I just had one of my coworkers try it on their mac and they still see transparency with pyside2: ``` Platform: Darwin-19.6.0-x86_64-i386-64bit Python: 3.7.8 | packaged by conda-forge | (default, Jul 31 2020, 02:37:09) [Clang 10.0.1 ] NumPy: 1.19.1 Backend: PySide2 pyqt4: None pyqt5: None pyside: None pyside2: ('PySide2', '5.13.2', '5.12.5') ``` NOTE: @sofroniewn you should double check the conda build of your pyside2 installation; specifically `qt`. I'm curious if this is related to a specific version of Qt and your installation of Pyside2 was using an older one. > @sofroniewn Can you double check the pyside versus pyqt5 behavior? I just had one of my coworkers try it on their mac and they still see transparency with pyside2: I'll try and take a look tonight
2021-05-28T11:00:16
vispy/vispy
2,042
vispy__vispy-2042
[ "2041" ]
081a1216e336e8c2c9aa4c61b926ba771bb5479f
diff --git a/vispy/visuals/filters/mesh.py b/vispy/visuals/filters/mesh.py --- a/vispy/visuals/filters/mesh.py +++ b/vispy/visuals/filters/mesh.py @@ -332,6 +332,9 @@ def _attach(self, visual): self.vshader['scene2doc'] = scene2doc self.vshader['doc2scene'] = doc2scene + if self._visual.mesh_data is not None: + self._update_data() + visual.events.data_updated.connect(self.on_mesh_data_updated) def _detach(self, visual): diff --git a/vispy/visuals/mesh.py b/vispy/visuals/mesh.py --- a/vispy/visuals/mesh.py +++ b/vispy/visuals/mesh.py @@ -117,6 +117,8 @@ def __init__(self, vertices=None, faces=None, vertex_colors=None, self.events.add(data_updated=Event) + self._meshdata = None + # Define buffers self._vertices = VertexBuffer(np.zeros((0, 3), dtype=np.float32)) self._cmap = get_colormap('cubehelix') @@ -158,9 +160,9 @@ def shading(self, shading): if self.shading_filter is None: from vispy.visuals.filters import ShadingFilter self.shading_filter = ShadingFilter(shading=shading) + self.attach(self.shading_filter) else: self.shading_filter.shading = shading - self.attach(self.shading_filter) def set_data(self, vertices=None, faces=None, vertex_colors=None, face_colors=None, color=None, vertex_values=None,
diff --git a/vispy/visuals/tests/test_mesh.py b/vispy/visuals/tests/test_mesh.py --- a/vispy/visuals/tests/test_mesh.py +++ b/vispy/visuals/tests/test_mesh.py @@ -29,6 +29,25 @@ def test_mesh_color(): np.testing.assert_allclose(vertices['position'], new_vertices) +@requires_pyopengl() +@requires_application() [email protected]('shading', [None, 'flat', 'smooth']) +def test_mesh_shading_change_from_none(shading): + # Regression test for #2041: exception raised when changing the shading + # mode with shading=None initially. + size = (45, 40) + with TestingCanvas(size=size) as c: + v = c.central_widget.add_view(border_width=0) + vertices = np.array([(0, 0, 0), (0, 0, 1), (1, 0, 0)], dtype=float) + faces = np.array([(0, 1, 2)]) + mesh = scene.visuals.Mesh(vertices=vertices, faces=faces, shading=None) + v.add(mesh) + c.render() + # This below should not fail. + mesh.shading = shading + c.render() + + @requires_pyopengl() @requires_application() @pytest.mark.parametrize('shading', [None, 'flat', 'smooth'])
Shading mode switching for MeshVisual doesn't work if initialised with shading=None If a `MeshVisual` is initialised with `shading=None` then switched to `shading='flat'` or `shading='smooth'` there are some shader compilation errors <details> <summary>example adapted from tube</summary> <br> ```python import sys from vispy import scene from vispy.geometry.torusknot import TorusKnot from colorsys import hsv_to_rgb import numpy as np canvas = scene.SceneCanvas(keys='interactive') view = canvas.central_widget.add_view() points1 = TorusKnot(5, 3).first_component[:-1] points1[:, 0] -= 20. points1[:, 2] -= 15. colors = np.linspace(0, 1, len(points1)) colors = np.array([hsv_to_rgb(c, 1, 1) for c in colors]) vertex_colors = np.random.random(8 * len(points1)) vertex_colors = np.array([hsv_to_rgb(c, 1, 1) for c in vertex_colors]) l1 = scene.visuals.Tube(points1, shading=None, color=colors, # this is overridden by # the vertex_colors argument vertex_colors=vertex_colors, tube_points=8) view.add(l1) view.camera = scene.TurntableCamera() # tube does not expose its limits yet view.camera.set_range((-20, 20), (-20, 20), (-20, 20)) canvas.show() if __name__ == '__main__': if sys.flags.interactive != 1: canvas.app.run() l1.shading = 'flat' ``` </details> <details> <summary>Error...</summary> <br> ```python WARNING: Unsubstituted placeholders in code: ['$light_dir'] replacements made: ['normal', 'render2scene', 'visual2scene', 'scene2doc', 'doc2scene'] WARNING: Unsubstituted placeholders in code: ['$flat_shading', '$light_color', '$diffuse_color', '$shininess', '$shininess', '$light_color', '$specular_color', '$shading_enabled', '$ambient_color'] replacements made: [] WARNING: Error drawing visual <Tube at 0x14e9d4df0> WARNING: Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py", line 483, in <module> pydevconsole.start_client(host, port) File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py", line 411, in start_client process_exec_queue(interpreter) File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py", line 244, in process_exec_queue inputhook() File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydev_ipython/inputhookqt5.py", line 112, in inputhook_qt5 app.processEvents(QtCore.QEventLoop.AllEvents, 300) File "/Users/aburt/Programming/vispy/vispy/app/backends/_qt.py", line 526, in event out = super(QtBaseCanvasBackend, self).event(ev) File "/Users/aburt/Programming/vispy/vispy/app/backends/_qt.py", line 846, in paintGL self._vispy_canvas.events.draw(region=None) File "/Users/aburt/Programming/vispy/vispy/util/event.py", line 452, in __call__ self._invoke_callback(cb, event) File "/Users/aburt/Programming/vispy/vispy/util/event.py", line 470, in _invoke_callback _handle_exception(self.ignore_callback_errors, << caught exception here: >> File "/Users/aburt/Programming/vispy/vispy/util/event.py", line 468, in _invoke_callback cb(event) File "/Users/aburt/Programming/vispy/vispy/scene/canvas.py", line 218, in on_draw self._draw_scene() File "/Users/aburt/Programming/vispy/vispy/scene/canvas.py", line 267, in _draw_scene self.draw_visual(self.scene) File "/Users/aburt/Programming/vispy/vispy/scene/canvas.py", line 305, in draw_visual node.draw() File "/Users/aburt/Programming/vispy/vispy/scene/visuals.py", line 99, in draw self._visual_superclass.draw(self) File "/Users/aburt/Programming/vispy/vispy/visuals/mesh.py", line 346, in draw Visual.draw(self, *args, **kwds) File "/Users/aburt/Programming/vispy/vispy/visuals/visual.py", line 446, in draw self._program.draw(self._vshare.draw_mode, File "/Users/aburt/Programming/vispy/vispy/visuals/shaders/program.py", line 102, in draw Program.draw(self, *args, **kwargs) File "/Users/aburt/Programming/vispy/vispy/gloo/program.py", line 498, in draw raise RuntimeError('All attributes must have the same size, got:\n' RuntimeError: All attributes must have the same size, got: <VertexBuffer size=4704 last_dim=4>: 4704 <VertexBuffer size=0 last_dim=3>: 0 <VertexBuffer size=4704 last_dim=3>: 4704 ERROR: Invoking <bound method SceneCanvas.on_draw of <SceneCanvas (PyQt5) at 0x135877fd0>> for DrawEvent WARNING: Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py", line 483, in <module> pydevconsole.start_client(host, port) File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py", line 411, in start_client process_exec_queue(interpreter) File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydevconsole.py", line 244, in process_exec_queue inputhook() File "/Applications/PyCharm.app/Contents/plugins/python/helpers/pydev/pydev_ipython/inputhookqt5.py", line 112, in inputhook_qt5 app.processEvents(QtCore.QEventLoop.AllEvents, 300) File "/Users/aburt/Programming/vispy/vispy/app/backends/_qt.py", line 526, in event out = super(QtBaseCanvasBackend, self).event(ev) File "/Users/aburt/Programming/vispy/vispy/app/backends/_qt.py", line 846, in paintGL self._vispy_canvas.events.draw(region=None) File "/Users/aburt/Programming/vispy/vispy/util/event.py", line 452, in __call__ self._invoke_callback(cb, event) File "/Users/aburt/Programming/vispy/vispy/util/event.py", line 470, in _invoke_callback _handle_exception(self.ignore_callback_errors, << caught exception here: >> File "/Users/aburt/Programming/vispy/vispy/util/event.py", line 468, in _invoke_callback cb(event) File "/Users/aburt/Programming/vispy/vispy/gloo/context.py", line 172, in flush_commands self.glir.flush(self.shared.parser) File "/Users/aburt/Programming/vispy/vispy/gloo/glir.py", line 579, in flush self._shared.flush(parser) File "/Users/aburt/Programming/vispy/vispy/gloo/glir.py", line 501, in flush parser.parse(self._filter(self.clear(), parser)) File "/Users/aburt/Programming/vispy/vispy/gloo/glir.py", line 819, in parse self._parse(command) File "/Users/aburt/Programming/vispy/vispy/gloo/glir.py", line 789, in _parse ob.set_data(*args) File "/Users/aburt/Programming/vispy/vispy/gloo/glir.py", line 926, in set_data raise RuntimeError("Shader compilation error in %s:\n%s" % RuntimeError: Shader compilation error in GL_VERTEX_SHADER: on line 330: '<' : syntax error: syntax error vec3 light = normalize($light_dir.xyz); ERROR: Invoking <bound method GLContext.flush_commands of <GLContext at 0x14d1e6130>> for DrawEvent WARNING: Error drawing visual <Tube at 0x14e9d4df0> ERROR: Invoking <bound method SceneCanvas.on_draw of <SceneCanvas (PyQt5) at 0x135877fd0>> repeat 2 ``` </details> This error does not happen if the `MeshVisual` is initialised with `shading='flat'`, you can then switch freely between all three shading modes I guess this is mostly related to #1463 (@asnt) since this switching wasn't possible before with the separate shaders for shaded and unshaded meshes
2021-05-28T18:48:06
vispy/vispy
2,058
vispy__vispy-2058
[ "1109" ]
fd97fa3a3e93cf5d240a4ad2c10172c21066991a
diff --git a/vispy/gloo/gl/__init__.py b/vispy/gloo/gl/__init__.py --- a/vispy/gloo/gl/__init__.py +++ b/vispy/gloo/gl/__init__.py @@ -11,7 +11,7 @@ This is in part possible by the widespread availability of OpenGL ES 2.0. All functions that this API provides accept and return Python arguments -(no ctypes is required); strings are real strings and you can pass +(no ctypes is required); strings are real strings and you can pass data as numpy arrays. In general the input arguments are not checked (for performance reasons). Each function results in exactly one OpenGL API call, except when using the pyopengl backend. @@ -41,7 +41,7 @@ class MainProxy(BaseGLProxy): - """Main proxy for the GL ES 2.0 API. + """Main proxy for the GL ES 2.0 API. The functions in this namespace always call into the correct GL backend. Therefore these function objects can be safely stored for @@ -58,7 +58,7 @@ def __call__(self, funcname, returns, *args): proxy = MainProxy() -def use_gl(target='gl2'): +def use_gl(target=None): """Let Vispy use the target OpenGL ES 2.0 implementation Also see ``vispy.use()``. @@ -66,7 +66,7 @@ def use_gl(target='gl2'): Parameters ---------- target : str - The target GL backend to use. + The target GL backend to use. Default gl2 or es2, depending on the platform. Available backends: * gl2 - Use ES 2.0 subset of desktop (i.e. normal) OpenGL @@ -81,7 +81,7 @@ def use_gl(target='gl2'): debug". (Debug does not apply to 'gl+', since PyOpenGL has its own debug mechanism) """ - target = target or 'gl2' + target = target or default_backend.__name__.split(".")[-1] target = target.replace('+', 'plus') # Get options @@ -168,7 +168,7 @@ def gl_debug_wrapper(*args): # Log return value if ret is not None: if fn.__name__ == 'glReadPixels': - logger.debug(" <= %s[%s]" % (type(ret), len(ret))) + logger.debug(" <= %s[%s]" % (type(ret), len(ret))) else: logger.debug(" <= %s" % repr(ret)) # Check for errors (raises if an error occured) @@ -226,6 +226,9 @@ def _fix_osmesa_gl_lib_if_testing(): # Load default gl backend from . import gl2 as default_backend # noqa +if default_backend._lib is None: # Probably Android or RPi + from . import es2 as default_backend # noqa + # Call use to start using our default backend use_gl() diff --git a/vispy/gloo/gl/gl2.py b/vispy/gloo/gl/gl2.py --- a/vispy/gloo/gl/gl2.py +++ b/vispy/gloo/gl/gl2.py @@ -14,7 +14,6 @@ # Ctypes stuff - # Load the OpenGL library. We more or less follow the same approach # as PyOpenGL does internally diff --git a/vispy/gloo/glir.py b/vispy/gloo/glir.py --- a/vispy/gloo/glir.py +++ b/vispy/gloo/glir.py @@ -458,7 +458,7 @@ def command(self, *args): self._commands.append(args) def set_verbose(self, verbose): - """Set verbose or not. If True, the GLIR commands are printed right before they get parsed. + """Set verbose or not. If True, the GLIR commands are printed right before they get parsed. If a string is given, use it as a filter. """ self._verbose = verbose @@ -1375,7 +1375,7 @@ def set_data(self, offset, data): # Determine whether to check errors to try handling the ATI bug check_ati_bug = ((not self._bufferSubDataOk) and - (gl.current_backend is gl.gl2) and + (gl.current_backend.__name__.split(".")[-1] == "gl2") and sys.platform.startswith('win')) # flush any pending errors
Vispy always tries to import gl2 by default At https://github.com/vispy/vispy/blob/master/vispy/gloo/gl/__init__.py#L235-L238, vispy always tries to import gl2 and call use_gl with 'gl2' as the default argument. This fails on Android (and I assume other places) because only gles is available. I fixed it for that by patching to import es2 by default instead. I'd like to change it so that Vispy works without modification on Android, but I'm not sure how since gloo.gl does need to import something as a default. One option would be to try the current method, then if it fails catch the Exception and try es2 instead, but I'm not sure if there are downsides to that. Any ideas?
I think it would be fine to try to import the most compete gl possible. We could triage based on platform or fall back as you suggest. Systematically going from most compete to most restrictive GL seems like it would work well. I think ideally you would detect the platform; when its Android or Raspberry pi use es2, otherwise use gl2. @inclement do you have time to try the autodetection? Sure, but I missed this - is that something now in master? Sorry, I meant try _implementing_ the autodetection :) Oh, right! In that case, still sure, it's been on my list of things to try for a while but hasn't been a priority. I might return to Vispy on Android soon to try to get it working properly, in which case I'll certainly take a loot at it. On 20/05/16 01:57, Eric Larson wrote: > Sorry, I meant try /implementing/ the autodetection :) > > — > You are receiving this because you were mentioned. > Reply to this email directly or view it on GitHub > https://github.com/vispy/vispy/issues/1109#issuecomment-220491606 I may be able to implement code to detect raspberry pi if you let me know where it should go. @kmuehlbauer What does rpi do for this? Does it have a full GL library available or only ES? Either way I'm moving this to 0.7. @djhoese There seems to be not much detailed information out there. According to the specs it is - OpenGL ES 1.1, 2.0 graphics for Raspberry Pi 3B+ - OpenGL ES 3.0 graphics for the new Raspberry Pi 4
2021-06-09T16:11:33
vispy/vispy
2,059
vispy__vispy-2059
[ "1465" ]
fd97fa3a3e93cf5d240a4ad2c10172c21066991a
diff --git a/vispy/app/backends/_glfw.py b/vispy/app/backends/_glfw.py --- a/vispy/app/backends/_glfw.py +++ b/vispy/app/backends/_glfw.py @@ -289,6 +289,7 @@ def __init__(self, *args, **kwargs): self._next_key_text = {} self._vispy_canvas.set_current() self._vispy_canvas.events.initialize() + self._on_resize(self._id, size[0], size[1]) def _vispy_warmup(self): etime = time() + 0.25
Transforms broken in SceneCanvas with glfw backend Hello. I'm using vispy 0.5.1 on Debian 8 with a PyQt5 backend. When I run my app, the SceneCanvas is stuck with an identity transform (which looks broken, obviously) until I resize the window or use a mouse key in the window. This also happens with the example https://github.com/vispy/vispy/blob/master/examples/demo/scene/oscilloscope.py when not using fullscreen. My workaround was to call SceneCanvas' _update_transforms() right after creating the canvas.
@ltjax Thanks for reporting this issue. Could you try installing this repository's `master` branch and see if that fixes things for you? There have been updates recently for fixing PyQt5 compatibility. I don't remember fixing anything specifically dealing with transforms, but it would be best to make sure it hasn't been fixed already. If this isn't fixed for you in `master` could you please provide me with a minimum working example so I can try to figure out what's going on. I can confirm the bug still happens with the `master` version. Here's a small sample that illustrates the problem: ``` import vispy from vispy import scene from vispy.scene import ViewBox class Application(object): def __init__(self): view = ViewBox(camera='panzoom', border_color=(1, 1, 1, 1)) self.canvas = scene.SceneCanvas(keys='interactive', show=True, title="Update fix") # Uncomment this for workaround #self.canvas._update_transforms() self.canvas.central_widget.add_widget(view) self.canvas.show() def run(self): print(vispy.version_info) self.canvas.app.run() if __name__ == '__main__': Application().run() ``` Thanks for the code. I'm testing on a macbook with a conda environment (python 3.6, pyqt5) and I'm not seeing a difference with or without the `_update_transforms` line. Are you getting exceptions/errors/warnings? Could you take a screenshot of the difference if it is visual? When I print the `transforms` object and the `self.canvas.transforms.canvas_transform` I see non-identity transforms. I can do that next week. I definitely saw an identity transform before the _update_transforms and non-identity after (I checked with breakpoints in the debugger/PyCharm). Since that bug reacts to events, my guess is that where the platform dependency comes in. Are you getting resize events when just showing the window on mac maybe? Cause the resize handler is what normally called _update_transforms() and that was only called when I manually dragged the window edges. Yes, I see a resize event before the SceneCanvas creation even returns. Well, there's the problem then. No such event on linux. Kind of a typical cross-platform problem, unfortunately Hello. So here are the promised screenshots. The first one is the same right after starting it. I changed the border_color to red to make it more visible. ![vispy-after-start](https://user-images.githubusercontent.com/770847/38543354-aa7524a0-3ca4-11e8-8243-caad85fe0703.png) This one is after the first resize event. As you can see, the border is correctly transformed now. ![vispy-after-move](https://user-images.githubusercontent.com/770847/38543471-e468ddc8-3ca4-11e8-8fdf-9baa747d1b6c.png) Oh, mea culpa - I'm actually using the glfw backend, not pyqt5. Sorry about that. Ok, so I have investigated this a bit more: When I switch to PyQt5 via vispy.use("PyQt5"), all the problems are gone. If I use vispy.use("Glfw"), it breaks again. With the latter, it breaks again even with my initial _update_transforms() hack once I add a Text visual. Again, problem goes away after the first pan or resize. Hope that sheds some light on the issue. So with glfw the initial canvas is wrong, you pan/zoom/resize and it fixes itself. If you add a visual it breaks again? Is everything broken again or just the text visual? Or, after rereading your message, if you have your update transforms hack then it is still broken when you add a visual after the update transforms? I'm not sure I even understand my question at this point. Hehe, sorry for the confusion. First of, everything is fine with PyQt5. All other cases use glfw: * no hack, no text visual -> initial canvas is broken * hack, no text visual -> initial canvas is okay * with text visual: first frame is exactly like both cases without text visual, but then it "breaks" on its own and zooms out to about 2000% - after resize or pan it corrects itself again What do you mean by first frame? Could you update your tiny example from your previous message to behave the same way (adding a text visual, etc)? In the past we have seen differences between backends in whether they generate an initial resize event when the window is created. I'll bet that's what happened here. @campagnola But why would adding the visual cause the redraw to be wrong? @djhoese I could - but you gotta have to wait another week. I'm developing on site for a customer, and I won't be there again until next week. I really just added a Text visual saying "Hello World!" though. Here's the updated code. You can try the different cases by changing the CASE variable. ``` import vispy from vispy import scene from vispy.scene import ViewBox, Label CASE = 3 class Application(object): def __init__(self): self.view = ViewBox(camera='panzoom', border_color=(1, 0, 0, 1)) self.canvas = scene.SceneCanvas(keys='interactive', show=True, title="Update fix", size=(200, 200)) self.grid_lines = scene.GridLines(color=(1, 1, 1, 1.0), parent=self.view.scene) self.canvas.central_widget.add_widget(self.view) if CASE != 3: self.view.add_widget(Label("Hello World!", color=(1, 1, 1, 1))) self.canvas.show() def run(self): print(vispy.version_info) self.canvas.app.run() if __name__ == '__main__': vispy.use("PyQt5" if CASE == 1 else "Glfw") Application().run() ``` Case 1: (PyQt5, all good) ![vispy_case_1](https://user-images.githubusercontent.com/770847/39748092-7bf096d4-52af-11e8-822b-2aeb182bcbcd.png) Case 2: (Glfw, with text visual) ![vispy_case_2](https://user-images.githubusercontent.com/770847/39748101-81c8b244-52af-11e8-8bb8-c1bb52e2d0b7.png) Case 3: (Glfw, without text visual) ![vispy_case_3](https://user-images.githubusercontent.com/770847/39748109-88b414f4-52af-11e8-8db1-53baf9b25acd.png) Note that Case 2 flickers at first and seems to render a frame that looks like Case 3 What happens if you do `show=False` in the SceneCanvas creation (I think I asked this before)? That does not change anything (And I don't think you did) @ltjax Any chance you could try vispy from current master and try this out again? I changed a lot with PyQt5 but also semi-recently fixed some bugs with resize events with the PyQt5 backend. So coming back to this and running on OSX with glfw from conda-forge shows one small change, the two glfw cases (with/without text visual) are not the same result. Still wrong, but at least the same. I'm moving this from the 0.6 to 0.7 version milestone. As far as I can tell this is only an issue with the glfw backend and I'm having trouble figuring it out. I had some success forcing a `self.canvas.size = (300, 300)` after the canvas was shown which caused a resize (because the size was different than the initial size) and caused things to show correctly. Otherwise, not much luck trying to get glfw to emit the right events. Hello there and sorry for the delay. I tried again and glfw still does not work correctly. qt5 does not work at all (CanvasBackendDesktop has not attribute setFormat). Maybe glfw has some sort of create event at the start with the window sizes and you have to just use that to initialize the sizes? @ltjax What version of PyQt are you running with? I do not know. Still whatever I installed when I first worked on this last year, I guess. The program is at the customer's and I can only check next month. So how do you know Qt5 still doesn't work? Did you or your customer update vispy? Would it be possible for you to install PyQt5 locally and test it? I'm assuming you are running glfw locally? What do you mean, Qt5 still doesn't work? It worked fine before I updated to the latest vispy. I just tried it out since you asked me - though I was kinda confused why you would ask me to do that after fixing stuff in the Qt5 backend. And what do you mean by "install locally"? I assumed you were running things on customer machines that you didn't have access to. I wanted to know if you installed vispy with PyQt5 on your local machine that's right in front of you (not a customer machine) if it worked or not. You mentioned `qt5 does not work at all (CanvasBackendDesktop has not attribute setFormat).` but I've never seen this error. So there is the glfw issue, but also a PyQt5 issue apparently. I have all the code and setup on the customers machine, I cannot test it here. Yea, that's right, but both issues seem to be unrelated, except that they appear on my customers machine. I say we just stay on track with the glfw thing and ignore Qt5 for now (because it _was_ working fine:-)) So I'm coming back to this because I marked it for the 0.7 milestone. As mentioned above it seems the glfw backend doesn't emit a resize event when it is first created/shown. A simple workaround seems to be: ``` diff --git a/vispy/app/backends/_glfw.py b/vispy/app/backends/_glfw.py --- a/vispy/app/backends/_glfw.py (revision e33aae23847e8e5f43248ba9d014cc4aea211a90) +++ b/vispy/app/backends/_glfw.py (date 1623253407778) @@ -282,6 +282,7 @@ self._vispy_set_position(*p.position) if p.show: glfw.glfwShowWindow(self._id) + self._on_resize(self._id, size[0], size[1]) # Init self._initialized = True ``` My guess for why this doesn't happen on pyqt but does on glfw is that the CanvasBackend for the pyqt backend is itself a QtGLWidget. So when it gets created Qt's internals call the widget's `resizeGL` method which starts things moving in the right direction as far as vispy is concerned. For glfw we are simply wrapping glfw to create a window (`glfwCreateWindow`). We don't actually assign the callbacks for handling things like resizing until *after* the Window is created. There isn't really a way around this as assigning the callbacks requires the reference to the window. @kmuehlbauer @ltjax @almarklein Any opinions on this? Let me try moving the resize call after the `init` and see if that still works. Then I'll make a PR. Biggest downside could be trying to use glfw without showing the canvas and hoping for something to show up...but then again the visuals wouldn't be sized correctly without resizing anyway. Ok, so I was on my way to make a PR for this when I thought "I should write a test for this...wait how aren't all the glfw tests failing already?". Turns out that if you put a `canvas.render()` before the `canvas.show()` call the resulting canvas/window is correct. All the tests use `.render()` so they all produce the expected output. I'm not really sure how to test this then.
2021-06-09T16:46:37
vispy/vispy
2,063
vispy__vispy-2063
[ "1441" ]
190f69e60f28a1c6d1dae6edcedf0fabc6c165ef
diff --git a/vispy/visuals/line/line.py b/vispy/visuals/line/line.py --- a/vispy/visuals/line/line.py +++ b/vispy/visuals/line/line.py @@ -418,6 +418,8 @@ def __init__(self, parent): Visual.__init__(self, vcode=self.VERTEX_SHADER, fcode=self.FRAGMENT_SHADER) self._index_buffer = gloo.IndexBuffer() + # The depth_test being disabled prevents z-ordering, but if + # we turn it on the blending of the aa edges produces artifacts. self.set_gl_state('translucent', depth_test=False) self._draw_mode = 'triangles' @@ -425,7 +427,6 @@ def _prepare_transforms(self, view): data_doc = view.get_transform('visual', 'document') doc_px = view.get_transform('document', 'framebuffer') px_ndc = view.get_transform('framebuffer', 'render') - vert = view.view_program.vert vert['transform'] = data_doc vert['doc_px_transform'] = doc_px
Z-indexing visuals in 2d plots using scene.SceneCanvas The translation of z-coordinates to move visuals back and forth (like z-indexing) doens't seems to work with different types of visual classes? I tried with a custom visual and a scene.visuals.Image(). The only thing that mattered to me was which visuals that was first created.
For custom visuals you'll need to make sure that your vertex shader is properly using the Z-coordinate of the transform. I've had issues using ImageVisuals too, but never had time to look in to what the issue was. Additionally you can control the draw order by specifying `the_vis_obj.order = integer`. You'll want to set this order before you add it to the scene though otherwise you have to call a private method `canvas._update_scenegraph(None)` which is not recommended because it is private, but I don't know of another way to do it. @larsoner @kmuehlbauer Any other tips for specifying z-order? @mkkb @davidh-ssec A minimal example showing the behaviour is always best for getting fast into the problem. I can make a simplified example showing the behavior early next week Here is an example that does not let me edit the "z-index". I first make a red line visual, then an image and at last I make a blue line. On_key_press I added that one can change the z-transform of the red line, preferably moving it to the front/back of the canvas. ``` import sys from vispy import scene from vispy import app from vispy.io import load_data_file, read_png import numpy as np from vispy.visuals.transforms import STTransform canvas = scene.SceneCanvas(keys='interactive') canvas.size = 800, 600 canvas.show() # Set up a viewbox to display the image with interactive pan/zoom view = canvas.central_widget.add_view() # Create the image img_data = read_png(load_data_file('mona_lisa/mona_lisa_sm.png')) interpolation = 'nearest' # Add other visuals to main_view pos = np.zeros((2, 2)).astype(np.float32) pos[:, 0] = np.array([-10, 600]).astype(np.float32) pos[:, 1] = np.array([-10, 600]).astype(np.float32) line_pre = scene.visuals.Line(pos=pos, parent=view.scene, color='red', width=40, method='agg') line_pre_z_ind = 0 line_pre.transform = STTransform(translate=[0, 0, line_pre_z_ind]) image = scene.visuals.Image(img_data, interpolation=interpolation, parent=view.scene, method='subdivide') image.transform = STTransform(translate=[0, 0, 0]) canvas.title = 'Spatial Filtering using %s Filter' % interpolation # Set 2D camera (the camera will scale to the contents in the scene) view.camera = scene.PanZoomCamera(aspect=1) # flip y-axis to have correct aligment view.camera.flip = (0, 1, 0) view.camera.set_range() view.camera.zoom(0.1, (250, 200)) # get interpolation functions from Image names = image.interpolation_functions names = list(names) names.sort() act = 17 # Add other visuals to main_view pos = np.zeros((2, 2)).astype(np.float32) pos[:, 0] = np.array([-10, 600]).astype(np.float32) pos[:, 1] = np.array([-9, 601]).astype(np.float32) line_post = scene.visuals.Line(pos=pos, parent=view.scene, color='blue', width=40, method='agg') line_post.transform = STTransform(translate=[0, 0, 0]) view.camera.set_range(x=(-10,10), y=(-10,10)) # Implement key presses @canvas.events.key_press.connect def on_key_press(event): global act if event.key in ['Left', 'Right']: if event.key == 'Right': step = 1 line_pre.transform = STTransform(translate=[0, -5, line_pre_z_ind]) else: step = -1 line_pre.transform = STTransform(translate=[0, 5, line_pre_z_ind]) act = (act + step) % len(names) interpolation = names[act] image.interpolation = interpolation canvas.title = 'Spatial Filtering using %s Filter' % interpolation canvas.update() if event.key in ['Down', 'Up']: if event.key == 'Down': line_pre_z_ind = -10 print( event.key, 'New z-indx for red line', line_pre_z_ind) line_pre.transform = STTransform(translate=[0, 0, line_pre_z_ind]) if event.key == 'Up': line_pre_z_ind = 10 print( event.key, 'New z-indx for red line', line_pre_z_ind) line_pre.transform = STTransform(translate=[0, 0, line_pre_z_ind]) act = (act) % len(names) interpolation = names[act] canvas.title = 'Spatial Filtering using {:} Filter, z_ind={:d}'.format(interpolation, line_pre_z_ind) canvas.update() if __name__ == '__main__' and sys.flags.interactive == 0: app.run() ``` @mkkb Might not be the issue here, but canvas.update() should be called last in the callback. @mkkb You would need to add canvas.update() after you changed the transform in the keypressed event. I did the following updates but it doesn't help. Did it work for you? (I edited the code above) For fun I also added a translation moving the lines in y-direction with left/right key, that works but not the z-indexing. @mkkb Sorry, can't test atm. I'll have a look as soon as possible. @mkkb AFAICT this seems to be a bug in the `LineVisual` `agg`-method. When I change the method to `gl` then everything works as expected (red line will be switched in z-index above and below the image). For the time being you can use 'gl'-method. If you can dig something up concerning the `agg`-method, please let us know. This will be much more important in the future since I'd like to consider changing the default text method to `agg` (version 0.7?). Good to know. Thx Kai. I'll see if I can dig up something when I get the time. Just wanted to post a small clarification and explanation of what is wrong with the agg method: It seems the entire agg.vert shader is written with vec2's. It uses the transform you give it, but immediately drops any Z coordinate by doing `.xy` everywhere it is used (multiple spots). Handling a Z dimension would likely require a completely different algorithm to be implemented. The results if someone did a transform that resulted in points not all being on the same Z plane would likely be undesirable in one way or another (ex. x/y differences show a small distance, but visually the line spans a long distance in the Z dimension). Most of the algorithm is indeed 2d, but the z component can/should be stored and used when setting `gl_Position` at the bottom. I am looking into this now. It also does not help that the agg line has the depth test disabled ...
2021-06-10T15:35:27
vispy/vispy
2,066
vispy__vispy-2066
[ "1487" ]
c7f72cb8ba47f32606ec13dfab0147ca48b8a1cf
diff --git a/vispy/color/colormap.py b/vispy/color/colormap.py --- a/vispy/color/colormap.py +++ b/vispy/color/colormap.py @@ -3,7 +3,6 @@ # Distributed under the (new) BSD License. See LICENSE.txt for more info. from __future__ import division # just to be safe... -import inspect import warnings import numpy as np @@ -607,7 +606,7 @@ def map(self, t): np.sqrt(t)) -class _SingleHue(Colormap): +class SingleHue(Colormap): """A colormap which is solely defined by the given hue and value. Given the color hue and value, this color map increases the saturation @@ -643,10 +642,10 @@ def __init__(self, hue=200, saturation_range=[0.1, 0.8], value=1.0): (hue, saturation_range[0], value), (hue, saturation_range[1], value) ], color_space='hsv') - super(_SingleHue, self).__init__(colors) + super(SingleHue, self).__init__(colors) -class _HSL(Colormap): +class HSL(Colormap): """A colormap which is defined by n evenly spaced points in a circular color space. This means that we change the hue value while keeping the @@ -685,11 +684,11 @@ def __init__(self, ncolors=6, hue_start=0, saturation=1.0, value=1.0, colors = ColorArray([(hue, saturation, value) for hue in hues], color_space='hsv') - super(_HSL, self).__init__(colors, controls=controls, - interpolation=interpolation) + super(HSL, self).__init__(colors, controls=controls, + interpolation=interpolation) -class _HSLuv(Colormap): +class HSLuv(Colormap): """A colormap which is defined by n evenly spaced points in the HSLuv space. Parameters @@ -733,19 +732,19 @@ def __init__(self, ncolors=6, hue_start=0, saturation=1.0, value=0.7, [hsluv_to_rgb([hue, saturation, value]) for hue in hues], ) - super(_HSLuv, self).__init__(colors, controls=controls, - interpolation=interpolation) + super(HSLuv, self).__init__(colors, controls=controls, + interpolation=interpolation) -class _HUSL(_HSLuv): +class _HUSL(HSLuv): """Deprecated.""" def __init__(self, *args, **kwargs): - warnings.warn("_HUSL Colormap is deprecated. Please use '_HSLuv' instead.") + warnings.warn("_HUSL Colormap is deprecated. Please use 'HSLuv' instead.") super().__init__(*args, **kwargs) -class _Diverging(Colormap): +class Diverging(Colormap): def __init__(self, h_pos=20, h_neg=250, saturation=1.0, value=0.7, center="light"): @@ -759,11 +758,11 @@ def __init__(self, h_pos=20, h_neg=250, saturation=1.0, value=0.7, colors = ColorArray([start, mid, end]) - super(_Diverging, self).__init__(colors) + super(Diverging, self).__init__(colors) -class _RedYellowBlueCyan(Colormap): - """A colormap which is goes red-yellow positive and blue-cyan negative +class RedYellowBlueCyan(Colormap): + """A colormap which goes red-yellow positive and blue-cyan negative Parameters --------- @@ -783,7 +782,7 @@ def __init__(self, limits=(0.33, 0.66, 1.0)): colors = [(0., 1., 1., 1.), (0., 0., 1., 1.), (0., 0., 1., 0.), (1., 0., 0., 0.), (1., 0., 0., 1.), (1., 1., 0., 1.)] colors = ColorArray(colors) - super(_RedYellowBlueCyan, self).__init__( + super(RedYellowBlueCyan, self).__init__( colors, controls=controls, interpolation='linear') @@ -1068,8 +1067,8 @@ def __init__(self, limits=(0.33, 0.66, 1.0)): hot=_Hot(), ice=_Ice(), winter=_Winter(), - light_blues=_SingleHue(), - orange=_SingleHue(hue=35), + light_blues=SingleHue(), + orange=SingleHue(hue=35), viridis=Colormap(ColorArray(_viridis_data)), # Diverging presets coolwarm=Colormap(ColorArray( @@ -1080,53 +1079,70 @@ def __init__(self, limits=(0.33, 0.66, 1.0)): ], color_space="hsv" )), - PuGr=_Diverging(145, 280, 0.85, 0.30), - GrBu=_Diverging(255, 133, 0.75, 0.6), - GrBu_d=_Diverging(255, 133, 0.75, 0.6, "dark"), - RdBu=_Diverging(220, 20, 0.75, 0.5), - - # Configurable colormaps - cubehelix=CubeHelixColormap, - single_hue=_SingleHue, - hsl=_HSL, - husl=_HUSL, - hsluv=_HSLuv, - diverging=_Diverging, - RdYeBuCy=_RedYellowBlueCyan, + PuGr=Diverging(145, 280, 0.85, 0.30), + GrBu=Diverging(255, 133, 0.75, 0.6), + GrBu_d=Diverging(255, 133, 0.75, 0.6, "dark"), + RdBu=Diverging(220, 20, 0.75, 0.5), + + cubehelix=CubeHelixColormap(), + single_hue=SingleHue(), + hsl=HSL(), + husl=HSLuv(), + diverging=Diverging(), + RdYeBuCy=RedYellowBlueCyan(), ) def get_colormap(name, *args, **kwargs): - """Obtain a colormap - Some colormaps can have additional configuration parameters. Refer to - their corresponding documentation for more information. + """Obtain a colormap. + Parameters ---------- name : str | Colormap Colormap name. Can also be a Colormap for pass-through. + *args: + Deprecated. + **kwargs + Deprecated. + Examples -------- >>> get_colormap('autumn') - >>> get_colormap('single_hue', hue=10) + >>> get_colormap('single_hue') + + .. versionchanged: 0.7 + + Additional args/kwargs are no longer accepted. Colormap classes are + no longer created on the fly. To create a ``cubehelix`` + (``CubeHelixColormap``), ``single_hue`` (``SingleHue``), ``hsl`` + (``HSL``), ``husl`` (``HSLuv``), ``diverging`` (``Diverging``), or + ``RdYeBuCy`` (``RedYellowBlueCyan``) colormap you must import and + instantiate it directly from the ``vispy.color.colormap`` module. + """ + if args or kwargs: + warnings.warn("Creating a Colormap instance with 'get_colormap' is " + "no longer supported. No additional arguments or " + "keyword arguments should be passed.", DeprecationWarning) if isinstance(name, BaseColormap): - cmap = name - else: - if not isinstance(name, str): - raise TypeError('colormap must be a Colormap or string name') - if name in _colormaps: # vispy cmap - cmap = _colormaps[name] - elif has_matplotlib(): # matplotlib cmap - try: - cmap = MatplotlibColormap(name) - except ValueError: - raise KeyError('colormap name %s not found' % name) - else: + return name + + if not isinstance(name, str): + raise TypeError('colormap must be a Colormap or string name') + if name in _colormaps: # vispy cmap + cmap = _colormaps[name] + if name in ("cubehelix", "single_hue", "hsl", "husl", "diverging", "RdYeBuCy"): + warnings.warn(f"Colormap '{name}' has been deprecated. " + f"Please import and create 'vispy.color.colormap.{cmap.__class__.__name__}' " + "directly instead.", DeprecationWarning) + + elif has_matplotlib(): # matplotlib cmap + try: + cmap = MatplotlibColormap(name) + except ValueError: raise KeyError('colormap name %s not found' % name) - - if inspect.isclass(cmap): - cmap = cmap(*args, **kwargs) - + else: + raise KeyError('colormap name %s not found' % name) return cmap
diff --git a/vispy/visuals/tests/test_colormap.py b/vispy/visuals/tests/test_colormap.py --- a/vispy/visuals/tests/test_colormap.py +++ b/vispy/visuals/tests/test_colormap.py @@ -11,7 +11,7 @@ from vispy.testing import (requires_application, TestingCanvas, run_tests_if_main) from vispy.testing.image_tester import assert_image_approved -from vispy.color import (get_colormap, Colormap) +from vispy.color import Colormap size = (100, 100) @@ -58,10 +58,12 @@ def test_colormap_discrete_nu(): @requires_application() def test_colormap_single_hue(): """Test colormap support using a single hue()""" + from vispy.color.colormap import SingleHue with TestingCanvas(size=size, bgcolor='w') as c: idata = np.linspace(255, 0, size[0]*size[1]).astype(np.ubyte) data = idata.reshape((size[0], size[1])) - image = Image(cmap=get_colormap('single_hue', 255), + cmap = SingleHue(255) + image = Image(cmap=cmap, clim='auto', parent=c.scene) image.set_data(data) assert_image_approved(c.render(), "visuals/colormap_hue.png") @@ -81,10 +83,12 @@ def test_colormap_coolwarm(): @requires_application() def test_colormap_CubeHelix(): """Test colormap support using cubehelix colormap in only blues""" + from vispy.color.colormap import CubeHelixColormap with TestingCanvas(size=size, bgcolor='w') as c: idata = np.linspace(255, 0, size[0]*size[1]).astype(np.ubyte) data = idata.reshape((size[0], size[1])) - image = Image(cmap=get_colormap('cubehelix', rot=0, start=0), + cmap = CubeHelixColormap(rot=0, start=0) + image = Image(cmap=cmap, clim='auto', parent=c.scene) image.set_data(data) assert_image_approved(c.render(), "visuals/colormap_cubehelix.png")
Some colormaps in the `get_colormaps` dictionary are not Colormap instances If I recall correctly this was added by @larsoner. In `vispy/color/colormap.py` there is a `_colormaps` dictionary that can be accessed via the public `get_colormaps()`. However, as a user, I expect this dictionary to map colormap names to colormap instances, some of these values though are colormap classes or functions. For example, `cubehelix -> CubeHelixColormap` and `single_hue -> _SingleHue`. This is "worked around" by having the `get_colormap` function create these colormaps with optional kwargs passed to the class. I'm not a huge fan of this so unless someone can argue for this behavior I would like to propose that we replace these non-instance colormaps with basic instances or remove them from the colormap dictionary returned from `get_colormaps`.
fine by me @djhoese I can have a look early next week. Here is a copy of the raw dictionary: <details> ``` _colormaps = dict( # Some colormap presets autumn=Colormap([(1., 0., 0., 1.), (1., 1., 0., 1.)]), blues=Colormap([(1., 1., 1., 1.), (0., 0., 1., 1.)]), cool=Colormap([(0., 1., 1., 1.), (1., 0., 1., 1.)]), greens=Colormap([(1., 1., 1., 1.), (0., 1., 0., 1.)]), reds=Colormap([(1., 1., 1., 1.), (1., 0., 0., 1.)]), spring=Colormap([(1., 0., 1., 1.), (1., 1., 0., 1.)]), summer=Colormap([(0., .5, .4, 1.), (1., 1., .4, 1.)]), fire=_Fire(), grays=_Grays(), hot=_Hot(), ice=_Ice(), winter=_Winter(), light_blues=_SingleHue(), orange=_SingleHue(hue=35), viridis=Colormap(ColorArray(_viridis_data)), # Diverging presets coolwarm=Colormap(ColorArray( [ (226, 0.59, 0.92), (222, 0.44, 0.99), (218, 0.26, 0.97), (30, 0.01, 0.87), (20, 0.3, 0.96), (15, 0.5, 0.95), (8, 0.66, 0.86) ], color_space="hsv" )), PuGr=_Diverging(145, 280, 0.85, 0.30), GrBu=_Diverging(255, 133, 0.75, 0.6), GrBu_d=_Diverging(255, 133, 0.75, 0.6, "dark"), RdBu=_Diverging(220, 20, 0.75, 0.5), # Configurable colormaps cubehelix=CubeHelixColormap, single_hue=_SingleHue, hsl=_HSL, husl=_HUSL, diverging=_Diverging, RdYeBuCy=_RedYellowBlueCyan, ) ``` </details> And visuals like `ImageVisual` typically run `get_colormap(cmap)` when a user does `my_img.cmap = 'cubehelix'` which will automatically generate the *instance* of the colormap. I've a suggestion. If the colormap is not in the `_colormaps` dictionary and if matplotlib is installed, it might be interesting to build the colormap with Matplotlib? Something like : ```python if (cmap not in _colormaps) and has_mpl: from matplotlib import cm # Get the list of implemented colormaps in Matplotlib : full_mpl_cmaps = list(cm.datad.keys()) + list(cm.cmaps_listed.keys()) if cmap not in full_mpl_cmaps: raise ValueError("%s colormap not in matplotlib" % cmap) sc = cm.ScalarMappable(cmap=cmap) x = np.arange(256) cmap_vec = np.array(sc.to_rgba(x, alpha=1.)) return Colormap(cmap_vec) ``` @EtienneCmb Now that vispy supports texture-based colormaps this should be a lot easier. If you want to make a pull request for this I'd be ok with that. If mpl colormaps need more than 256 colors we can do that too (ex. viridis).
2021-06-11T18:32:27
vispy/vispy
2,092
vispy__vispy-2092
[ "1871" ]
a53bcb458d1dd30947eb4a1cbdd558e7401a324e
diff --git a/examples/demo/gloo/realtime_signals.py b/examples/demo/gloo/realtime_signals.py --- a/examples/demo/gloo/realtime_signals.py +++ b/examples/demo/gloo/realtime_signals.py @@ -155,6 +155,7 @@ def on_timer(self, event): self.program['a_position'].set_data(y.ravel().astype(np.float32)) self.update() + self.context.flush() # prevent memory leak when minimized def on_draw(self, event): gloo.clear() diff --git a/examples/demo/scene/scrolling_plots.py b/examples/demo/scene/scrolling_plots.py --- a/examples/demo/scene/scrolling_plots.py +++ b/examples/demo/scene/scrolling_plots.py @@ -41,6 +41,7 @@ def update(ev): data = np.random.normal(size=(N, m), scale=0.3) data[data > 1] += 4 lines.roll_data(data) + canvas.context.flush() # prevent memory leak when minimized timer = app.Timer(connect=update, interval=0) timer.start()
memory surge after minimizing the vispy window Hi, thank you very much for working on vispy. Recently, I found a bug related to memory consumption. It appears after minimizing the vispy window, with a memory surge rate of about 50 MB/second. This surge doesn't exist even if you bring other programs to the top level. The only way to trigger it, based on my experience so far, is to minimize the window by either clicking the "Minimize" icon on the window or the taskbar icon of the vispy window. Please try the two scripts provided in the Examples folder in the vispy github: Examples\demo\scene\scrolling_plots.py and Examples\demo\gloo\realtime_signals.py Below is my environment: OS: Windows 10 ver.1909 Python: 3.8.3 vispy: 0.6.4 or github master pyqt5: 5.14.2 Thanks! Appreciate the help.
That's...crazy. I got the same results when running the scrolling_plots.py example on my Ubuntu machine with Python 3.7. What seems to be the (obvious?) problem is that vispy, while being minimized, is telling the GPU to update with new data but since the window isn't visible the GPU isn't drawing it or PyQt5 is building up a queue of draws (or drawing events) and they're filling up memory. Not really sure how to tackle this one. We might need to figure out first whether this is PyQt5 only or if this happens with other backends. Another thing to check would be to find out what is actually filling up memory. I did a quick test of changing the scrolling lines timer to a 5 second update interval and the memory increase is still there just much slower. Thanks, David, for quick responses. Just tried app.use() to change backends for the app. No surge for glfw and pyglet, but not for pyqt5. So, it's related to pyqt, which unfortunately is mandatory in my software. Could anyone fix the problem with pyqt5 backend? With pyqt5, it also uses much higher cpu as well. In my case, pyqt5 consumes 8.5% cpu, but pyglte only consumes 1.5% cpu. All these cpu tests were performed with the vispy window visible on the top. > Could anyone fix the problem with pyqt5 backend? So far based on your tests and my own tests I don't see anything that says this is something we (vispy) can fix ourselves. It's possible this is something in PyQt5 that we don't have control over. That said, I'm sure we can come up with a workaround. In your application, are you seeing this because you have a timer that is updating the visuals? Do you have the option to *not* update the visuals if you detect that the window is minimized? Regardless, someone (not sure I'll have time right now) could try playing with PyQt's process events (processEvents) in specific places in the timer function or in the backend to see if this fixes the issue. I wonder if telling Qt "I don't care that we aren't being shown, keep drawing stuff". There may be other Qt flags that control this logic so processEvents wouldn't be needed. I did playing with processEvents in the timer, but it didn't work out in the end. Currently, as you said, vispy updates are disabled once the window is minimized. Thanks.
2021-06-22T09:16:25
vispy/vispy
2,100
vispy__vispy-2100
[ "2097" ]
99d04d20902aed96aeea13aec8e44979668112d4
diff --git a/vispy/scene/widgets/grid.py b/vispy/scene/widgets/grid.py --- a/vispy/scene/widgets/grid.py +++ b/vispy/scene/widgets/grid.py @@ -462,19 +462,15 @@ def _update_child_widget_dim(self): # we only need to remove and add the height and width constraints of # the solver if they are not the same as the current value - if abs(rect.height - self._var_h.value()) > 1e-4: - # if self._height_stay: - # self._solver.remove_constraint(self._height_stay) - + h_changed = abs(rect.height - self._var_h.value()) > 1e-4 + w_changed = abs(rect.width - self._var_w.value()) > 1e-4 + if h_changed: self._solver.suggestValue(self._var_h, rect.height) - # self._height_stay = self._solver.add_stay(self._var_h | 'strong') - - if abs(rect.width - self._var_w.value()) > 1e-4: - # if self._width_stay: - # self._solver.remove_constraint(self._width_stay) + if w_changed: self._solver.suggestValue(self._var_w, rect.width) - # self._width_stay = self._solver.add_stay(self._var_w | 'strong') + if h_changed or w_changed: + self._solver.updateVariables() value_vectorized = np.vectorize(lambda x: x.value())
Fix grid solver allowing for 0 sized widgets and causing errors As discussed in #2093 it seems there are random cases (hard to reproduce) that produce widgets in a Grid widget with 0 size. This results in the PanZoomCamera sometimes getting a scale of `0` which then fails later inside the STTransform/MatrixTransform work.
@djhoese Just guessing, a few lines below that change, there is a newly introduced if clause which compares a difference to be <1e-4. Could that cause this? Sorry, can't link the exact line atm. Thanks @kmuehlbauer. That will be the next thing I play with. I also see there are other places where the constraint is `>= 0`. @djhoese Looks like you had the right feeling. :+1: Oh, one is still running. Since this is intermittent, let's try rerunning it a couple times. This may be a solution if it passes a couple times (will have to wait for @almarklein to test locally since I still haven't been able to get it to fail here). I don't really like this solution though. It is simple and obvious, but I think it means that any checks in the Grid for "is the size of the widget 0? Ok, then don't draw it" which I think there is at least one instance of. I think the `if` statement you mentioned was added to avoid floating point equality issues. So it may not be an issue actually. So for the record `>= 1` passed once. ...twice. ...three time. Just tested these changes with my script. Sorry, still fails. But even with these fixes ... why does the height become so small in this example sometimes? ... mmm > But even with these fixes ... why does the height become so small in this example sometimes? ... mmm Yeah this is definitely a workaround and definitely not the root of the cause. I'm not sure if kiwisolver has some psuedo-random stuff going on inside that would make it provide different solutions to some constraints depending on this randomness. That's the only thing I can think of. Oh, except maybe a race condition between the size stuff and the window not being opened yet (and vispy's size properties being updated). Can you tell if when it fails it is on the first ".scale" call from the PanZoomCamera or after a couple of the Visuals/components have been initialized? Full traceback: ``` File "c:\dev\pylib\vispy\vispy\app\canvas.py", line 436, in show self._backend._vispy_set_visible(visible) File "c:\dev\pylib\vispy\vispy\app\backends\_qt.py", line 425, in _vispy_set_visible self.showNormal() File "c:\dev\pylib\vispy\vispy\app\backends\_qt.py", line 526, in event out = super(QtBaseCanvasBackend, self).event(ev) File "c:\dev\pylib\vispy\vispy\app\backends\_qt.py", line 526, in event out = super(QtBaseCanvasBackend, self).event(ev) File "c:\dev\pylib\vispy\vispy\app\backends\_qt.py", line 846, in paintGL self._vispy_canvas.events.draw(region=None) File "c:\dev\pylib\vispy\vispy\util\event.py", line 453, in __call__ self._invoke_callback(cb, event) File "c:\dev\pylib\vispy\vispy\util\event.py", line 469, in _invoke_callback cb(event) File "c:\dev\pylib\vispy\vispy\scene\canvas.py", line 218, in on_draw self._draw_scene() File "c:\dev\pylib\vispy\vispy\scene\canvas.py", line 267, in _draw_scene self.draw_visual(self.scene) File "c:\dev\pylib\vispy\vispy\scene\canvas.py", line 305, in draw_visual node.draw() File "c:\dev\pylib\vispy\vispy\scene\visuals.py", line 99, in draw self._visual_superclass.draw(self) File "c:\dev\pylib\vispy\vispy\visuals\visual.py", line 599, in draw if self._prepare_draw(view=self) is False: File "c:\dev\pylib\vispy\vispy\scene\widgets\grid.py", line 197, in _prepare_draw self._update_child_widget_dim() File "c:\dev\pylib\vispy\vispy\scene\widgets\grid.py", line 499, in _update_child_widget_dim widget.rect = Rect(x, y, width, height) File "c:\dev\pylib\vispy\vispy\util\frozen.py", line 17, in __setattr__ object.__setattr__(self, key, value) File "c:\dev\pylib\vispy\vispy\scene\widgets\widget.py", line 250, in rect self.events.resize() File "c:\dev\pylib\vispy\vispy\util\event.py", line 453, in __call__ self._invoke_callback(cb, event) File "c:\dev\pylib\vispy\vispy\util\event.py", line 471, in _invoke_callback _handle_exception(self.ignore_callback_errors, << caught exception here: >> File "c:\dev\pylib\vispy\vispy\util\event.py", line 469, in _invoke_callback cb(event) File "c:\dev\pylib\vispy\vispy\scene\cameras\panzoom.py", line 195, in viewbox_resize_event self.view_changed() File "c:\dev\pylib\vispy\vispy\scene\cameras\base_camera.py", line 437, in view_changed self._update_transform() File "c:\dev\pylib\vispy\vispy\scene\cameras\panzoom.py", line 291, in _update_transform self.tf_mat.matrix = self.transform.as_matrix().matrix File "c:\dev\pylib\vispy\vispy\visuals\transforms\linear.py", line 219, in as_matrix m.scale(self.scale) File "c:\dev\pylib\vispy\vispy\visuals\transforms\linear.py", line 445, in scale self.matrix = np.dot(self.matrix, scale) File "c:\dev\pylib\vispy\vispy\visuals\transforms\linear.py", line 401, in matrix self.shader_imap() File "c:\dev\pylib\vispy\vispy\visuals\transforms\linear.py", line 389, in shader_imap fn['inv_matrix'] = self.inv_matrix # uniform mat4 File "c:\dev\pylib\vispy\vispy\visuals\transforms\linear.py", line 407, in inv_matrix self._inv_matrix = np.linalg.inv(self.matrix) File "<__array_function__ internals>", line 5, in inv File "c:\pythons\python39\lib\site-packages\numpy\linalg\linalg.py", line 546, in inv ainv = _umath_linalg.inv(a, signature=signature, extobj=extobj) File "c:\pythons\python39\lib\site-packages\numpy\linalg\linalg.py", line 88, in _raise_linalgerror_singular raise LinAlgError("Singular matrix") ``` Look like its in the draw event. All visuals are created beforehand. How many iterations until it failed with both sets of `>= 1` changes? Is that at least more iterations than without the changes? Are you just running the scatter_histogram.py example in a loop? Or what does your script look like? I'll see if I can get it to fail. A summary of what we're seeing: 1. We know that the kiwisolver change is the problem. 2. We know that something is resulting in a matrix that can't be inverted: ```python matrix = np.array([[2.52820244e+01, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], [0.00000000e+00, 0.00000000e+00, 9.99999997e-07, 0.00000000e+00], [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.00000000e+00]]) np.linalg.inv(matrix) ``` I assume this is caused by a scale of 0. ### Next Steps I suppose the next step is to print out various things that the GridWidget is controlling (like sizes of the other widgets) and seeing what changes between iterations. Edit: Theoretically somewhere inbetween these steps: ``` File "c:\dev\pylib\vispy\vispy\scene\widgets\grid.py", line 197, in _prepare_draw self._update_child_widget_dim() File "c:\dev\pylib\vispy\vispy\scene\widgets\grid.py", line 499, in _update_child_widget_dim widget.rect = Rect(x, y, width, height) ``` With your original changing of two constraints it *seemed* to take more iterations for it to fail, but current `main` now also seem to take more iters than before. Might just be the alignment of the moon or something. With the additional two constraints changed, I ran over 800 iters without getting an error, so I'm pretty sure that fixes the issue (well, avoids the error, anyway). I run basically the scatter example in a loop yes: <details> import numpy as np import vispy.plot as vp iter = 0 while True: iter += 1 print(f"iter {iter}") np.random.seed(2324) n = 100000 data = np.empty((n, 2)) lasti = 0 for i in range(1, 20): nexti = lasti + (n - lasti) // 2 scale = np.abs(np.random.randn(2)) + 0.1 scale[1] = scale.mean() data[lasti:nexti] = np.random.normal(size=(nexti-lasti, 2), loc=np.random.randn(2), scale=scale / i) lasti = nexti data = data[:lasti] color = (0.3, 0.5, 0.8) n_bins = 100 fig = vp.Fig(show=False) line = fig[0:4, 0:4].plot(data, symbol='o', width=0, face_color=color + (0.02,), edge_color=None, marker_size=4) line.set_gl_state(depth_test=False) fig[4, 0:4].histogram(data[:, 0], bins=n_bins, color=color, orientation='h') fig[0:4, 4].histogram(data[:, 1], bins=n_bins, color=color, orientation='v') fig.show() </details> This is what the example looks like (normally). Those margins seem a little big to me. ![image](https://user-images.githubusercontent.com/3015475/123163286-d7b09900-d471-11eb-8ee1-c6de9e434f07.png) Reminder that during this switch to kiwisolver one of the tests failed because suddenly `.padding` (and maybe `.margin`) were being respected. Ok so I added a print on line 499 of grid.py with `print(x, y, width, height)` and I was able to get failures. https://github.com/vispy/vispy/blob/89e83cabea4e0e6ae08df5012985e816009924aa/vispy/scene/widgets/grid.py#L498-L502 This is what I got on one run: ``` iter 66 102.0 41.0 456.9999999999982 297.99999999999994 102.0 41.0 456.99999999999966 20.0 70.50000000000001 41.0 34.25000000000001 297.99999999999994 iter 67 102.0 41.0 456.9999999999982 297.99999999999994 102.0 41.0 456.99999999999966 19.999999999999996 70.50000000000003 41.0 34.25 297.99999999999994 iter 68 102.0 41.0 456.9999999999982 297.99999999999994 102.0 41.0 456.99999999999875 20.0 70.50000000000001 41.0 34.25000000000001 297.99999999999994 iter 69 102.0 41.0 456.9999999999982 297.99999999999994 102.0 41.0 456.99999999999955 0.0 <traceback> ``` On my system, this happens from the `fig.show()` call. Note how the failure happens when the second `widget` is being updated (there is no third entry). Note that the last value (height) is `0.0`. Also notice that for the previous iterations the precision of some of the values changes. My guess is this is why that `if` statement @kmuehlbauer brought up had to be changed from a regular `!=` to `(y - x) > epsilon`. I hope to end my day now so I probably won't look at this much more. Tomorrow...we finish this. :crossed_swords:
2021-06-24T02:34:53
vispy/vispy
2,110
vispy__vispy-2110
[ "2107" ]
184d854c7542f4c6df21bb4c7db3dd5b340dd900
diff --git a/vispy/scene/widgets/widget.py b/vispy/scene/widgets/widget.py --- a/vispy/scene/widgets/widget.py +++ b/vispy/scene/widgets/widget.py @@ -50,7 +50,7 @@ def __init__(self, pos=(0, 0), size=(10, 10), border_color=None, self._mesh.set_gl_state('translucent', depth_test=False, cull_face=False) self._picking_mesh = MeshVisual(mode='triangle_fan') - self._picking_mesh.set_gl_state(cull_face=False) + self._picking_mesh.set_gl_state(cull_face=False, depth_test=False) self._picking_mesh.visible = False # reserved space inside border diff --git a/vispy/visuals/mesh.py b/vispy/visuals/mesh.py --- a/vispy/visuals/mesh.py +++ b/vispy/visuals/mesh.py @@ -358,9 +358,6 @@ def _prepare_draw(self, view): return False self._data_changed = False - def draw(self, *args, **kwds): - Visual.draw(self, *args, **kwds) - @staticmethod def _prepare_transforms(view): tr = view.transforms.get_transform()
diff --git a/vispy/scene/tests/test_canvas.py b/vispy/scene/tests/test_canvas.py --- a/vispy/scene/tests/test_canvas.py +++ b/vispy/scene/tests/test_canvas.py @@ -60,3 +60,31 @@ def test_canvas_render(blend_func): else: # the alpha should have some transparency assert (rgba_result[..., 3] != 255).any() + + +@requires_application() +def test_picking_basic(): + """Test basic picking behavior. + + Based on https://github.com/vispy/vispy/issues/2107. + + """ + with TestingCanvas(size=(125, 125), show=True, title='run') as c: + view = c.central_widget.add_view() + view.margin = 5 # add empty space where there are no visuals + view.camera = 'panzoom' + + x = np.linspace(0, 400, 100) + y = np.linspace(0, 200, 100) + line = scene.Line(np.array((x, y)).T.astype(np.float32)) + line.interactive = True + view.add(line) + view.camera.set_range() + + c.render() # initial basic draw + for _ in range(2): # run picking twice to make sure it is repeatable + # get Visuals on a Canvas point that Line is drawn on + picked_visuals = c.visuals_at((100, 25)) + assert len(picked_visuals) == 2 + assert any(isinstance(vis, scene.ViewBox) for vis in picked_visuals) + assert any(isinstance(vis, scene.Line) for vis in picked_visuals)
Picking broken (visual_at) While testing current main I've found that the picking example doesn't work anymore. examples/demo/scene/picking.py @djhoese just confirmed on gitter chat, that it doesn't work for him too. I'll try to bisect this tomorrow, but if anyone is faster, please do so.
So I could be doing something wrong, but this example doesn't seem to work for me on the `maint/0.6` branch either. Tag v0.6.2 works, v0.6.3 doesn't I can't remember which version worked. But I know it worked at some point in time, because I've adapted from that example for one of my applications. Unfortunately it got lost, was not used for years now. https://github.com/vispy/vispy/pull/1748 broke it. Still debugging... CC @tlambert03 Yep, if I manually revert the `plotwidget.py` changes in that PR to what they were before then it works. @djhoese I'm not that fast on the phone, but this is also my impression. The viewbox somehow overlays all other added plots. Strange... ugh :/ bummer... does https://github.com/vispy/vispy/issues/1742 come back then? @tlambert03 Your fix is still there so I would assume not. My guess is that something with picking is assuming that the viewbox is early in the list of children which is the opposite of what you needed in #1748 since the sizing has to be bottom-up to work properly...if I remember correctly. Still debugging to see what the different ordering changes as far as picking. Record keeping... If you run `self._scene.describe_tree()` from the SceneCanvas, you get this in the old code: ``` SubScene +--Widget +--Grid +--PlotWidget +--Grid +--Widget +--Widget +--Widget +--Label +--Widget +--Widget +--Label +--AxisWidget +--ViewBox | +--SubScene | +--BaseCamera | +--PanZoomCamera | +--LinePlot | +-- <... lots of LinePlot instances> | +--LinePlot | +--Text | +--Line | +--Markers +--AxisWidget +--Widget +--Label +--Widget ``` I just wanted to show what the order of things is. Edit: In the old code (0.6.2) when doing the picking the picking sees all of the various things on the canvas. In the new method it *only* sees the ViewBox. This is strange to me as I would assume that since the LinePlots are children of the ViewBox they would be "understood" during picking. Ok, very interesting findings now. Things to notice about this situation: 1. The `_configure_2d` method is called separately (before) the LinePlot Visual is created and added to the view. So as far as the ViewBox <-> LinePlot relationship, nothing should be different. 2. The ViewBox is being added to a GridWidget. The GridWidget doesn't do anything ordering specific as far as I can tell. It just resizes things. 3. If I move the view box creation before the `xlabel` `Label` creation in `_configure_2d` then it works. If I move it after that it fails. **BUT** if I comment out the `self.xlabel` usage it doesn't work whether I create the view right before the label code or right after. :shrug: Workaround: set `self.view.interactive = False` in the `_configure_2d` method. There could be some unexpected side effects that I'm missing here, but here's some things we should know: 1. Setting `self.view.interactive = False` and having it works means that the `PickingFilter` is being used and applied properly. 2. The fact that what widgets are created and in what order suggests that the issue is the GridWidget or some of these other widgets blocking something. BUT this doesn't really make sense because the ViewBox is still the thing getting selected/picked, not one of these other widgets. It is like the ViewBox drawing (it draws its picking mesh) is somehow getting drawn before the children (the LinePlot visuals), but this, again, shouldn't be effected by the GridWidget and when widgets are added. Edit: I forgot to add that I printed out the drawing order and as far as I can tell it is the same (or as similar as can be expected given the different order of children being added to the grid). Ok major discovery: If you comment out the `on_mouse_move` handler in the picking example script then it finds things just fine. Edit: Ok if you comment out the `cursor_text` stuff then it mostly works except only on every other click. This is really weird. Current minimal reproducible example: ```python import numpy as np import vispy.plot as vp # create figure with plot fig = vp.Fig() plt = fig[0, 0] # plot data x = np.linspace(0, 400, 100) y = np.linspace(-144.1, -9.44, 100) line = plt.plot((x, y), color='red') line.interactive = True fig._plot_widgets[0].view.order = -5 fig.app.process_events() print("Selected: ", fig.visuals_at((201, 411))) ``` I'm going to try to make this even smaller and remove the PlotWidget from the situation. If you comment out the `view.order` it doesn't work and you should see only the ViewBox in the print out. If you leave it uncommented (the ViewBox is drawn before the other Fig components - axis, labels, colorbar widgets, etc) then you should see two elements in the print out; the ViewBox and the LinePlot. This seems to make the picking work in the original example: ```diff diff --git a/vispy/visuals/line/line.py b/vispy/visuals/line/line.py index f709949f..1fa01df4 100644 --- a/vispy/visuals/line/line.py +++ b/vispy/visuals/line/line.py @@ -299,7 +299,7 @@ class _GLLineVisual(Visual): Visual.__init__(self, vcode=self.VERTEX_SHADER, fcode=self.FRAGMENT_SHADER) - self.set_gl_state('translucent') + # self.set_gl_state('translucent') def _prepare_transforms(self, view): xform = view.transforms.get_transform() diff --git a/vispy/visuals/markers.py b/vispy/visuals/markers.py index bf7f07ec..54fb0e27 100644 --- a/vispy/visuals/markers.py +++ b/vispy/visuals/markers.py @@ -496,8 +496,8 @@ class MarkersVisual(Visual): Visual.__init__(self, vcode=vert, fcode=frag) self.shared_program.vert['v_size'] = self._v_size_var self.shared_program.frag['v_size'] = self._v_size_var - self.set_gl_state(depth_test=True, blend=True, - blend_func=('src_alpha', 'one_minus_src_alpha')) + # self.set_gl_state(depth_test=True, blend=True, + # blend_func=('src_alpha', 'one_minus_src_alpha')) self._draw_mode = 'points' if len(kwargs) > 0: self.set_data(**kwargs) ``` Thanks @asnt I'll test that out. From my findings it seems to be something related to drawing order and likely the TextVisual. I also saw something related to `set_gl_state` (or `configure_gl_state` which is what TextVisual uses), but couldn't nail down what was going on. Here is my new minimal example: ```python import numpy as np from vispy import scene canvas = scene.SceneCanvas() grid = canvas.central_widget.add_grid() yaxis = scene.Label("") # yaxis = scene.Widget() yaxis_widget = grid.add_widget(yaxis, row=2, col=3) yaxis_widget.width_max = 40 view = grid.add_view(row=2, col=4, border_color='grey', bgcolor="#efefef") view.camera = 'panzoom' camera = view.camera # plot data x = np.linspace(0, 400, 100) y = np.linspace(-144.1, -9.44, 100) line = scene.LinePlot((x, y)) line.interactive = True view.add(line) view.camera.set_range() view.order = -5 # view.interactive = False canvas.show() canvas.app.process_events() print("Picked IDs: ", np.unique(canvas._render_picking((0.0, 0.0, 800, 600)))) print("Picked IDs: ", np.unique(canvas._render_picking((0.0, 0.0, 800, 600)))) from vispy.scene import VisualNode # print(list(VisualNode._visual_ids.items())) ``` The print out is a series of IDs. In the first print out with the `view.order` set you should see three IDs. `0` means no visual there, one of the others is the ViewBox, and one of the others is the LinePlot. This is all of the IDs the rendered picking is seeing when drawing the whole Scene. Not that in the second print out the LinePlot disappears. Also notice that if you replace the Label with a plain Widget that it doesn't work. @asnt Nice find on that gl_state stuff. If I remove (comment out) the `view.order` line in my above example and comment out the `set_gl_state` for the Markers and Line visuals then both print outs show all the expected IDs (3 total). Edit: Simplification to the above, change the LinePlot line to: ```python line = scene.Line(np.array((x, y)).T.astype(np.float32)) ``` Edit 2: It looks like commenting out the `Line` `set_gl_state` makes the `Widget` versus `Label` case work too. Now I'm just really confused, even this doesn't work without commenting out the `set_gl_state` for the LineVisual: ```python import numpy as np from vispy import scene canvas = scene.SceneCanvas() view = canvas.central_widget.add_view() view.camera = 'panzoom' camera = view.camera x = np.linspace(0, 400, 100) y = np.linspace(-144.1, -9.44, 100) line = scene.Line(np.array((x, y)).T.astype(np.float32)) line.interactive = True view.add(line) view.camera.set_range() # view.order = -5 canvas.show() canvas.app.process_events() print("Picked IDs: ", np.unique(canvas._render_picking((0.0, 0.0, 800, 600)))) print("Picked IDs: ", np.unique(canvas._render_picking((0.0, 0.0, 800, 600)))) ``` This change alone (without the previous diff) also makes it work (without looking at whether it breaks the rendering): ```diff diff --git a/vispy/scene/visuals.py b/vispy/scene/visuals.py index 0147f17b..c4bcef30 100644 --- a/vispy/scene/visuals.py +++ b/vispy/scene/visuals.py @@ -68,6 +68,7 @@ class VisualNode(Node): self._picking = p self._picking_filter.enabled = p self.update_gl_state(blend=not p) + self.update_gl_state(depth_test=False) def _update_trsys(self, event): """Transform object(s) have changed for this Node; assign these to the ``` Note: Not related to the issue here, but I have the impression that `self.update_gl_state(blend=not p)` makes the assumption that we always have `blend=True` when not picking. Isn't that a bit strong an assumption? Or the visuals always reset the state, so it doesn't matter? > Isn't that a bit strong an assumption? Or the visuals always reset the state, so it doesn't matter? Yes, I think it is a strong assumption although not a bad one given how many vispy visuals use blending perhaps. It also doesn't seem like something that would be that hard to workaround (use the current blending state and change it depending on that if needed). Also, visuals typically don't re-assert their GL state. Only on `__init__`. Pushing the ViewBox that always get picked further back also helps: ```diff diff --git a/vispy/scene/widgets/widget.py b/vispy/scene/widgets/widget.py index a1c44dd7..9e85b193 100644 --- a/vispy/scene/widgets/widget.py +++ b/vispy/scene/widgets/widget.py @@ -377,6 +377,10 @@ class Widget(Compound): [right, top], [right-w, top-w], [left, top], [left+w, top-w], ], dtype=np.float32) + if self.__class__.__name__ == "ViewBox": + z_behind = 1.0 + pos_z = np.full((len(pos), 1), z_behind, dtype=np.float32) + pos = np.hstack((pos, pos_z)) faces = np.array([ [0, 2, 1], [1, 2, 3], ``` Ok so based on these recent "GL state" discoveries I feel like it makes sense then there is some conflict between the GL state desired by some Visuals/Widgets and those of others. That's why in my testing I was able to get it to work by reordering the draw order. I want to make sure that however we solve this that we at least *know* why it is not working even if we end up having to implement a workaround rather than a "real" solution. Here's what I get for what widgets/visuals are made and what GL state they attempt to make by running my Line script above. These sections are in order of creation (from what I can tell). ## Regular Draw ### `SceneCanvas.central_widget` - `Widget` The base `Widget` class makes two MeshVisuals: https://github.com/vispy/vispy/blob/184d854c7542f4c6df21bb4c7db3dd5b340dd900/vispy/scene/widgets/widget.py#L49-L54 Mesh 1 (border): `{'depth_test': False, 'cull_face': False, 'preset': 'translucent'}` Mesh 2 (picking): ` {'depth_test': True, 'cull_face': False, 'preset': 'translucent'}` Note the picking mesh isn't drawn during regular draw, but the configuration is still "attempted" during creation. ### `ViewBox` - `Widget subclass` Same as `Widget` above ### `Line` `{'preset': 'translucent'}` There's some line smoothing stuff later on, but not relevant here. Also see #2109. ## Final Regular Draw GL State `{'depth_test': True, 'cull_face': False, 'blend': True, 'blend_func': ('src_alpha', 'one_minus_src_alpha', 'zero', 'one')}` ## Picking draw Basically blend is set to False. This fails and only "sees" the ViewBox. ### Picking Mesh from ViewBox GL state: `{'cull_face': False, 'blend': False}` ### LineVisual GL state: `{'line_smooth': False, 'line_width': 1.0, 'blend': False, 'depth_test': True, 'cull_face': False, 'blend_func': ('src_alpha', 'one_minus_src_alpha', 'zero', 'one')}` If I comment out the LineVisual's state configuration then we get: GL state: `{'line_smooth': False, 'line_width': 1.0, 'blend': False}` and the proper picked IDs. ## Depth testing for the win It seems like if I add `depth_test=False` to the picking mesh then this all works: https://github.com/vispy/vispy/blob/184d854c7542f4c6df21bb4c7db3dd5b340dd900/vispy/scene/widgets/widget.py#L52-L53 It is getting late here so I may not make much sense with this explanation, but I'm not sure I understand how this ever works or worked. If I run the original `picking.py` example and move the ViewBox creation between the 2 places I don't see an obvious useful difference. That must mean (I think) that drawing order is just "getting lucky". So is `depth_test=False` on the picking mesh the right answer? :shrug: Edit: The last time a depth_test or other GL state change was made was in https://github.com/vispy/vispy/pull/1191 to fix some plotting issue in an example if I remember, but this was only for Markers. The depth_test was changed from False to True which would negatively effect the picking...I guess. Nice analysis! Nice find with #1191: Reverting it (back to `depth_test=False`) indeed makes the picking example work. EDIT: Sorry, I just read #2109 and it seems you are well aware @djhoese . I missed this one. EDIT2: Removed my suggestion because you had it all in your analysis. I was just repeating it. Now, I think I understand and I follow you. :+1: :+1: :+1: Yes! I was just about to post about this. I have a better understanding of this now. And I think my last comment was 50% "I don't know when GL state is changed" and 50% "oh this is how it works" so it got extra confusing. I'll make another comment in a second with my findings. For today's novel...ok so I have a slightly better understanding of why some cases worked and some didn't. I think this has only worked by chance most of the time. Here's what I see if I print out information about the GL state as my [LinePlot example](https://github.com/vispy/vispy/issues/2107#issuecomment-869056283). ``` From the regular draw: About to call _configure_gl_state from Visual.draw: <vispy.visuals.mesh.MeshVisual object at 0x7f97bc40c910> GL state: {'depth_test': False, 'cull_face': False, 'blend': True, 'blend_func': ('src_alpha', 'one_minus_src_alpha', 'zero', 'one')} About to call _configure_gl_state from Visual.draw: <vispy.visuals.line.line._GLLineVisual object at 0x7f97bc401450> GL state: {'depth_test': True, 'cull_face': False, 'blend': True, 'blend_func': ('src_alpha', 'one_minus_src_alpha', 'zero', 'one')} About to call _configure_gl_state from Visual.draw: <vispy.visuals.markers.MarkersVisual object at 0x7f97bc3a0ed0> GL state: {'depth_test': True, 'blend': True, 'blend_func': ('src_alpha', 'one_minus_src_alpha')} About to call _configure_gl_state from Visual.draw: <vispy.visuals.text.text.TextVisual object at 0x7f97bc48da50> GL state: {'blend': True, 'depth_test': False, 'cull_face': False, 'blend_func': ('src_alpha', 'one_minus_src_alpha')} When it works and we use a Label widget, we get these GL states: About to call _configure_gl_state from Visual.draw: <vispy.visuals.mesh.MeshVisual object at 0x7f97bc4848d0> GL state: {'cull_face': False, 'blend': False} About to call _configure_gl_state from Visual.draw: <vispy.visuals.line.line._GLLineVisual object at 0x7f97bc401450> GL state: {'line_smooth': False, 'line_width': 1.0, 'blend': False, 'depth_test': True, 'cull_face': False, 'blend_func': ('src_alpha', 'one_minus_src_alpha', 'zero', 'one')} About to call _configure_gl_state from Visual.draw: <vispy.visuals.markers.MarkersVisual object at 0x7f97bc3a0ed0> GL state: {'depth_test': True, 'blend': False, 'blend_func': ('src_alpha', 'one_minus_src_alpha')} The second time we call the picking: About to call _configure_gl_state from Visual.draw: <vispy.visuals.mesh.MeshVisual object at 0x7f97bc4848d0> GL state: {'cull_face': False, 'blend': False} About to call _configure_gl_state from Visual.draw: <vispy.visuals.line.line._GLLineVisual object at 0x7f97bc401450> GL state: {'line_smooth': False, 'line_width': 1.0, 'blend': False, 'depth_test': True, 'cull_face': False, 'blend_func': ('src_alpha', 'one_minus_src_alpha', 'zero', 'one')} About to call _configure_gl_state from Visual.draw: <vispy.visuals.markers.MarkersVisual object at 0x7f97bc3a0ed0> GL state: {'depth_test': True, 'blend': False, 'blend_func': ('src_alpha', 'one_minus_src_alpha')} ``` Things to note: 1. After the regular draw `depth_test` is `False` because of the `TextVisual`. This state doesn't change when the picking mesh is drawn in the next step (more on that later). 2. After the first picking, the MarkersVisual leaves `depth_test` as `True`. This state doesn't change when the picking mesh is drawn in the next step. So during the second picking the picking mesh is drawn with `depth_test` as `True`. This is why the second picking call doesn't behave as expected. 3. The picking mesh's state is only ever set as `{'cull_face': False, 'blend': False}`. This is because after it is created with `self.set_gl_state('translucent', depth_test=True, cull_face=False)` in `__init__`, the `Widget` class does `self._picking_mesh.set_gl_state(cull_face=False)`. **BUT** `gl_state` doesn't just update one parameter and keep all the old ones that were in the state. It overwrite this. The other similar issue is that if you use a preset name once, you need to use it every time if you want those preset values to be included in the GL state for this visual. This means that the depth testing and other GL state parameters for the picking mesh are completely dependent on the previously drawn visual. Since the ViewBox is usually the first thing drawn and it only draws the picking mesh during picking this means it is dependent on the last thing to be drawn from regular drawing. ### More on MarkersVisual One thing that's interesting to me is that I brought up in my previous comment that MarkersVisual was changed from `depth_test=False` to `depth_test=True`. If this change hadn't been done then my second picking in my example above would have worked as the MarkersVisual was the last thing drawn. Edit 2: Also note that MarkersVisual are included in every LinePlot entry as it is a Compound of a LineVisual and a MarkersVisual. It may not be drawn, but its GL state is still configured. ### Best fix I'd say the picking mesh should either be re-configured after creation (in `Widget.__init__`) with: ```python self._picking_mesh.set_gl_state('translucent', depth_test=False, cull_face=False) ``` Or maybe: ```python self._picking_mesh.set_gl_state(depth_test=False, cull_face=False) ``` Thoughts? Edit: Put another way, I think it should be considered best practice to specify all parameters (or a preset) when you change/set/update GL state. This will technically effect performance as it means more GLIR commands which means more GL calls, but otherwise I think you are dependent on the order that you draw things in and what those other things set for GL state. > 2. After the first picking, the MarkersVisual leaves `depth_test` as `True`. This state doesn't change when the picking mesh is drawn in the next step. So during the second picking the picking mesh is drawn with `depth_test` as `True`. This is why the second picking call doesn't behave as expected. I have the impression that the root cause of this is that the `Widget.picking_mesh` of the `ViewBox` (derived of `Widget`) is covering the entire viewport. So, when `depth_test=True` in picking mode, the viewbox, drawn first, prevents the child visuals to be drawn, because they are all at the same depth and the entire depth buffer has already been written to by the view box. In this 2D plotting context, if the end goal is that the foreground visuals (lines, markers...) be over the background (viewbox), it seems to me that there can be several strategies: 1. (The intended current one?) Set `depth_test=False` and draw the visuals from furthest to closest (~~using `.order`~~ EDIT: See below.). (The actual depth position of the visuals, if any, has no effect.) 2. Set `depth_test=True` and draw the visuals from closest to furthest (~~using `.order`~~ EDIT: See below.). (Assuming a common depth position for all visuals.) 3. Arrange the visuals in foreground/background layers with different `z` values, e.g. `pos=(x, y, z0)`, `pos=(x, y, z1)`.... Render with `depth_test=True`. The drawing order has no effect. EDIT: Drawing order in strategy 1. EDIT2: Revert incorrect first edit and add strategy 2. EDIT3: Actually `.order` is not enough because it represents the order between the children of a single node (at a single level of the hierarchy), not an absolute order in the scene. So, only strategy 1 would work if the child visuals are always more into the foreground. Strategy 2 seems difficult to implement (if at all possible) with the current scene graph and picking models. > Edit 2: Also note that MarkersVisual are included in every LinePlot entry as it is a Compound of a LineVisual and a MarkersVisual. It may not be drawn, but its GL state is still configured. Shouldn't the `self._configure_gl_state()` call come after the next `if` block, to not unnecessarily send glir commands: https://github.com/vispy/vispy/blob/184d854c7542f4c6df21bb4c7db3dd5b340dd900/vispy/visuals/visual.py#L439-L444 EDIT: Already being addressed in #2109. Sorry. > I'd say the picking mesh should either be re-configured after creation (in `Widget.__init__`) with: > > ```python > self._picking_mesh.set_gl_state('translucent', depth_test=False, cull_face=False) > ``` > > Or maybe: > > ```python > self._picking_mesh.set_gl_state(depth_test=False, cull_face=False) > ``` It seems like the adequate fix to me. The second one seems sufficient because `blending=False` is taken care of by the picking logic, and `blend_func` doesn't matter then). Also, to me this assumes strategy one above. Right? > The second one seems sufficient because blending=False is taken care of by the picking logic, and blend_func doesn't matter then). Oh good point. At that point there aren't any unspecified settings. I think you've addressed any concerns I had with the z-position stuff. I think it just ends up being difficult to safely implement without telling the user they need to setup their SceneCanvas a certain way if they want picking to work. Some other things I want to point out: 1. I'm 99% sure the ViewBox doesn't take up the whole viewport. In my examples with the plotting API or where a GridWidget is used, the Visuals/Widgets that are not the ViewBox are not drawn during picking and show up as 0s. In one of my examples above the rendered picking array that I get the unique values for includes 0. When I view it in pycharm's debugger I see that it is a border of 0s. 2. The only reason these ViewBox's child Visuals are drawn during picking is because their `.interactive = True` property is set. Without this they are skipped for picking. 3. We should be able to assume (as it is how it is coded) that the ViewBox picking Mesh is always drawn before the children under the ViewBox. The other option I thought about would be along the lines of your Z-level stuff where we make the ViewBox picking mesh go all the way back; something like a max-z level so it is always behind everything else. However, I think this still depends on all of the other transforms and how the Visuals are set up. I guess I'll make a PR for `self._picking_mesh.set_gl_state(depth_test=False, cull_face=False)` and we'll see how the tests go and what other thoughts people have.
2021-06-27T20:46:52
vispy/vispy
2,111
vispy__vispy-2111
[ "2109" ]
184d854c7542f4c6df21bb4c7db3dd5b340dd900
diff --git a/vispy/visuals/visual.py b/vispy/visuals/visual.py --- a/vispy/visuals/visual.py +++ b/vispy/visuals/visual.py @@ -439,13 +439,14 @@ def _index_buffer(self, buf): def draw(self): if not self.visible: return - self._configure_gl_state() if self._prepare_draw(view=self) is False: return if self._vshare.draw_mode is None: raise ValueError("_draw_mode has not been set for visual %r" % self) + + self._configure_gl_state() try: self._program.draw(self._vshare.draw_mode, self._vshare.index_buffer)
LineVisual line smooth and width set after GL state is configured In #2082 @almarklein updated the line visual to call `self.update_gl_state` to change `line_smooth` and `line_width`. The problem is, as I just realized while debugging #2107, that `update_gl_state` doesn't have an immediate effect on GL state. Only when `Visual._configure_gl_state` does the lower-level `gloo.set_state` call get executed. That happens on every `Visual.draw` call *BUT* before `_prepare_draw` is called. `_prepare_draw` is when these line smooth/width changes happen. https://github.com/vispy/vispy/blob/184d854c7542f4c6df21bb4c7db3dd5b340dd900/vispy/visuals/visual.py#L442-L444
I'm kind of wondering if there are reasons GL state needs to be configured *before* `_prepare_draw`. I can only see `TextVisual` needing this, but it could run that manually if it really needs to. Right now this current behavior means that Visuals GL state is sent/configured on the GPU regardless of if its `_prepare_draw` thinks it should be drawn. > I'm kind of wondering if there are reasons GL state needs to be configured _before_ `_prepare_draw`. I can only see `TextVisual` needing this, but it could run that manually if it really needs to. Right now this current behavior means that Visuals GL state is sent/configured on the GPU regardless of if its `_prepare_draw` thinks it should be drawn. I was wondering the same. I don't see either why the state would need to be set when not drawing. Moving it down would also get rid of unnecessary glir commands. I think the one issue may be if the `_prepare_draw` was doing something that depended on the GL state, but I can't think of anything right now. TextVisual is a special case as I mentioned because it has the option of drawing the glyphs on the CPU or GPU and has to change the GL state to due that properly (based on what I saw in the code). @asnt or @almarklein if either of you want to make a PR that moves the configure call to below the `_prepare_draw` I'd be OK with that. I guess we could assume that if the tests pass then it is an OK change... :fearful:
2021-06-28T03:33:28
vispy/vispy
2,115
vispy__vispy-2115
[ "2114" ]
91430ea4cfa7abf57819b88416fdab51226a9b6b
diff --git a/vispy/visuals/volume.py b/vispy/visuals/volume.py --- a/vispy/visuals/volume.py +++ b/vispy/visuals/volume.py @@ -278,7 +278,7 @@ MIP_SNIPPETS = dict( before_loop=""" float maxval = -99999.0; // The maximum encountered value - int maxi = 0; // Where the maximum value was encountered + int maxi = -1; // Where the maximum value was encountered """, in_loop=""" if( val > maxval ) { @@ -287,13 +287,15 @@ } """, after_loop=""" - // Refine search for max value - loc = start_loc + step * (float(maxi) - 0.5); - for (int i=0; i<10; i++) { - maxval = max(maxval, $sample(u_volumetex, loc).r); - loc += step * 0.1; - } - gl_FragColor = applyColormap(maxval); + // Refine search for max value, but only if anything was found + if ( maxi > -1 ) {{ + loc = start_loc + step * (float(maxi) - 0.5); + for (int i=0; i<10; i++) { + maxval = max(maxval, $sample(u_volumetex, loc).r); + loc += step * 0.1; + } + gl_FragColor = applyColormap(maxval); + }} """, ) MIP_FRAG_SHADER = FRAG_SHADER.format(**MIP_SNIPPETS) @@ -326,7 +328,7 @@ MINIP_SNIPPETS = dict( before_loop=""" float minval = 99999.0; // The minimum encountered value - int mini = 0; // Where the minimum value was encountered + int mini = -1; // Where the minimum value was encountered """, in_loop=""" if( val < minval ) { @@ -335,13 +337,15 @@ } """, after_loop=""" - // Refine search for min value - loc = start_loc + step * (float(mini) - 0.5); - for (int i=0; i<10; i++) { - minval = min(minval, $sample(u_volumetex, loc).r); - loc += step * 0.1; - } - gl_FragColor = applyColormap(minval); + // Refine search for min value, but only if anything was found + if ( mini > -1 ) {{ + loc = start_loc + step * (float(mini) - 0.5); + for (int i=0; i<10; i++) { + minval = min(minval, $sample(u_volumetex, loc).r); + loc += step * 0.1; + } + gl_FragColor = applyColormap(minval); + }} """, ) MINIP_FRAG_SHADER = FRAG_SHADER.format(**MINIP_SNIPPETS)
`VolumeVisual` max/min intensity projection failure mode The `VolumeVisual` has an interesting failure mode in both maximum and minimum intensity projection modes highlighted by @brisvag in the following [comment](https://github.com/napari/napari/pull/2934/files/c5c96e2b5faa854600f3d65d68a2ae01f47d8c7a#r660050470) which includes a nice video If real maxima/minima are not found when the rays are cast, the value is searched for around `start_loc` of the ray anyway, causing the front faces of the cuboid to include some artefacts.
2021-06-29T14:25:38