def test_color(): """Basic tests for Color class""" x = Color('white') assert_array_equal(x.rgba, [1.] * 4) assert_array_equal(x.rgb, [1.] * 3) assert_array_equal(x.RGBA, [255] * 4) assert_array_equal(x.RGB, [255] * 3) assert_equal(x.value, 1.) assert_equal(x.alpha, 1.) x.rgb = [0, 0, 1] assert_array_equal(x.hsv, [240, 1, 1])
def set_color(self, label, rgb): if isinstance(rgb, six.string_types): rgb = Color(rgb).rgb self.layers[label]['color'] = np.asarray(rgb) self._update()
all_faces = faces all_strikes = strikes else: faces += all_verts.shape[0] all_verts = np.concatenate((all_verts, verts)) all_faces = np.concatenate((all_faces, faces)) all_strikes = np.concatenate((all_strikes, strikes)) fault_surface = Mesh(all_verts, all_faces, vertex_values=all_strikes, shading='smooth') fault_surface.cmap = fault_cmap fault_surface.clim = fault_range fault_surface.shininess = 0.01 fault_surface.ambient_light_color = Color([.2, .2, .2, 1]) fault_surface.light_dir = (5, -10, 5) visual_nodes = volume_slices(seismic_vol, cmaps=seismic_cmap, clims=seismic_range, interpolation='bilinear', **slicing) xyz_axis = XYZAxis() colorbar = Colorbar(cmap=fault_cmap, clim=fault_range, label_str='Fault Strike Angle', size=colorbar_size) canvas5 = SeismicCanvas(title='Fault Surfaces', visual_nodes=visual_nodes + [fault_surface],
Vispy has a few bugs/limitations that we're trying to overcome. First, it doesn't parse lists like [Color('red'), Color('red')]. Second, the color of 'g' and 'green' is different. We're consistent with vispy's behavior ATM, but it might change in a future release. """ import numpy as np from vispy.color import Color, ColorArray # Apparently there are two types of greens - 'g' is represented by a # (0, 1, 0) tuple, while 'green' has an approximate value of # (0, 0.5, 0). This is why these two colors are treated differently # below. REDA = (1.0, 0.0, 0.0, 1.0) RED = (1.0, 0.0, 0.0) REDF = '#ff0000' GREENV = Color('green').rgb[1] GREENA = (0.0, GREENV, 0.0, 1.0) GREEN = (0.0, GREENV, 0.0) GREENF = Color('green').hex REDARR = np.array([[1.0, 0.0, 0.0, 1.0]], dtype=np.float32) GREENARR = np.array([[0.0, GREENV, 0.0, 1.0]], dtype=np.float32) single_color_options = [ RED, GREENA, 'transparent', 'red', 'g', GREENF, '#ffccaa44', REDA,
def zbow_2d_plot(self, parent, scale, color, update=False, highlight_cells=None, highlight_color=False): new_window_position = parent.pos() if parent.was_closed: parent.show() if update: options = self.h_view_2d.camera.get_state() # get scale data: scale_list = ['custom', 'default', 'linear'] if scale == 0: scale_data = self.custom_ternary.as_matrix() elif scale == 1: scale_data = self.default_ternary.as_matrix() elif scale == 2: scale_data = self.linear_ternary.as_matrix() else: scale_data = self.custom_ternary.as_matrix() # get color data:color_list = ['custom', 'default', 'cluster color', 'linear'] if color == 0: color_data = self.custom_transformed.as_matrix() elif color == 1: color_data = self.default_transformed[['RFP', 'YFP', 'CFP']].as_matrix() elif color == 2: if self.tab_cluster_data.empty: color_data = helper.distinguishable_colors(1) else: pseudo_color = helper.distinguishable_colors(self.tab_cluster_data['id'].count()) pseudo_color[self.noise_cluster_idx] = "#646464" color_data = [None] * scale_data.shape[0] for i in range(0, scale_data.shape[0]): color_data[i] = pseudo_color[self.cluster_data_idx[i]] elif color == 3: color_data = self.linear_transformed[['RFP', 'YFP', 'CFP']].as_matrix() elif color == 4: color_data = np.empty([self.custom_transformed.shape[0], self.custom_transformed.shape[1]]) color_data[:] = 0.8 # grey for non-highlighted cells highlight_cells = pd.Series(highlight_cells, name='bools') if highlight_color: color_data[highlight_cells, :] = [0.2, 0.2, 0.2] else: color_data[highlight_cells, :] = self.custom_transformed[['RFP', 'YFP', 'CFP']][ highlight_cells.values].as_matrix() if not update: # build your visuals scatter = scene.visuals.create_visual_node(visuals.MarkersVisual) # build canvas self.h_canvas_2d = scene.SceneCanvas(title='zbow 2D ternary plot', keys='interactive', show=True, bgcolor=Color([1, 1, 1, 1]), ) parent.setCentralWidget(self.h_canvas_2d.native) # Add a ViewBox to let the user zoom/rotate if not update: self.h_view_2d = self.h_canvas_2d.central_widget.add_view() self.h_view_2d.camera = 'panzoom' self.h_view_2d.camera.set_range(x=(-0.2, 1.2), y=(-0.2, 1.2)) # if update: # self.h_view_2d = self.h_canvas_2d.central_widget.add_view() # self.h_view_2d.camera = 'panzoom' # self.h_view_2d.camera.set_state(options) # else: # self.h_view_2d = self.h_canvas_2d.central_widget.add_view() # self.h_view_2d.camera = 'panzoom' self.h_scatter_2d = scatter(parent=self.h_view_2d.scene) # p1.set_gl_state('translucent', blend=True, depth_test=True) self.h_scatter_2d.set_gl_state('translucent', blend=True, depth_test=False) # plot 2D ternary axis bottom_axis = scene.Axis(parent=self.h_view_2d.scene, pos=[[0, 0], [1, 0]], tick_direction=(0, 1), font_size=12, axis_color='k', tick_color='k', tick_font_size=0, axis_width=3, axis_label='', axis_label_margin=20, axis_font_size=18) right_axis = scene.Axis(parent=self.h_view_2d.scene, pos=[[1, 0], [0.5, 1]], tick_direction=(-1, -1), font_size=12, axis_color='k', tick_color='k', tick_font_size=0, axis_width=3, axis_label='', axis_label_margin=20, axis_font_size=18) left_axis = scene.Axis(parent=self.h_view_2d.scene, pos=[[0, 0], [0.5, 1]], tick_direction=(1, -1), font_size=12, axis_color='k', tick_color='k', tick_font_size=0, axis_width=3, axis_label='', axis_label_margin=20, axis_font_size=18) cell_color = ColorArray(color=color_data, alpha=1) # @BUG I want to use a different alpha here, but Vispy has a bug where you can see through the main canvas with alpha self.h_scatter_2d.set_data(pos=scale_data, symbol='o', size=5, edge_width=0, face_color=cell_color) # if not update: # self.h_scatter_2d.symbol = visuals.marker_types[10] if not update: parent.move(new_window_position.x(), new_window_position.y()) parent.show()
def _update_vispy_color(self): self._vispy_color = Color(self.color) self._vispy_color.alpha = self.alpha
def __init__(self, color='red', symbol='x'): super().__init__() self._color = Color(color) self._symbol = symbol self._markers_data = -1e8 * np.ones((1, 2))
def _update_cmap_from_color(self): cmap = get_translucent_cmap(*Color(self.color).rgb) self._multivol.set_cmap(self.id, cmap) self.redraw()
def _ui(self): l1 = QVBoxLayout() self.setLayout(l1) l1.setContentsMargins(0, 0, 0, 0) self.canvas = scene.SceneCanvas(title="", show=False, create_native=False, px_scale=1, bgcolor=Color("#101010"), dpi=None) self.canvas.create_native() l1.addWidget(self.canvas.native, ) # not set alignment # grid = self.canvas.central_widget.add_grid() grid.spacing = 0 yaxis = scene.AxisWidget( orientation='left', # axis_label='Y Axis', axis_font_size=12, axis_label_margin=50, tick_label_margin=5) yaxis.width_max = 50 yaxis.stretch = (0.05, 1) grid.add_widget(yaxis, row=0, col=0) xaxis = scene.AxisWidget( orientation='bottom', axis_label='X Axis', axis_font_size=12, axis_label_margin=100, tick_label_margin=10, ) xaxis.height_max = 100 xaxis.stretch = (1, .1) grid.add_widget(xaxis, row=1, col=1) view: scene.ViewBox = grid.add_view(row=0, col=1, border_color='white') view.camera = scene.PanZoomCamera() view.border_color = "#ffffff" xaxis.link_view(view) yaxis.link_view(view) global df # Candlestick kline1 = Candlestick(borderwidth=.2, padding=.1) kline1.set_data(df.x.values, df.o.values, df.h.values, df.l.values, df.c.values) view.add(kline1) # MA(CLOSE,22) try: import talib pos = np.empty((len(df), 2), dtype=np.float32) pos[:, 0] = np.arange(len(df)) pos[:, 1] = talib.MA(df.c.values, timeperiod=22) ma_line = scene.visuals.Line(pos, color=(1, 1, 1, 1), method='gl', width=1) view.add(ma_line) except: pass # view.camera.rect = (0, 0, 800, 7000) view.camera.set_range()
def __init__(self, n_volume_max=16, emulate_texture=False, bgcolor='white', resolution=256): # Choose texture class tex_cls = TextureEmulated3D if emulate_texture else Texture3D self._n_volume_max = n_volume_max self._vol_shape = (resolution, resolution, resolution) self._need_vertex_update = True self._data_bounds = None self.resolution = resolution # We deliberately don't use super here because we don't want to call # VolumeVisual.__init__ Visual.__init__(self, vcode=VERT_SHADER, fcode="") self.volumes = defaultdict(dict) # We turn on clipping straight away - the following variable is needed # by _update_shader self._clip_data = True # Set up initial shader so that we can start setting shader variables # that don't depend on what volumes are actually active. self._update_shader() # Set initial clipping parameters self.shared_program['u_clip_min'] = [0, 0, 0] self.shared_program['u_clip_max'] = [1, 1, 1] # Set up texture vertices - note that these variables are required by # the parent VolumeVisual class. self._vertices = VertexBuffer() self._texcoord = VertexBuffer( np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [1, 1, 0], [0, 0, 1], [1, 0, 1], [0, 1, 1], [1, 1, 1]], dtype=np.float32)) self._draw_mode = 'triangle_strip' self._index_buffer = IndexBuffer() self.shared_program['a_position'] = self._vertices self.shared_program['a_texcoord'] = self._texcoord # Only show back faces of cuboid. This is required because if we are # inside the volume, then the front faces are outside of the clipping # box and will not be drawn. self.set_gl_state('translucent', cull_face=False) # Set up the underlying volume shape and define textures self._vol_shape = (resolution, resolution, resolution) self.shared_program['u_shape'] = self._vol_shape self.textures = [] for i in range(n_volume_max): # Set up texture object self.textures.append( tex_cls(self._vol_shape, interpolation='linear', wrapping='clamp_to_edge')) # Pass texture object to shader program self.shared_program['u_volumetex_{0}'.format(i)] = self.textures[i] # Make sure all textures are disabled self.shared_program['u_enabled_{0}'.format(i)] = 0 self.shared_program['u_weight_{0}'.format(i)] = 1 # Don't use downsampling initially (1 means show 1:1 resolution) self.shared_program['u_downsample'] = 1. # Set up texture sampler self.shared_program.frag['sampler_type'] = self.textures[ 0].glsl_sampler_type self.shared_program.frag['sample'] = self.textures[0].glsl_sample # Set initial background color self.shared_program['u_bgcolor'] = Color(bgcolor).rgba # Prevent additional attributes from being added try: self.freeze() except AttributeError: # Older versions of VisPy pass
def set_background(self, color): self.shared_program['u_bgcolor'] = Color(color).rgba
name='cvb', border_width=2e-3, margin=0.02, border_color='green') cubeViewBox.interactive = True #spr = battery.Battery(parent=imageViewBox.scene) therm = Thermometer(parent=imageViewBox.scene) cubeViewBox.pos = 0, 0 cubeViewBox.size = 1, 1 cubeViewBox.camera = 'turntable' cubeViewBox.camera.rect = (-1, -1, 2, 2) cubeViewBox.camera.interactive = True color = Color("#3f51b5ff") # cube = scene.visuals.Cube(size=1, color=color, edge_color="black", # parent=cubeViewBox.scene) # spr.rect = (0, 0, 0.5, 0.5) # spr.depth = -1.0 @canvas.events.key_press.connect def on_key_press(event): k = event.text if k == '1': spr.percent = 100 if k == '2': spr.percent = 75 if k == '3':
def visualize(z_in, azimuth=25., elevation=30., thresholds=[0.94, .89, .75, .5, .25, .1], opacities=[.9, .8, .7, .5, .2, .1], # thresholds=[0.94, .89, .75], opacities=[.99, .7, .2], # thresholds=[0.7, .5, .2], opacities=[.95, .5, .2], fourier_label = {'f_x':'f_x', 'f_y':'f_y', 'f_t':'f_t'}, name=None, ext=ext, do_axis=True, do_grids=False, draw_projections=True, colorbar=False, f_N=2., f_tN=2., figsize=figsize, figpath=figpath, **kwargs): """ Visualization of the Fourier spectrum by showing 3D contour plots at different thresholds parameters ---------- z : envelope of the cloud """ if not(os.path.isdir(figpath)): os.mkdir(figpath) z = z_in.copy() N_X, N_Y, N_frame = z.shape fx, fy, ft = get_grids(N_X, N_Y, N_frame) # Normalize the amplitude. z /= z.max() from vispy import app, scene app.use_app('pyglet') #from vispy.util.transforms import perspective, translate, rotate from vispy.color import Color transparent = Color(color='black', alpha=0.) import colorsys canvas = scene.SceneCanvas(size=figsize, bgcolor='white', dpi=450) view = canvas.central_widget.add_view() vol_data = np.rollaxis(np.rollaxis(z, 1), 2) # volume = scene.visuals.Volume(vol_data, parent=view.scene)#frame) center = scene.transforms.STTransform(translate=( -N_X/2, -N_Y/2, -N_frame/2)) # volume.transform = center # volume.cmap = 'blues' if draw_projections: from vispy.color import Colormap cm = Colormap([(1.0, 1.0, 1.0, 1.0), 'k']) opts = {'parent':view.scene, 'cmap':cm, 'clim':(0., 1.)} energy_xy = np.rot90(np.max(z, axis=2)[:, ::-1], 3) fourier_xy = scene.visuals.Image(np.rot90(energy_xy), **opts) tr_xy = scene.transforms.MatrixTransform() tr_xy.rotate(90, (0, 0, 1)) tr_xy.translate((N_X/2, -N_Y/2, -N_frame/2)) fourier_xy.transform = tr_xy energy_xt = np.rot90(np.max(z, axis=1)[:, ::-1], 3) fourier_xt = scene.visuals.Image(energy_xt, **opts) tr_xt = scene.transforms.MatrixTransform() tr_xt.rotate(90, (1, 0, 0)) tr_xt.translate((-N_X/2, N_Y/2, -N_frame/2)) fourier_xt.transform = tr_xt energy_yt = np.max(z, axis=0)[:, ::-1] fourier_yt = scene.visuals.Image(energy_yt, **opts) tr_yt = scene.transforms.MatrixTransform() tr_yt.rotate(90, (0, 1, 0)) tr_yt.translate((-N_X/2, -N_Y/2, N_frame/2)) fourier_yt.transform = tr_yt # Generate iso-surfaces at different energy levels surfaces = [] for i_, (threshold, opacity) in enumerate(zip(thresholds, opacities)): surfaces.append(scene.visuals.Isosurface(z, level=threshold, # color=Color(np.array(colorsys.hsv_to_rgb(1.*i_/len(thresholds), 1., 1.)), alpha=opacity), color=Color(np.array(colorsys.hsv_to_rgb(.66, 1., 1.)), alpha=opacity), shading='smooth', parent=view.scene) ) surfaces[-1].transform = center # Draw a sphere at the origin axis = scene.visuals.XYZAxis(parent=view.scene) for p in ([1, 1, 1, -1, 1, 1], [1, 1, -1, -1, 1, -1], [1, -1, 1, -1, -1, 1],[1, -1, -1, -1, -1, -1], [1, 1, 1, 1, -1, 1], [-1, 1, 1, -1, -1, 1], [1, 1, -1, 1, -1, -1], [-1, 1, -1, -1, -1, -1], [1, 1, 1, 1, 1, -1], [-1, 1, 1, -1, 1, -1], [1, -1, 1, 1, -1, -1], [-1, -1, 1, -1, -1, -1]): line = scene.visuals.Line(pos=np.array([[p[0]*N_X/2, p[1]*N_Y/2, p[2]*N_frame/2], [p[3]*N_X/2, p[4]*N_Y/2, p[5]*N_frame/2]]), color='black', parent=view.scene) axisX = scene.visuals.Line(pos=np.array([[0, -N_Y/2, 0], [0, N_Y/2, 0]]), color='red', parent=view.scene) axisY = scene.visuals.Line(pos=np.array([[-N_X/2, 0, 0], [N_X/2, 0, 0]]), color='green', parent=view.scene) axisZ = scene.visuals.Line(pos=np.array([[0, 0, -N_frame/2], [0, 0, N_frame/2]]), color='blue', parent=view.scene) if do_axis: t = {} for text in ['f_x', 'f_y', 'f_t']: t[text] = scene.visuals.Text(fourier_label[text], parent=canvas.scene, face='Helvetica', color='black') t[text].font_size = 8 t['f_x'].pos = canvas.size[0] // 3, canvas.size[1] - canvas.size[1] // 8 t['f_y'].pos = canvas.size[0] - canvas.size[0] // 8, canvas.size[1] - canvas.size[1] // 6 t['f_t'].pos = canvas.size[0] // 8, canvas.size[1] // 2 cam = scene.TurntableCamera(elevation=elevation, azimuth=azimuth, up='z') cam.fov = 48 cam.scale_factor = N_X * 1.8 if do_axis: margin = 1.35 else: margin = 1 cam.set_range((-N_X/2*margin, N_X/2/margin), (-N_Y/2*margin, N_Y/2/margin), (-N_frame/2*margin, N_frame/2/margin)) view.camera = cam im = canvas.render(size=figsize) app.quit() if not(name is None): import vispy.io as io io.write_png(name + ext, im) else: return im
import os import math import numpy as np from vispy import scene, app, io, geometry from vispy.color import Color from vispy.visuals import transforms from vispy.scene.cameras import TurntableCamera from .. import util as util CF_MESH_PATH = os.path.join(os.path.dirname(__file__), "crazyflie2.obj.gz") ELLIPSOID_COLOR_OK = Color("#11FF22", alpha=0.1) ELLIPSOID_COLOR_COLLISION = Color("#FF0000", alpha=0.1) class VisVispy: def __init__(self): self.canvas = scene.SceneCanvas(keys='interactive', size=(1024, 768), show=True, config=dict(samples=4), resizable=True) self.plane_color = 0.25 * np.ones((1, 3)) self.bg_color = 0.9 * np.ones((1, 3)) self.line_color = 0.7 * np.ones((1, 3)) # Set up a viewbox to display the cube with interactive arcball self.view = self.canvas.central_widget.add_view() self.view.bgcolor = self.bg_color
def __init__(self, nb_boxes, vertices=None, faces=None, vertex_colors=None, face_colors=None, color=(0.5, 0.5, 1, 1), vertex_values=None, meshdata=None, shading=None, mode='triangles', variable_vis=False, **kwargs): # Visual.__init__ -> prepare_transforms() -> uses shading if shading is not None: raise ValueError('"shading" must be "None"') self.shading = shading self._variable_vis = variable_vis if variable_vis: Visual.__init__(self, vcode=vertex_template_vis, fcode=fragment_template_vis, **kwargs) else: Visual.__init__(self, vcode=vertex_template, fcode=fragment_template, **kwargs) self.set_gl_state('translucent', depth_test=True, cull_face=False) # Define buffers self._vertices = VertexBuffer(np.zeros((0, 3), dtype=np.float32)) self._normals = None self._faces = IndexBuffer() self._normals = VertexBuffer(np.zeros((0, 3), dtype=np.float32)) self._ambient_light_color = Color((0.3, 0.3, 0.3, 1.0)) self._light_dir = (10, 5, -5) self._shininess = 1. / 200. self._cmap = get_colormap('cubehelix') self._clim = 'auto' self._mode = mode # Uniform color self._color = Color(color) # primitive mode self._draw_mode = mode # Init self._bounds = None # Note we do not call subclass set_data -- often the signatures # do no match. VarVisMeshVisual.set_data(self, vertices=vertices, faces=faces, vertex_colors=vertex_colors, face_colors=face_colors, color=color, vertex_values=vertex_values, meshdata=meshdata) self.freeze()
app.use_app('pyqt5') from PyQt5 import QtWidgets, QtCore, QtGui from PyQt5.QtWidgets import * from vispy.util.transforms import perspective, translate, rotate from vispy.geometry import meshdata as md from vispy.geometry import generation as gen from BuildingList import * #from cube import cube from vispy.scene import SceneCanvas from vispy.scene.visuals import Polygon, Ellipse, Rectangle, RegularPolygon, XYZAxis from vispy.color import Color white = Color("#ecf0f1") gray = Color("#121212") red = Color("#e74c3c") blue = Color("#2980b9") orange = Color("#e88834") read_data = bfp.bfps_from_shape_file() dxdy = read_data[0].points[0] polygons = [] print(type(read_data[0].fnr_br)) data = [] rest = [] for building in read_data[:100]: if building.fnr_br == '10002489162':
#!/usr/bin/env python import sys import numpy from vispy import app from vispy.scene import SceneCanvas from vispy.scene.visuals import Ellipse from vispy.color import Color foot_radius = 0.1 radius = 1.075 black = Color("#000000") white = Color("#ecf0f1") blue = Color("#2980b9") green = Color("#00ff00") red = Color("#e74c3c") w, h = 800, 600 global target target = (0., 0.) feet = { 'fr': { 'center': (1.95627967418, 3.19594053089), }, 'mr': {
#!/usr/bin/env python """ Simple use of SceneCanvas to display a cube with an arcball camera. sudo apt-get install libglfw3* """ import sys from vispy import scene from vispy.color import Color canvas = scene.SceneCanvas(keys='interactive', size=(800, 600), show=True) # Set up a viewbox to display the cube with interactive arcball view = canvas.central_widget.add_view() view.bgcolor = '#efefef' view.camera = 'turntable' view.padding = 100 color = Color("#3f51b5") cube = scene.visuals.Cube(size=1, color=color, edge_color="black", parent=view.scene) if __name__ == '__main__' and sys.flags.interactive == 0: canvas.app.run()
def __init__(self, color='yellow'): super().__init__() self._color = Color(color).rgba self._shape = np.array([0, 0]) self._line_data2D = None self._line_length = 4096
def edge_color(self, edge_color): """ set """ self._edge_color = Color(edge_color) self._update()
def zbow_3d_plot(self, parent, scale, color, update=False, highlight_cells=None, highlight_color=False): if parent.was_closed: parent.show() new_window_position = parent.pos() if update: options = self.h_view_3d.camera.get_state() # get scale data: scale_list = ['custom', 'default', 'linear'] if scale == 0: scale_data = self.custom_transformed.as_matrix() elif scale == 1: scale_data = self.default_transformed[['RFP', 'YFP', 'CFP']].as_matrix() elif scale == 2: scale_data = self.linear_transformed[['RFP', 'YFP', 'CFP']].as_matrix() else: scale_data = self.custom_transformed.as_matrix() # get color data:color_list = ['custom', 'default', 'cluster color', 'linear'] if color == 0: color_data = self.custom_transformed.as_matrix() elif color == 1: color_data = self.default_transformed[['RFP', 'YFP', 'CFP']].as_matrix() elif color == 2: if self.tab_cluster_data.empty: color_data = helper.distinguishable_colors(1) else: pseudo_color = helper.distinguishable_colors(self.tab_cluster_data['id'].count()) pseudo_color[self.noise_cluster_idx] = "#646464" color_data = [None] * scale_data.shape[0] for i in range(0, scale_data.shape[0]): color_data[i] = pseudo_color[self.cluster_data_idx[i]] elif color == 3: color_data = self.linear_transformed[['RFP', 'YFP', 'CFP']].as_matrix() elif color == 4: color_data = np.empty([self.custom_transformed.shape[0], self.custom_transformed.shape[1]]) color_data[:] = 0.3 # grey for non-highlighted cells highlight_cells = pd.Series(highlight_cells, name='bools') if highlight_color: color_data[highlight_cells, :] = [0.9, 0.9, 0.9] else: color_data[highlight_cells, :] = self.custom_transformed[['RFP', 'YFP', 'CFP']][highlight_cells.values].as_matrix() if not update: # build your visuals scatter = scene.visuals.create_visual_node(visuals.MarkersVisual) # build initial canvas if one doesn't exist self.h_canvas_3d = scene.SceneCanvas(title='zbow 3D scatter plot', keys='interactive', show=True, bgcolor=Color([0, 0, 0, 1]), ) parent.setCentralWidget(self.h_canvas_3d.native) # Add a ViewBox to let the user zoom/rotate default_options = {'fov': 5, 'distance': 25, 'elevation': 30, 'azimuth': 130, 'scale_factor': 3.0} self.h_view_3d = self.h_canvas_3d.central_widget.add_view() self.h_view_3d.camera = 'turntable' self.h_view_3d.camera.fov = default_options['fov'] self.h_view_3d.camera.distance = default_options['distance'] self.h_view_3d.camera.elevation = default_options['elevation'] self.h_view_3d.camera.azimuth = default_options['azimuth'] self.h_view_3d.camera.scale_factor = default_options['scale_factor'] # if update: # self.h_view_3d = self.h_canvas_3d.central_widget.add_view() # self.h_view_3d.camera = 'turntable' # self.h_view_3d.camera.set_state(options) # # else: # self.h_view_3d = self.h_canvas_3d.central_widget.add_view() # self.h_view_3d.camera = 'turntable' # self.h_view_3d.camera.fov = default_options['fov'] # self.h_view_3d.camera.distance = default_options['distance'] # self.h_view_3d.camera.elevation = default_options['elevation'] # self.h_view_3d.camera.azimuth = default_options['azimuth'] # self.h_view_3d.camera.scale_factor = default_options['scale_factor'] # plot 3D RGB axis scene.visuals.XYZAxis(parent=self.h_view_3d.scene) # this isn't supported, apparently # x_axis = scene.Axis(parent=self.h_view_3d.scene, pos=[[0, 0, 0], [1, 0, 0]], # font_size=12, axis_color='k', tick_color='k', text_color='r', # axis_width=3) # # y_axis = scene.Axis(parent=self.h_view_3d.scene, pos=[[0, 0, 0], [0, 1, 0]], # font_size=12, axis_color='k', tick_color='k', text_color='g', # axis_width=3) # # left_axis = scene.Axis(parent=self.h_view_3d.scene, pos=[[0, 0, 0], [0, 0, 1]], tick_direction=(1, -1), # font_size=12, axis_color='k', tick_color='k', text_color='b', # axis_width=3) self.h_scatter_3d = scatter(parent=self.h_view_3d.scene) self.h_scatter_3d.set_gl_state('translucent') # h_scatter.set_gl_state(blend=False, depth_test=True) cell_color = ColorArray(color=color_data, alpha=1) # @BUG I want to use a different alpha here, but Vispy has a bug where you can see through the main canvas with alpha self.h_scatter_3d.set_data(pos=scale_data, symbol='o', size=5, edge_width=0, face_color=cell_color) # h_scatter.symbol = visuals.marker_types[10] if not update: parent.move(new_window_position.x(), new_window_position.y()) parent.show()
def _update_shape_buffers(data, triangulation='glu'): """ Translates Shapely geometry to internal buffers for speedup redraws :param data: dict Input shape data :param triangulation: str Triangulation engine """ mesh_vertices = [] # Vertices for mesh mesh_tris = [] # Faces for mesh mesh_colors = [] # Face colors line_pts = [] # Vertices for line line_colors = [] # Line color geo, color, face_color, tolerance = data['geometry'], data['color'], data[ 'face_color'], data['tolerance'] if geo is not None and not geo.is_empty: simple = geo.simplify( tolerance) if tolerance else geo # Simplified shape pts = [] # Shape line points tri_pts = [] # Mesh vertices tri_tris = [] # Mesh faces if type(geo) == LineString: # Prepare lines pts = _linestring_to_segments(list(simple.coords)) elif type(geo) == LinearRing: # Prepare lines pts = _linearring_to_segments(list(simple.coords)) elif type(geo) == Polygon: # Prepare polygon faces if face_color is not None: if triangulation == 'glu': gt = GLUTess() tri_tris, tri_pts = gt.triangulate(simple) else: print "Triangulation type '%s' isn't implemented. Drawing only edges." % triangulation # Prepare polygon edges if color is not None: pts = _linearring_to_segments(list(simple.exterior.coords)) for ints in simple.interiors: pts += _linearring_to_segments(list(ints.coords)) # Appending data for mesh if len(tri_pts) > 0 and len(tri_tris) > 0: mesh_tris += tri_tris mesh_vertices += tri_pts mesh_colors += [Color(face_color).rgba] * (len(tri_tris) / 3) # Appending data for line if len(pts) > 0: line_pts += pts line_colors += [Color(color).rgba] * len(pts) # Store buffers data['line_pts'] = line_pts data['line_colors'] = line_colors data['mesh_vertices'] = mesh_vertices data['mesh_tris'] = mesh_tris data['mesh_colors'] = mesh_colors # Clear shapely geometry del data['geometry'] return data