コード例 #1
0
ファイル: glcanvas.py プロジェクト: wradlib/wradvis
    def __init__(self, source=None, **kwargs):
        super(PolarImage, self).__init__(**kwargs)

        self.unfreeze()

        # source should be an object, which contains information about
        # a specific radar source
        self.source = source

        # source should contain the radar coordinates in some usable format
        # here I assume offset from lower left (0,0)
        if source is not None:
            xoff = source['X']
            yoff = source['Y']
        else:
            xoff = 0
            yoff = 0

        # this takes the image sizes and uses it for transformation
        self.theta = self._data.shape[0]
        self.range = self._data.shape[1]

        # PTransform takes care of making PPI from data array
        # rot rotates the ppi 180 deg (image origin is upper left)
        # the translation moves the image to centere the ppi
        rot = MatrixTransform()
        rot.rotate(180, (0, 0, 1))
        self.transform = (
            STTransform(translate=(self.range + xoff, self.range + yoff, 0)) *
            rot * PTransform())
        self.freeze()
コード例 #2
0
def _colorbar_for_surf(colormap, limits):
    colorbar = ColorBar(colormap, 'top', (50, 10), clim=limits)
    tr = MatrixTransform()
    tr.rotate(-90, (0, 1, 0))
    tr.translate((0, -100, 50))
    colorbar.transform = tr

    return colorbar
コード例 #3
0
ファイル: image_transforms.py プロジェクト: Eric89GXL/vispy
    def __init__(self):
        vispy.app.Canvas.__init__(self, keys='interactive', size=(800, 800))
        
        # Create 4 copies of an image to be displayed with different transforms
        image = get_image()
        self.images = [visuals.ImageVisual(image, method='impostor')
                       for i in range(4)]
        
        # Transform all images to a standard size / location (because
        # get_image() might return unexpected sizes)
        s = 100. / max(self.images[0].size)
        tx = 0.5 * (100 - (self.images[0].size[0] * s))
        ty = 0.5 * (100 - (self.images[0].size[1] * s))
        base_tr = STTransform(scale=(s, s), translate=(tx, ty))
        
        self.images[0].transform = (STTransform(scale=(30, 30),
                                                translate=(600, 600)) *
                                    SineTransform() *
                                    STTransform(scale=(0.1, 0.1),
                                                translate=(-5, -5)) *
                                    base_tr)

        tr = MatrixTransform()
        tr.rotate(40, (0, 0, 1))
        tr.rotate(30, (1, 0, 0))
        tr.translate((0, -20, -60))
        
        p = MatrixTransform()
        p.set_perspective(0.5, 1, 0.1, 1000)
        tr = p * tr
        
        tr1 = (STTransform(translate=(200, 600)) *
               tr *
               STTransform(translate=(-50, -50)) *
               base_tr)
        self.images[1].transform = tr1

        tr2 = (STTransform(scale=(3, -100), translate=(200, 50)) *
               LogTransform((0, 2, 0)) *
               STTransform(scale=(1, -0.01), translate=(-50, 1.1)) *
               base_tr)
        self.images[2].transform = tr2

        tr3 = (STTransform(scale=(400, 400), translate=(570, 400)) *
               PolarTransform() *
               STTransform(scale=(np.pi/150, -0.005),
                           translate=(-3.3*np.pi/4., 0.7)) *
               base_tr)
        self.images[3].transform = tr3

        text = visuals.TextVisual(
            text=['logarithmic', 'polar', 'perspective', 'custom (sine)'],
            pos=[(100, 20), (500, 20), (100, 410), (500, 410)],
            color='k', font_size=16)
        
        self.visuals = self.images + [text]

        self.show()
コード例 #4
0
ファイル: image_transforms.py プロジェクト: djhoese/vispy
    def __init__(self):
        vispy.app.Canvas.__init__(self, keys='interactive', size=(800, 800))

        # Create 4 copies of an image to be displayed with different transforms
        image = get_image()
        self.images = [visuals.ImageVisual(image, method='impostor')
                       for i in range(4)]

        # Transform all images to a standard size / location (because
        # get_image() might return unexpected sizes)
        s = 100. / max(self.images[0].size)
        tx = 0.5 * (100 - (self.images[0].size[0] * s))
        ty = 0.5 * (100 - (self.images[0].size[1] * s))
        base_tr = STTransform(scale=(s, s), translate=(tx, ty))

        self.images[0].transform = (STTransform(scale=(30, 30),
                                                translate=(600, 600)) *
                                    SineTransform() *
                                    STTransform(scale=(0.1, 0.1),
                                                translate=(-5, -5)) *
                                    base_tr)

        tr = MatrixTransform()
        tr.rotate(40, (0, 0, 1))
        tr.rotate(30, (1, 0, 0))
        tr.translate((0, -20, -60))

        p = MatrixTransform()
        p.set_perspective(0.5, 1, 0.1, 1000)
        tr = p * tr

        tr1 = (STTransform(translate=(200, 600)) *
               tr *
               STTransform(translate=(-50, -50)) *
               base_tr)
        self.images[1].transform = tr1

        tr2 = (STTransform(scale=(3, -100), translate=(200, 50)) *
               LogTransform((0, 2, 0)) *
               STTransform(scale=(1, -0.01), translate=(-50, 1.1)) *
               base_tr)
        self.images[2].transform = tr2

        tr3 = (STTransform(scale=(400, 400), translate=(570, 400)) *
               PolarTransform() *
               STTransform(scale=(np.pi/150, -0.005),
                           translate=(-3.3*np.pi/4., 0.7)) *
               base_tr)
        self.images[3].transform = tr3

        text = visuals.TextVisual(
            text=['logarithmic', 'polar', 'perspective', 'custom (sine)'],
            pos=[(100, 20), (500, 20), (100, 410), (500, 410)],
            color='k', font_size=16)

        self.visuals = self.images + [text]

        self.show()
コード例 #5
0
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, keys='interactive', size=(800, 550))

        vertices, faces, outline = create_box(width=1,
                                              height=1,
                                              depth=1,
                                              width_segments=4,
                                              height_segments=8,
                                              depth_segments=16)

        self.box = visuals.BoxVisual(width=1,
                                     height=1,
                                     depth=1,
                                     width_segments=4,
                                     height_segments=8,
                                     depth_segments=16,
                                     vertex_colors=vertices['color'],
                                     edge_color='b')

        self.theta = 0
        self.phi = 0

        self.transform = MatrixTransform()

        self.box.transform = self.transform
        self.show()

        self.timer = app.Timer(connect=self.rotate)
        self.timer.start(0.016)

    def rotate(self, event):
        self.theta += .5
        self.phi += .5
        self.transform.reset()
        self.transform.rotate(self.theta, (0, 0, 1))
        self.transform.rotate(self.phi, (0, 1, 0))
        self.transform.scale((100, 100, 0.001))
        self.transform.translate((200, 200))
        self.update()

    def on_resize(self, event):
        # Set canvas viewport and reconfigure visual transforms to match.
        vp = (0, 0, self.physical_size[0], self.physical_size[1])
        self.context.set_viewport(*vp)

        self.box.transforms.configure(canvas=self, viewport=vp)

    def on_draw(self, ev):
        gloo.clear(color='white', depth=True)
        self.box.draw()
コード例 #6
0
def _niimg_rot():
    """Get rotation trnasformations of each slice."""
    # Sagittal
    sg_rot = MatrixTransform()
    sg_rot.rotate(90., (0, 0, 1))
    sg_rot.rotate(180., (0, 1, 0))
    # Coronal
    cr_rot = MatrixTransform()
    cr_rot.rotate(90., (0, 0, 1))
    cr_rot.rotate(180., (0, 1, 0))
    # Axial
    ax_rot = MatrixTransform()
    ax_rot.rotate(180., (1, 0, 0))
    return sg_rot, cr_rot, ax_rot
コード例 #7
0
ファイル: box.py プロジェクト: Calvarez20/vispy
class Canvas(app.Canvas):

    def __init__(self):
        app.Canvas.__init__(self, keys='interactive', size=(800, 550))

        vertices, faces, outline = create_box(width=1, height=1, depth=1,
                                              width_segments=4,
                                              height_segments=8,
                                              depth_segments=16)

        self.box = visuals.BoxVisual(width=1, height=1, depth=1,
                                     width_segments=4,
                                     height_segments=8,
                                     depth_segments=16,
                                     vertex_colors=vertices['color'],
                                     edge_color='b')

        self.theta = 0
        self.phi = 0

        self.transform = MatrixTransform()

        self.box.transform = self.transform
        self.show()

        self.timer = app.Timer(connect=self.rotate)
        self.timer.start(0.016)

    def rotate(self, event):
        self.theta += .5
        self.phi += .5
        self.transform.reset()
        self.transform.rotate(self.theta, (0, 0, 1))
        self.transform.rotate(self.phi, (0, 1, 0))
        self.transform.scale((100, 100, 0.001))
        self.transform.translate((200, 200))
        self.update()

    def on_resize(self, event):
        # Set canvas viewport and reconfigure visual transforms to match.
        vp = (0, 0, self.physical_size[0], self.physical_size[1])
        self.context.set_viewport(*vp)

        self.box.transforms.configure(canvas=self, viewport=vp)

    def on_draw(self, ev):
        gloo.clear(color='white', depth=True)
        self.box.draw()
コード例 #8
0
ファイル: TestVispy.py プロジェクト: skidzo/visual
class dummy(scene.visuals.Cube):
    """
    creates a custom draft to demonstrate what is not working
    """
    def __init__(self,view,x,y,z,face_color,edge_color):
        scene.visuals.Cube.__init__(self,(x,y,z),color=face_color,edge_color=edge_color,parent=view)

    def trafo(self,x=0.,y=0.,z=0.,angle=0.,al=0.,be=0.,ga=0.):
        #Not Working
        self.transform = MatrixTransform()
        self.transform = self.transform.rotate(angle,[al,be,ga])
        self.transform = self.transform.translate([x,y,z])
コード例 #9
0
class dummy(scene.visuals.Cube):
    """
    creates a custom draft to demonstrate what is not working
    """
    def __init__(self, view, x, y, z, face_color, edge_color):
        scene.visuals.Cube.__init__(self, (x, y, z),
                                    color=face_color,
                                    edge_color=edge_color,
                                    parent=view)

    def trafo(self, x=0., y=0., z=0., angle=0., al=0., be=0., ga=0.):
        #Not Working
        self.transform = MatrixTransform()

        self.transform = self.transform.translate([x, y, z])
        self.transform = self.transform.rotate(angle, [al, be, ga])
コード例 #10
0
ファイル: mesh_banded.py プロジェクト: sylm21/vispy
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, keys='interactive', size=(800, 550))

        self.meshes = []
        self.rotation = MatrixTransform()

        # Generate some data to work with
        global mdata
        mdata = create_sphere(20, 40, 1.0)
        verts = mdata.get_vertices()
        faces = mdata.get_faces()
        gamma, phi = xyz_to_gp(verts)
        data = np.cos(5*gamma)+np.cos(phi*4)/2.
        mesh = visuals.MeshVisual(vertices=verts, faces=faces,
                                  banded=False, nband=8,
                                  vertex_values=data)
        mesh.cmap = 'viridis'
        self.meshes.append(mesh)
        mesh = visuals.MeshVisual(vertices=verts,
                                  faces=faces,  banded=True, nband=8,
                                  vertex_values=data)
        mesh.cmap = 'viridis'
        self.meshes.append(mesh)
        mesh = visuals.MeshVisual(vertices=verts,
                                  faces=faces,  banded=False, nband=8,
                                  vertex_values=data, shading='flat')
        mesh.cmap = 'viridis'
        self.meshes.append(mesh)
        mesh = visuals.MeshVisual(vertices=verts,
                                  faces=faces,  banded=True, nband=8,
                                  vertex_values=data, shading='flat')
        mesh.cmap = 'viridis'
        self.meshes.append(mesh)
        mesh = visuals.MeshVisual(vertices=verts,
                                  faces=faces,  banded=False, nband=8,
                                  vertex_values=data, shading='smooth')
        mesh.cmap = 'viridis'
        mesh.shininess = 0.01
        self.meshes.append(mesh)
        # Mesh with color indexed into a colormap
        mesh = visuals.MeshVisual(vertices=verts,
                                  faces=faces,  banded=True, nband=8,
                                  vertex_values=data, shading='smooth')
        mesh.cmap = 'viridis'
        mesh.shininess = 0.01
        self.meshes.append(mesh)

        # Lay out meshes in a grid
        grid = (3, 3)
        s = 300. / max(grid)
        for i, mesh in enumerate(self.meshes):
            x = 800. * (i % grid[0]) / grid[0] + 400. / grid[0] - 2
            y = 800. * (i // grid[1]) / grid[1] + 400. / grid[1] + 2
            transform = ChainTransform([STTransform(translate=(x, y),
                                                    scale=(s, s, s)),
                                        self.rotation])
            mesh.transform = transform
            mesh.transforms.scene_transform = STTransform(scale=(1, 1, 0.01))

        self.show()

        self.timer = app.Timer(connect=self.rotate)
        self.timer.start(0.016)

    def rotate(self, event):
        # rotate with an irrational amount over each axis so there is no
        # periodicity
        self.rotation.rotate(0.2 ** 0.5, (1, 0, 0))
        self.rotation.rotate(0.3 ** 0.5, (0, 1, 0))
        self.rotation.rotate(0.5 ** 0.5, (0, 0, 1))
        self.update()

    def on_resize(self, event):
        # Set canvas viewport and reconfigure visual transforms to match.
        vp = (0, 0, self.physical_size[0], self.physical_size[1])
        self.context.set_viewport(*vp)

        for mesh in self.meshes:
            mesh.transforms.configure(canvas=self, viewport=vp)

    def on_draw(self, ev):
        gloo.set_viewport(0, 0, *self.physical_size)
        gloo.clear(color='black', depth=True)

        for mesh in self.meshes:
            mesh.draw()
コード例 #11
0
ファイル: Normalise.py プロジェクト: esmam/MRATPython27
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, keys='interactive', size=(800, 600))
        brain = np.load(load_data_file('brain/brain.npz', force_download='2014-09-04'))

        #brain1 = scipy.io.loadmat('NewBESATri.mat')
        brain2 = brain1['t']


        from numpy import genfromtxt
        my_data = genfromtxt('BESACOORD61.csv', delimiter=',')

        dataTest = brain['vertex_buffer']
        color = dataTest['a_color']
        color = color[750:1500]
        facesTest = brain['index_buffer']

        n = 750
        ps = 100
        data = np.zeros(n, [('a_position', np.float32, 3),
                            ('a_normal', np.float32, 3),
                            ('a_color', np.float32, 3)])
                            #('a_size', np.float32, 1)])

        import scipy.spatial
        tri = scipy.spatial.Delaunay(my_data) # points: np.array() of 3d points
        convex = tri.convex_hull
        indices = tri.simplices
        vertices = my_data[indices]
        data['a_position'] = my_data
        data['a_color'] = np.random.uniform(0, 1, (n, 3))
        faces = brain2
        faces = faces-1
        vertices = my_data
        norm = np.zeros( vertices.shape, dtype=vertices.dtype )
        #Create an indexed view into the vertex array using the array of three indices for triangles
        tris = vertices[faces]

        #Calculate the normal for all the triangles, by taking the cross product of the vectors v1-v0, and v2-v0 in each triangle
        n = np.cross( tris[::,1 ] - tris[::,0]  , tris[::,2 ] - tris[::,0] )
        # n is now an array of normals per triangle. The length of each normal is dependent the vertices,
        # we need to normalize these, so that our next step weights each normal equally.
        lens = np.sqrt( n[:,0]**2 + n[:,1]**2 + n[:,2]**2 )
        n[:,0] /= lens
        n[:,1] /= lens
        n[:,2] /= lens



        norm[ faces[:,0] ] += n
        norm[ faces[:,1] ] += n
        norm[ faces[:,2] ] += n

        ''' Normalize a numpy array of 3 component vectors shape=(n,3) '''
        lens = np.sqrt( norm[:,0]**2 + norm[:,1]**2 + norm[:,2]**2 )
        norm[:,0] /= lens
        norm[:,1] /= lens
        norm[:,2] /= lens

        data['a_normal'] = norm #np.random.uniform(0, 1.0, (n, 3)) #10, 3, 3
        #data['a_size'] = np.random.uniform(5*ps, 10*ps, n)
        u_linewidth = 1.0
        u_antialias = 1.0



        brain2 = np.uint32(brain2)
        convex = np.uint32(convex)
        data = data
        faces = brain2-1

        #data = dataTest
        #faces = facesTest

        self.meshes = []
        self.rotation = MatrixTransform()

        # Generate some data to work with
        global mdata
        mdata = create_sphere(20, 40, 1.0)
        #mdata['_faces'] =faces
        #mdata['_vertices']=data
        # Mesh with pre-indexed vertices, uniform color
        meshData=vispy.geometry.MeshData(vertices=data['a_position'], faces=None, edges=None, vertex_colors=None, face_colors=None)
        meshData._vertices = data['a_position']
        meshData._faces = faces
        #meshData._face_colors = data['a_color']
        #meshData._vertex_colors = data['a_color']

        self.meshes.append(visuals.MeshVisual(meshdata=meshData, color='b'))
        #for mesh in self.meshes:
        #    mesh.draw()

        # Mesh with pre-indexed vertices, per-face color
        # Because vertices are pre-indexed, we get a different color
        # every time a vertex is visited, resulting in sharp color
        # differences between edges.
        tris = vertices[faces]
        verts = data['a_position'] #mdata.get_vertices(indexed='faces')

        nf = 1496#verts.size//9
        fcolor = np.ones((nf, 3, 4), dtype=np.float32)
        fcolor[..., 0] = np.linspace(1, 0, nf)[:, np.newaxis]
        fcolor[..., 1] = np.random.normal(size=nf)[:, np.newaxis]
        fcolor[..., 2] = np.linspace(0, 1, nf)[:, np.newaxis]
        #fcolor = data['a_color']
        mesh = visuals.MeshVisual(vertices=tris, face_colors=fcolor)
        self.meshes.append(mesh)


        # Mesh with unindexed vertices, per-vertex color
        # Because vertices are unindexed, we get the same color
        # every time a vertex is visited, resulting in no color differences
        # between edges.
        #verts = mdata.get_vertices()
        faces = faces #mdata.get_faces()
        nv = verts.size//3
        vcolor = np.ones((nv, 4), dtype=np.float32)
        vcolor[:, 0] = np.linspace(.6, .6, nv)
        vcolor[:, 1] = np.random.normal(size=nv)
        vcolor[:, 2] = np.linspace(0.6, .6, nv)
        self.meshes.append(visuals.MeshVisual(verts, faces, vcolor))
        self.meshes.append(visuals.MeshVisual(verts, faces, vcolor,
                                              shading='flat'))
        #
        self.meshes.append(visuals.MeshVisual(verts, faces, vcolor,
                                              shading='smooth'))

        # Lay out meshes in a grid
        grid = (1, 1)
        s = 300. / max(grid)
        #s = 500
        for i, mesh in enumerate(self.meshes):
            x = 800. * (i % grid[0]) / grid[0]  / grid[0] - 2
            y = 800. * (i // grid[1]) / grid[1]  / grid[1] + 2
            transform = ChainTransform([STTransform(translate=(x, y),
                                                    scale=(s, s, s)),
                                        self.rotation])
            mesh.transform = transform
            mesh.transforms.scene_transform = STTransform(scale=(.01, .01, .00001))

        self.show()

        self.timer = app.Timer(connect=self.rotate)
        self.timer.start(0.00016)

    def rotate(self, event):
        # rotate with an irrational amount over each axis so there is no
        # periodicity
        self.rotation.rotate(0.2 ** 0.5, (1, 0, 0))
        self.rotation.rotate(0.3 ** 0.5, (0, 1, 0))
        self.rotation.rotate(0.5 ** 0.5, (0, 0, 1))
        self.update()

    def on_resize(self, event):
        # Set canvas viewport and reconfigure visual transforms to match.
        vp = (0,0,self.physical_size[0], self.physical_size[1])

        self.context.set_viewport(*vp)

        for mesh in self.meshes:
            mesh.transforms.configure(canvas=self, viewport=vp)

    def on_draw(self, ev):
        test = self.physical_size
        gloo.set_viewport(800, 0, *self.physical_size)
        gloo.clear(color='white', depth=True)

        for mesh in self.meshes:
            mesh.draw()
コード例 #12
0
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, keys='interactive', size=(800, 550))

        self.meshes = []
        self.rotation = MatrixTransform()

        # Generate some data to work with
        global mdata
        mdata = create_sphere(20, 40, 1.0)

        # Mesh with pre-indexed vertices, uniform color
        self.meshes.append(visuals.MeshVisual(meshdata=mdata, color='b'))

        # Mesh with pre-indexed vertices, per-face color
        # Because vertices are pre-indexed, we get a different color
        # every time a vertex is visited, resulting in sharp color
        # differences between edges.
        rng = np.random.RandomState(0)
        verts = mdata.get_vertices(indexed='faces')
        nf = verts.size // 9
        fcolor = np.ones((nf, 3, 4), dtype=np.float32)
        fcolor[..., 0] = np.linspace(1, 0, nf)[:, np.newaxis]
        fcolor[..., 1] = rng.randn(nf, 1)
        fcolor[..., 2] = np.linspace(0, 1, nf)[:, np.newaxis]
        mesh = visuals.MeshVisual(vertices=verts, face_colors=fcolor)
        self.meshes.append(mesh)

        # Mesh with unindexed vertices, per-vertex color
        # Because vertices are unindexed, we get the same color
        # every time a vertex is visited, resulting in no color differences
        # between edges.
        verts = mdata.get_vertices()
        faces = mdata.get_faces()
        nv = verts.size // 3
        vcolor = np.ones((nv, 4), dtype=np.float32)
        vcolor[:, 0] = np.linspace(1, 0, nv)
        vcolor[:, 1] = rng.randn(nv)
        vcolor[:, 2] = np.linspace(0, 1, nv)
        self.meshes.append(visuals.MeshVisual(verts, faces, vcolor))
        self.meshes.append(
            visuals.MeshVisual(verts, faces, vcolor, shading='flat'))
        self.meshes.append(
            visuals.MeshVisual(verts, faces, vcolor, shading='smooth'))

        # Mesh with color indexed into a colormap
        verts = mdata.get_vertices(None)
        faces = mdata.get_faces()
        values = rng.randn(len(verts))
        mesh = visuals.MeshVisual(vertices=verts,
                                  faces=faces,
                                  vertex_values=values,
                                  shading='smooth')
        mesh.clim = [-1, 1]
        mesh.cmap = 'viridis'
        mesh.shininess = 0.01
        self.meshes.append(mesh)

        # Lay out meshes in a grid
        grid = (3, 3)
        s = 300. / max(grid)
        for i, mesh in enumerate(self.meshes):
            x = 800. * (i % grid[0]) / grid[0] + 400. / grid[0] - 2
            y = 800. * (i // grid[1]) / grid[1] + 400. / grid[1] + 2
            transform = ChainTransform([
                STTransform(translate=(x, y), scale=(s, s, s)), self.rotation
            ])
            mesh.transform = transform
            mesh.transforms.scene_transform = STTransform(scale=(1, 1, 0.01))

        self.show()

        self.timer = app.Timer(connect=self.rotate)
        self.timer.start(0.016)

    def rotate(self, event):
        # rotate with an irrational amount over each axis so there is no
        # periodicity
        self.rotation.rotate(0.2**0.5, (1, 0, 0))
        self.rotation.rotate(0.3**0.5, (0, 1, 0))
        self.rotation.rotate(0.5**0.5, (0, 0, 1))
        self.update()

    def on_resize(self, event):
        # Set canvas viewport and reconfigure visual transforms to match.
        vp = (0, 0, self.physical_size[0], self.physical_size[1])
        self.context.set_viewport(*vp)

        for mesh in self.meshes:
            mesh.transforms.configure(canvas=self, viewport=vp)

    def on_draw(self, ev):
        gloo.set_viewport(0, 0, *self.physical_size)
        gloo.clear(color='black', depth=True)

        for mesh in self.meshes:
            mesh.draw()
コード例 #13
0
ファイル: hoc_graphics.py プロジェクト: pbmanis/neuronvis
class vispy_Cylinders(app.Canvas):
    """
    Input:
        h: HocReader instance
    """

    def __init__(self, h):
        self.h = h
        app.Canvas.__init__(self, keys='interactive', size=(800, 550))
        
        hcyl = mplcyl.TruncatedCone()
        print('1')
        #plot_tc(p0=np.array([1, 3, 2]), p1=np.array([8, 5, 9]), R=[5.0, 2.0])
        verts, edges = h.get_geometry()

        self.meshes = []
        self.rotation = MatrixTransform()
        sec_ids = []
        s = 1.0
        x, y = 0., 0.
        for edge in edges:
            ends = verts['pos'][edge]  # xyz coordinate of one end [x,y,z]
            dia = verts['dia'][edge]  # diameter at that end
            sec_id = verts['sec_index'][edge[0]]  # save the section index
            
            dif = ends[1]-ends[0]  # distance between the ends
            length = (dif**2).sum() ** 0.5
            # print length
            # print dia
            #C, T, B = hcyl.make_truncated_cone(p0=ends[0], p1=ends[1], R=[dia[0]/2., dia[1]/2.])
            mesh_verts =  create_cylinder(8, 8, radius=[dia[0]/2., dia[1]/2.], length=length, offset=False)
            #mesh_verts = create_grid_mesh(C[0], C[1], C[2])

            
            # sec_id_array = np.empty(mesh_verts.shape[0]*3, dtype=int)
            # # sec_id_array[:] = sec_id
            # meshes.append(mesh_verts)
            # sec_ids.append(sec_id_array)
            self.meshes.append(visuals.MeshVisual(meshdata=mesh_verts, color='r'))

#             transform = ChainTransform([STTransform(translate=(x, y),
#                                                     scale=(s, s, s)),
#                                         self.rotation])
#
#         for i, mesh in enumerate(self.meshes):
# #            x = 800. * (i % grid[0]) / grid[0] + 40
#             mesh.transform = transform
#             mesh.transforms.scene_transform = STTransform(scale=(1, 1, 0.01))
        
        gloo.set_viewport(0, 0, *self.physical_size)
        gloo.clear(color='white', depth=True)

        for mesh in self.meshes:
            mesh.draw()

        print('running')
        self.show()
        if sys.flags.interactive != 1:
            app.run()
        #exit(1)
        
    def rotate(self, event):
        # rotate with an irrational amount over each axis so there is no
        # periodicity
        self.rotation.rotate(0.2 ** 0.5, (1, 0, 0))
        self.rotation.rotate(0.3 ** 0.5, (0, 1, 0))
        self.rotation.rotate(0.5 ** 0.5, (0, 0, 1))
        self.update()

    def on_resize(self, event):
        # Set canvas viewport and reconfigure visual transforms to match.
        vp = (0, 0, self.physical_size[0], self.physical_size[1])
        self.context.set_viewport(*vp)

        for mesh in self.meshes:
            mesh.transforms.configure(canvas=self, viewport=vp)

    def on_draw(self, ev):
        gloo.set_viewport(0, 0, *self.physical_size)
        gloo.clear(color='black', depth=True)

        for mesh in self.meshes:
            mesh.draw()
コード例 #14
0
pos = cga.round.location(circle)
pos = np.array(pos)[:3]
aa = cga.operate.axis_angle(circle)
aa = np.array(aa)
radius = cga.round.radius(circle)

circle_visual = Ellipse3D([0, 0, 0],
                          radius=radius,
                          parent=view.scene,
                          border_color='r',
                          color=(0, 0, 0, 0))
# circle_visual.border.method = 'agg'
# circle_visual.border.set_data(width=2)

m = MatrixTransform()
m.rotate(aa[0], aa[1:])
m.translate(pos)

circle_visual.transform = m

m = MatrixTransform()
m.rotate(45, [1, 0, 0])
m.translate([1, 2, 3])

# print(m.matrix.T)

sphere1 = scene.visuals.Sphere(radius=cga.round.radius(a),
                               method='latitude',
                               parent=view.scene,
                               color=(0.1, 0.2, 0.3, 1),
                               edge_color=None)
コード例 #15
0
class Canvas(app.Canvas):
    def __init__(self):
        app.Canvas.__init__(self, keys='interactive', size=(800, 550))

        self.meshes = []
        self.rotation = MatrixTransform()

        # Generate some data to work with
        global mdata
        mdata = create_sphere(20, 40, 1.0)

        # Mesh with pre-indexed vertices, uniform color
        self.meshes.append(visuals.MeshVisual(meshdata=mdata, color='b'))

        # Mesh with pre-indexed vertices, per-face color
        # Because vertices are pre-indexed, we get a different color
        # every time a vertex is visited, resulting in sharp color
        # differences between edges.
        verts = mdata.get_vertices(indexed='faces')
        nf = verts.size//9
        fcolor = np.ones((nf, 3, 4), dtype=np.float32)
        fcolor[..., 0] = np.linspace(1, 0, nf)[:, np.newaxis]
        fcolor[..., 1] = np.random.normal(size=nf)[:, np.newaxis]
        fcolor[..., 2] = np.linspace(0, 1, nf)[:, np.newaxis]
        mesh = visuals.MeshVisual(vertices=verts, face_colors=fcolor)
        self.meshes.append(mesh)

        # Mesh with unindexed vertices, per-vertex color
        # Because vertices are unindexed, we get the same color
        # every time a vertex is visited, resulting in no color differences
        # between edges.
        verts = mdata.get_vertices()
        faces = mdata.get_faces()
        nv = verts.size//3
        vcolor = np.ones((nv, 4), dtype=np.float32)
        vcolor[:, 0] = np.linspace(1, 0, nv)
        vcolor[:, 1] = np.random.normal(size=nv)
        vcolor[:, 2] = np.linspace(0, 1, nv)
        self.meshes.append(visuals.MeshVisual(verts, faces, vcolor))
        self.meshes.append(visuals.MeshVisual(verts, faces, vcolor,
                                              shading='flat'))
        self.meshes.append(visuals.MeshVisual(verts, faces, vcolor,
                                              shading='smooth'))

        # Lay out meshes in a grid
        grid = (3, 3)
        s = 300. / max(grid)
        for i, mesh in enumerate(self.meshes):
            x = 800. * (i % grid[0]) / grid[0] + 400. / grid[0] - 2
            y = 800. * (i // grid[1]) / grid[1] + 400. / grid[1] + 2
            transform = ChainTransform([STTransform(translate=(x, y),
                                                    scale=(s, s, s)),
                                        self.rotation])
            mesh.transform = transform
            mesh.transforms.scene_transform = STTransform(scale=(1, 1, 0.01))

        self.show()

        self.timer = app.Timer(connect=self.rotate)
        self.timer.start(0.016)

    def rotate(self, event):
        # rotate with an irrational amount over each axis so there is no
        # periodicity
        self.rotation.rotate(0.2 ** 0.5, (1, 0, 0))
        self.rotation.rotate(0.3 ** 0.5, (0, 1, 0))
        self.rotation.rotate(0.5 ** 0.5, (0, 0, 1))
        self.update()

    def on_resize(self, event):
        # Set canvas viewport and reconfigure visual transforms to match.
        vp = (0, 0, self.physical_size[0], self.physical_size[1])
        self.context.set_viewport(*vp)

        for mesh in self.meshes:
            mesh.transforms.configure(canvas=self, viewport=vp)

    def on_draw(self, ev):
        gloo.set_viewport(0, 0, *self.physical_size)
        gloo.clear(color='black', depth=True)

        for mesh in self.meshes:
            mesh.draw()
コード例 #16
0
class AxisAlignedImage(scene.visuals.Image):
  """ Visual subclass displaying an image that aligns to an axis.
  This image should be able to move along the perpendicular direction when
  user gives corresponding inputs.

  Parameters:

  """
  def __init__(self, image_funcs, axis='z', pos=0, limit=None,
               seismic_coord_system=True,
               cmaps=['grays'], clims=None,
               interpolation='nearest', method='auto'):

    assert clims is not None, 'clim must be specified explicitly.'

    # Create an Image obj and unfreeze it so we can add more
    # attributes inside.
    # First image (from image_funcs[0])
    scene.visuals.Image.__init__(self, parent=None, # no image func yet
      cmap=cmaps[0], clim=clims[0],
      interpolation=interpolation, method=method)
    self.unfreeze()
    self.interactive = True

    # Other images ...
    self.overlaid_images = [self]
    for i_img in range(1, len(image_funcs)):
      overlaid_image = scene.visuals.Image(parent=self,
        cmap=cmaps[i_img], clim=clims[i_img],
        interpolation=interpolation, method=method)
      self.overlaid_images.append(overlaid_image)

    # Set GL state. Must check depth test, otherwise weird in 3D.
    self.set_gl_state(depth_test=True, depth_func='lequal',
      blend_func=('src_alpha', 'one_minus_src_alpha'))

    # Determine the axis and position of this plane.
    self.axis = axis
    # Check if pos is within the range.
    if limit is not None:
      assert (pos>=limit[0]) and (pos<=limit[1]), \
        'pos={} is outside limit={} range.'.format(pos, limit)
    self.pos = pos
    self.limit = limit
    self.seismic_coord_system = seismic_coord_system

    # Get the image_func that returns either image or image shape.
    self.image_funcs = image_funcs # a list of functions!
    shape = self.image_funcs[0](self.pos, get_shape=True)

    # The selection highlight (a Plane visual with transparent color).
    # The plane is initialized before any rotation, on '+z' direction.
    self.highlight = scene.visuals.Plane(parent=self,
      width=shape[0], height=shape[1], direction='+z',
      color=(1, 1, 0, 0.1)) # transparent yellow color
    # Move the plane to align with the image.
    self.highlight.transform = STTransform(
      translate=(shape[0]/2, shape[1]/2, 0))
    # This is to make sure we can see highlight plane through the images.
    self.highlight.set_gl_state('additive', depth_test=True)
    self.highlight.visible = False # only show when selected

    # Set the anchor point (2D local world coordinates). The mouse will
    # drag this image by anchor point moving in the normal direction.
    self.anchor = None # None by default
    self.offset = 0

    # Apply SRT transform according to the axis attribute.
    self.transform = MatrixTransform()
    # Move the image plane to the corresponding location.
    self._update_location()

    self.freeze()

  @property
  def axis(self):
    """The dimension that this image is perpendicular aligned to."""
    return self._axis

  @axis.setter
  def axis(self, value):
    value = value.lower()
    if value not in ('z', 'y', 'x'):
      raise ValueError('Invalid value for axis.')
    self._axis = value

  def set_anchor(self, mouse_press_event):
    """ Set an anchor point (2D coordinate on the image plane) when left click
    in the selection mode (<Ctrl> pressed). After that, the dragging called
    in func 'drag_visual_node' will try to move along the normal direction
    and let the anchor follows user's mouse position as close as possible.
    """
    # Get the screen-to-local transform to get camera coordinates.
    tr = self.canvas.scene.node_transform(self)

    # Get click (camera) coordinate in the local world.
    click_pos = tr.map([*mouse_press_event.pos, 0, 1])
    click_pos /= click_pos[3] # rescale to cancel out the pos.w factor
    # Get the view direction (camera-to-target) vector in the local world.
    view_vector = tr.map([*mouse_press_event.pos, 1, 1])[:3]
    view_vector /= np.linalg.norm(view_vector) # normalize to unit vector

    # Get distance from camera to the drag anchor point on the image plane.
    # Eq 1: click_pos + distance * view_vector = anchor
    # Eq 2: anchor[2] = 0 <- intersects with the plane
    # The following equation can be derived by Eq 1 and Eq 2.
    distance = (0. - click_pos[2]) / view_vector[2]
    self.anchor = click_pos[:2] + distance * view_vector[:2] # only need vec2

  def drag_visual_node(self, mouse_move_event):
    """ Drag this visual node while holding left click in the selection mode
    (<Ctrl> pressed). The plane will move in the normal direction
    perpendicular to this image, and the anchor point (set with func
    'set_anchor') will move along the normal direction to stay as close to
    the mouse as possible, so that user feels like 'dragging' the plane.
    """
    # Get the screen-to-local transform to get camera coordinates.
    tr = self.canvas.scene.node_transform(self)

    # Unlike in 'set_anchor', we now convert most coordinates to the screen
    # coordinate system, because it's more intuitive for user to do operations
    # in 2D and get 2D feedbacks, e.g. mouse leading the anchor point.
    anchor = [*self.anchor, self.pos, 1] # 2D -> 3D
    anchor_screen = tr.imap(anchor) # screen coordinates of the anchor point
    anchor_screen /= anchor_screen[3] # rescale to cancel out 'w' term
    anchor_screen = anchor_screen[:2] # only need vec2

    # Compute the normal vector, starting from the anchor point and
    # perpendicular to the image plane.
    normal = [*self.anchor, self.pos+1, 1] # +[0,0,1,0] from anchor
    normal_screen = tr.imap(normal) # screen coordinates of anchor + [0,0,1,0]
    normal_screen /= normal_screen[3] # rescale to cancel out 'w' term
    normal_screen = normal_screen[:2] # only need vec2
    normal_screen -= anchor_screen # end - start = vector
    normal_screen /= np.linalg.norm(normal_screen) # normalize to unit vector

    # Use the vector {anchor_screen -> mouse.pos} and project to the
    # normal_screen direction using dot product, we can get how far the plane
    # should be moved (on the screen!).
    drag_vector = mouse_move_event.pos[:2] - anchor_screen
    drag = np.dot(drag_vector, normal_screen) # normal_screen must be length 1

    # We now need to convert the move distance from screen coordinates to
    # local world coordinates. First, find where the anchor is on the screen
    # after dragging; then, convert that screen point to a local line shooting
    # across the normal vector; finally, find where the line comes directly
    # above/below the anchor point (before dragging) and get that distance as
    # the true dragging distance in local coordinates.
    new_anchor_screen = anchor_screen + normal_screen * drag
    new_anchor = tr.map([*new_anchor_screen, 0, 1])
    new_anchor /= new_anchor[3] # rescale to cancel out the pos.w factor
    view_vector = tr.map([*new_anchor_screen, 1, 1])[:3]
    view_vector /= np.linalg.norm(view_vector) # normalize to unit vector
    # Solve this equation:
    # new_anchor := new_anchor + view_vector * ?,
    # ^^^ describe a 3D line of possible new anchor positions
    # arg min (?) |new_anchor[:2] - anchor[:2]|
    # ^^^ find a point on that 3D line that minimize the 2D distance between
    #     new_anchor and anchor.
    numerator = anchor[:2] - new_anchor[:2]
    numerator *= view_vector[:2] # element-wise multiplication
    numerator = np.sum(numerator)
    denominator = view_vector[0]**2 + view_vector[1]**2
    shoot_distance = numerator / denominator
    # Shoot from new_anchor to get the new intersect point. The z- coordinate
    # of this point will be our dragging offset.
    offset = new_anchor[2] + view_vector[2] * shoot_distance

    # Note: must reverse normal direction from -y direction to +y!
    if self.axis == 'y': offset = -offset
    # Limit the dragging within range.
    if self.limit is not None:
      if self.pos + offset < self.limit[0]: offset = self.limit[0] - self.pos
      if self.pos + offset > self.limit[1]: offset = self.limit[1] - self.pos
    self.offset = offset
    # Note: must reverse normal direction from +y direction to -y!
    if self.axis == 'y': offset = -offset

    self._update_location()

  def _update_location(self):
    """ Update the image plane to the dragged location and redraw this image.
    """
    self.pos += self.offset
    self.pos = int(np.round(self.pos)) # must round to nearest integer location

    # Update the transformation in order to move to new location.
    self.transform.reset()
    if self.axis == 'z':
      # 1. No rotation to do for z axis (y-x) slice. Only translate.
      self.transform.translate((0, 0, self.pos))
    elif self.axis == 'y':
      # 2. Rotation(s) for the y axis (z-x) slice, then translate:
      self.transform.rotate(90, (1, 0, 0))
      self.transform.translate((0, self.pos, 0))
    elif self.axis == 'x':
      # 3. Rotation(s) for the x axis (z-y) slice, then translate:
      self.transform.rotate(90, (1, 0, 0))
      self.transform.rotate(90, (0, 0, 1))
      self.transform.translate((self.pos, 0, 0))

    # Update image on the slice based on current position. The numpy array
    # is transposed due to a conversion from i-j to x-y axis system.
    # First image, the primary one:
    self.set_data(self.image_funcs[0](self.pos).T)
    # Other images, overlaid on the primary image:
    for i_img in range(1, len(self.image_funcs)):
      self.overlaid_images[i_img].set_data(
        self.image_funcs[i_img](self.pos).T)

    # Reset attributes after dragging completes.
    self.offset = 0
    self._bounds_changed() # update the bounds with new self.pos

  def _compute_bounds(self, axis_3d, view):
    """ Overwrite the original 2D bounds of the Image class. This will correct 
    the automatic range setting for the camera in the scene canvas. In the
    original Image class, the code assumes that the image always lies in x-y
    plane; here we generalize that to x-z and y-z plane.
    
    Parameters:
    axis_3d: int in {0, 1, 2}, represents the axis in 3D view box.
    view: the ViewBox object that connects to the parent.

    The function returns a tuple (low_bounds, high_bounds) that represents
    the spatial limits of self obj in the 3D scene.
    """
    # Note: self.size[0] is slow dim size, self.size[1] is fast dim size.
    if self.axis == 'z':
      if   axis_3d==0: return (0, self.size[0])
      elif axis_3d==1: return (0, self.size[1])
      elif axis_3d==2: return (self.pos, self.pos)
    elif self.axis == 'y':
      if   axis_3d==0: return (0, self.size[0])
      elif axis_3d==1: return (self.pos, self.pos)
      elif axis_3d==2: return (0, self.size[1])
    elif self.axis == 'x':
      if   axis_3d==0: return (self.pos, self.pos)
      elif axis_3d==1: return (0, self.size[0])
      elif axis_3d==2: return (0, self.size[1])