def __init__(self,
                 n_volume_max=10,
                 threshold=None,
                 relative_step_size=0.8,
                 emulate_texture=False):

        Visual.__init__(self)

        self._n_volume_max = n_volume_max

        # 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)
        tex_cls = TextureEmulated3D if emulate_texture else Texture3D

        # Storage of information of volume
        self._initial_shape = True
        self._vol_shape = ()
        self._vertex_cache_id = ()
        self._clim = None

        # Create gloo objects
        self._vbo = None
        self._tex = tex_cls((10, 10, 10),
                            interpolation='linear',
                            wrapping='clamp_to_edge')

        # Set custom vertex shader
        vert_shader, frag_shader = get_shaders(n_volume_max)
        frag_dict['additive_multi_volume'] = frag_shader

        # Create program
        self._program = ModularProgram(vert_shader)
        self.textures = []
        for i in range(n_volume_max):
            self.textures.append(
                tex_cls((10, 10, 10),
                        interpolation='linear',
                        wrapping='clamp_to_edge'))
            self._program['u_volumetex_{0}'.format(i)] = self.textures[i]
        self._index_buffer = None

        # Set params
        self.method = 'additive_multi_volume'
        self.relative_step_size = relative_step_size

        for i in range(n_volume_max):
            self._program.frag['cmap{0:d}'.format(i)] = Function(
                get_colormap('grays').glsl_map)
            self._program['u_enabled_{0}'.format(i)] = 0
            self._program['u_weight_{0}'.format(i)] = 1

        self.xd = None

        self._block_size = None

        self.volumes = {}

        self._create_vertex_data()
Beispiel #2
0
 def __init__(self, pos=None, color=None, size=None):
     Visual.__init__(self, self.VERTEX_SHADER, self.FRAGMENT_SHADER)
     self._pos = pos
     self._color = color
     self._size = size
     self.set_gl_state(blend=True,
                       blend_func=('src_alpha', 'one_minus_src_alpha'))
     self._draw_mode = 'points'
Beispiel #3
0
    def __init__(self,
                 points,
                 simplices,
                 vertex_color=None,
                 mask_color=None,
                 alpha=1.0,
                 mode='triangles'):
        """ initialize tetrahedra face plot

        Parameters
        ----------
        points : NDArray of float32
            N x 3 points coordinates
        simplices : NDArray of uint32
            N x 4 connectivity matrix

        Note
        ----
        initialize triangles structure
        """
        Visual.__init__(self, vcode=vert, fcode=frag)

        # set data
        self.shared_program.vert['position'] = gloo.VertexBuffer(points)
        if vertex_color is None:
            vertex_color = np.ones((points.shape[0], 4), dtype=np.float32)
        else:
            assert vertex_color.shape[0] == points.shape[0]
            # vertex color may be grayscale
            if np.ndim(vertex_color) == 1:
                f = vertex_color[:, np.newaxis]
                v = np.repeat(f, 4, axis=1)
                v[:, -1] = 1.0
                vertex_color = v.astype(np.float32)
        self.shared_program['a_color'] = vertex_color

        # mask colors, alpha channel is not used when mask_color is given.
        if mask_color is None:
            mask_color = [1.0, 1.0, 1.0, alpha]
        self.shared_program['u_color'] = mask_color

        # build buffer
        if mode is 'triangles':
            vbo = sim2tri(simplices)
        elif mode is 'lines':
            vbo = sim2edge(simplices)
        else:
            raise ValueError('Drawing mode = ' + mode + ' not supported')
        self._index_buffer = gloo.IndexBuffer(vbo)

        # config OpenGL, 'translucent' or 'additive'
        self.set_gl_state('additive',
                          blend=True,
                          depth_test=False,
                          cull_face=False,
                          polygon_offset_fill=False,
                          polygon_offset=(1, 1))
        self._draw_mode = mode
Beispiel #4
0
    def __init__(self,
                 vol,
                 clim=None,
                 method='mip',
                 threshold=None,
                 relative_step_size=0.8,
                 cmap='grays',
                 emulate_texture=False):

        tex_cls = TextureEmulated3D if emulate_texture else Texture3D

        # Storage of information of volume
        self._vol_shape = ()
        self._clim = None
        self._need_vertex_update = True

        # Set the colormap
        self._cmap = get_colormap(cmap)

        # Create gloo objects
        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._tex = tex_cls((10, 10, 10),
                            interpolation='linear',
                            wrapping='clamp_to_edge')

        # Create program
        Visual.__init__(self, vcode=VERT_SHADER, fcode="")
        self.shared_program['u_volumetex'] = self._tex
        self.shared_program['a_position'] = self._vertices
        self.shared_program['a_texcoord'] = self._texcoord
        self._draw_mode = 'triangle_strip'
        self._index_buffer = IndexBuffer()

        # 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 data
        self.set_data(vol, clim)

        # Set params
        self.method = method
        self.relative_step_size = relative_step_size
        self.threshold = threshold if (threshold is not None) else vol.mean()
        self.freeze()
Beispiel #5
0
    def __init__(self, vertices=None, faces=None, normals=None, lr_index=None,
                 hemisphere='both', sulcus=None, alpha=1., mask_color='orange',
                 camera=None, meshdata=None, invert_normals=False):
        """Init."""
        self._camera = None
        self._translucent = True
        self._alpha = alpha
        self._hemisphere = hemisphere
        self._n_overlay = 0
        self._data_lim = []

        # Initialize the vispy.Visual class with the vertex / fragment buffer :
        Visual.__init__(self, vcode=VERT_SHADER, fcode=FRAG_SHADER)

        # _________________ BUFFERS _________________
        # Vertices / faces / normals / color :
        def_3 = np.zeros((0, 3), dtype=np.float32)
        self._vert_buffer = gloo.VertexBuffer(def_3)
        self._normals_buffer = gloo.VertexBuffer(def_3)
        self._bgd_buffer = gloo.VertexBuffer()
        self._xrange_buffer = gloo.VertexBuffer()
        self._alphas_buffer = gloo.VertexBuffer()
        self._index_buffer = gloo.IndexBuffer()

        # _________________ PROGRAMS _________________
        self.shared_program.vert['a_position'] = self._vert_buffer
        self.shared_program.vert['a_normal'] = self._normals_buffer
        self.shared_program.vert['u_n_overlays'] = self._n_overlay
        self.shared_program.frag['u_alpha'] = alpha

        # _________________ LIGHTS _________________
        self.shared_program.frag['u_light_intensity'] = LIGHT_INTENSITY
        self.shared_program.frag['u_coef_ambient'] = COEF_AMBIENT
        self.shared_program.frag['u_coef_specular'] = COEF_SPECULAR
        self.shared_program.frag['u_light_position'] = LIGHT_POSITION
        self.shared_program.frag['camtf'] = vist.NullTransform()

        # _________________ DATA / CAMERA / LIGHT _________________
        # Data :
        self.set_data(vertices, faces, normals, hemisphere, lr_index,
                      invert_normals, sulcus, meshdata)
        # Camera :
        self.set_camera(camera)
        self.mask_color = mask_color

        # Slices :
        self.xmin, self.xmax = None, None
        self.ymin, self.ymax = None, None
        self.zmin, self.zmax = None, None
        self.inv_light = False

        # _________________ GL STATE _________________
        self.set_gl_state('translucent', depth_test=True, cull_face=False,
                          blend=True, blend_func=('src_alpha',
                                                  'one_minus_src_alpha'))
        self._draw_mode = 'triangles'
        self.freeze()
Beispiel #6
0
    def __init__(self, data, color, symbol="disc", size=3):
        Visual.__init__(self, vert, frag)

        self.size = size
        self.symbol = symbol

        self.shared_program["a_position"] = np.float32(data)
        self.shared_program["a_size"] = np.repeat(
            self.size, data.shape[0]).astype(np.float32)
        self.shared_program["a_color"] = VertexBuffer(color.rgba)
        self._draw_mode = "points"
Beispiel #7
0
    def __init__(self, points, simplices, vertex_color=None,
                 mask_color=None, alpha=1.0,
                 mode='triangles'):
        """ initialize tetrahedra face plot

        Parameters
        ----------
        points : NDArray of float32
            N x 3 points coordinates
        simplices : NDArray of uint32
            N x 4 connectivity matrix

        Note
        ----
        initialize triangles structure
        """
        Visual.__init__(self, vcode=vert, fcode=frag)

        # set data
        self.shared_program.vert['position'] = gloo.VertexBuffer(points)
        if vertex_color is None:
            vertex_color = np.ones((points.shape[0], 4), dtype=np.float32)
        else:
            assert vertex_color.shape[0] == points.shape[0]
            # vertex color may be grayscale
            if np.ndim(vertex_color) == 1:
                f = vertex_color[:, np.newaxis]
                v = np.repeat(f, 4, axis=1)
                v[:, -1] = 1.0
                vertex_color = v.astype(np.float32)
        self.shared_program['a_color'] = vertex_color

        # mask colors, alpha channel is not used when mask_color is given.
        if mask_color is None:
            mask_color = [1.0, 1.0, 1.0, alpha]
        self.shared_program['u_color'] = mask_color

        # build buffer
        if mode is 'triangles':
            vbo = sim2tri(simplices)
        elif mode is 'lines':
            vbo = sim2edge(simplices)
        else:
            raise ValueError('Drawing mode = ' + mode + ' not supported')
        self._index_buffer = gloo.IndexBuffer(vbo)

        # config OpenGL, 'translucent' or 'additive'
        self.set_gl_state('additive',
                          blend=True,
                          depth_test=False,
                          cull_face=False,
                          polygon_offset_fill=False,
                          polygon_offset=(1, 1))
        self._draw_mode = mode
Beispiel #8
0
    def __init__(self, vertices=None, faces=None, normals=None, lr_index=None,
                 hemisphere='both', sulcus=None, alpha=1., mask_color='orange',
                 camera=None, meshdata=None, invert_normals=False):
        """Init."""
        self._camera = None
        self._translucent = True
        self._alpha = alpha
        self._hemisphere = hemisphere
        self._n_overlay = 0
        self._data_lim = []

        # Initialize the vispy.Visual class with the vertex / fragment buffer :
        Visual.__init__(self, vcode=VERT_SHADER, fcode=FRAG_SHADER)

        # _________________ BUFFERS _________________
        # Vertices / faces / normals / color :
        def_3 = np.zeros((0, 3), dtype=np.float32)
        self._vert_buffer = gloo.VertexBuffer(def_3)
        self._normals_buffer = gloo.VertexBuffer(def_3)
        self._bgd_buffer = gloo.VertexBuffer()
        self._xrange_buffer = gloo.VertexBuffer()
        self._alphas_buffer = gloo.VertexBuffer()
        self._index_buffer = gloo.IndexBuffer()

        # _________________ PROGRAMS _________________
        self.shared_program.vert['a_position'] = self._vert_buffer
        self.shared_program.vert['a_normal'] = self._normals_buffer
        self.shared_program.vert['u_n_overlays'] = self._n_overlay
        self.shared_program.frag['u_alpha'] = alpha

        # _________________ LIGHTS _________________
        self.shared_program.frag['u_light_intensity'] = LIGHT_INTENSITY
        self.shared_program.frag['u_coef_ambient'] = COEF_AMBIENT
        self.shared_program.frag['u_coef_specular'] = COEF_SPECULAR
        self.shared_program.frag['u_light_position'] = LIGHT_POSITION
        self.shared_program.frag['camtf'] = vist.NullTransform()

        # _________________ DATA / CAMERA / LIGHT _________________
        # Data :
        self.set_data(vertices, faces, normals, hemisphere, lr_index,
                      invert_normals, sulcus, meshdata)
        # Camera :
        self.set_camera(camera)
        self.mask_color = mask_color

        # _________________ GL STATE _________________
        self.set_gl_state('translucent', depth_test=True, cull_face=False,
                          blend=True, blend_func=('src_alpha',
                                                  'one_minus_src_alpha'))
        self._draw_mode = 'triangles'
        self.freeze()
Beispiel #9
0
    def __init__(self, parent):
        self._parent = parent
        self._pos_vbo = gloo.VertexBuffer()
        self._color_vbo = gloo.VertexBuffer()

        Visual.__init__(self,
                        vcode=self.VERTEX_SHADER,
                        fcode=self.FRAGMENT_SHADER,
                        gcode=None)

        self._draw_mode = 'lines'
        self._connect = 'segments'
        self.set_gl_state('translucent', depth_test=False)
        self.freeze()
Beispiel #10
0
    def __init__(self, vertices=None, faces=None, normals=None, sulcus=None,
                 alpha=1., camera=None):
        """Init."""
        self._camera = None
        self._camera_transform = vist.NullTransform()
        self._translucent = True
        self._alpha = alpha
        self._n_overlay = 0
        self._data_lim = []
        self._colormaps = []

        # Initialize the vispy.Visual class with the vertex / fragment buffer :
        Visual.__init__(self, vcode=VERT_SHADER, fcode=FRAG_SHADER)

        # _________________ BUFFERS _________________
        # Vertices / faces / normals / color :
        def_3 = np.zeros((0, 3), dtype=np.float32)
        self._vert_buffer = gloo.VertexBuffer(def_3)
        self._normals_buffer = gloo.VertexBuffer(def_3)
        self._bgd_buffer = gloo.VertexBuffer()
        self._xrange_buffer = gloo.VertexBuffer()
        self._alphas_buffer = gloo.VertexBuffer()
        self._index_buffer = gloo.IndexBuffer()

        # _________________ PROGRAMS _________________
        self.shared_program.vert['a_position'] = self._vert_buffer
        self.shared_program.vert['a_normal'] = self._normals_buffer
        self.shared_program.vert['u_n_overlays'] = self._n_overlay
        self.shared_program.frag['u_alpha'] = alpha

        # _________________ TEXTURE _________________
        color_1d = np.c_[np.array([1.] * 4), np.array(SULCUS_COLOR)].T
        text_1d = gloo.Texture1D(color_1d.astype(np.float32))
        self.shared_program.vert['u_bgd_text'] = text_1d

        # _________________ LIGHTS _________________
        self.shared_program.frag['u_light_intensity'] = LIGHT_INTENSITY
        self.shared_program.frag['u_coef_ambient'] = COEF_AMBIENT

        # _________________ DATA / CAMERA / LIGHT _________________
        self.set_data(vertices, faces, normals, sulcus)
        self.set_camera(camera)

        # _________________ GL STATE _________________
        self.set_gl_state('translucent', depth_test=True, cull_face=False,
                          blend=True, blend_func=('src_alpha',
                                                  'one_minus_src_alpha'))
        self._draw_mode = 'triangles'
        self.freeze()
Beispiel #11
0
 def __init__(self, positions, colors):
     Visual.__init__(self, vertex_shader, fragment_shader)
     self.positions = positions
     self.colors = colors
     self.frames = self.positions.shape[0]
     self._vertices = gloo.VertexBuffer()
     self.set_vertex_data(0)
     self._draw_mode = 'points'
     self.texture = gloo.Texture2D(load_star_image(),
                                   interpolation='linear')
     self.shared_program['u_texture'] = self.texture
     self.shared_program.vert['color'] = self.colors
     self.pointsize = 5
     self.set_gl_state(clear_color=(0.0, 0.0, 0.03, 1.0),
                       depth_test=False,
                       blend=True,
                       blend_func=('src_alpha', 'one'))
Beispiel #12
0
    def __init__(self, data):
        Visual.__init__(self, self.VERTEX_SHADER, self.FRAGMENT_SHADER)

        nsignals, nsamples = data.shape
        # nsamples, nsignals = data.shape

        self._data = data

        a_index = np.c_[np.repeat(np.arange(nsignals), nsamples),
                        np.tile(np.arange(nsamples), nsignals)
                        ].astype(np.float32)

        # Doesn't seem to work nor to be very efficient.
        # indices = nsignals * np.arange(nsamples)
        # indices = indices[None, :] + np.arange(nsignals)[:, None]
        # indices = indices.flatten().astype(np.uint32)
        # self._ibuffer = gloo.IndexBuffer(indices)

        self._buffer = gloo.VertexBuffer(data.reshape(-1, 1))
        self.shared_program['a_position'] = self._buffer
        self.shared_program['a_index'] = a_index

        x_transform = Function(X_TRANSFORM)
        x_transform['nsamples'] = nsamples
        self.shared_program.vert['get_x'] = x_transform

        y_transform = Function(Y_TRANSFORM)
        y_transform['scale'] = Variable('uniform float u_signal_scale', 1.)
        y_transform['nsignals'] = nsignals
        self.shared_program.vert['get_y'] = y_transform
        self._y_transform = y_transform

        colormap = Function(DISCRETE_CMAP)
        rng = np.random.RandomState(0)
        cmap = rng.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)
        colormap['ncolors'] = nsignals
        self.shared_program.frag['get_color'] = colormap
        self._draw_mode = 'line_strip'
        self.set_gl_state('translucent', depth_test=False)
Beispiel #13
0
    def __init__(self, meshdata, color=None, light_vec=(1, 0, 0)):
        Visual.__init__(self, vertex_shader, fragment_shader)

        v = meshdata.get_vertices(indexed='faces').astype(float32)
        self._vertices = VertexBuffer(v)

        v_norm = meshdata.get_vertex_normals(indexed='faces').astype(float32)
        self._normals = VertexBuffer(v_norm)

        if color is not None:
            if len(color) == 3:
                color = r_[array(color), 1.]
            self._colors = color

        else:
            v_col = meshdata.get_vertex_colors(indexed='faces').astype(float32)
            self._colors = VertexBuffer(v_col)

        self._light_vec = light_vec

        self._draw_mode = 'triangles'
        self.set_gl_state('opaque', depth_test=True, cull_face=True)
Beispiel #14
0
    def __init__(self, data, rect=(0, 0, 1, 1), depth=0.0, **kwargs):
        self._data = data
        self._depth = depth
        vertices = np.array([(-1, -1), (-1, +1), (+1, -1), (+1, +1)],
                            dtype=np.float32)
        r = self._rect = rect
        texCoord = np.array([(r[0], r[1]), (r[0], r[1] + r[3]),
                             (r[0] + r[2], r[1]), (r[0] + r[2], r[1] + r[3])],
                            dtype=np.float32)

        self._texNeedUpdate = False
        self._texCoordNeedUpdate = False
        self._depthNeedUpdate = False

        Visual.__init__(self, VERTEX_SHADER, FRAGMENT_SHADER)
        self.shared_program["position"] = VertexBuffer(vertices)
        self.shared_program["texCoord"] = VertexBuffer(texCoord)
        self.shared_program['depth'] = self._depth
        self.shared_program['texture'] = self._data
        self.set_gl_state(blend=True,
                          blend_func=('src_alpha', 'one_minus_src_alpha'))
        self._draw_mode = 'triangle_strip'
Beispiel #15
0
    def __init__(self, pos, domain=(0., 1.), tick_direction=(-1., 0.),
                 scale_type="linear", axis_color=(1, 1, 1),
                 tick_color=(0.7, 0.7, 0.7), **kwargs):
        Visual.__init__(self, **kwargs)
        if scale_type != 'linear':
            raise NotImplementedError('only linear scaling is currently '
                                      'supported')
        self.pos = np.array(pos, float)
        self.domain = domain
        self.tick_direction = np.array(tick_direction, float)
        self.tick_direction = self.tick_direction
        self.scale_type = scale_type
        self.axis_color = axis_color
        self.tick_color = tick_color

        self.minor_tick_length = 5  # px
        self.major_tick_length = 10  # px
        self.label_margin = 5  # px

        self._text = None
        self._line = None
        self._ticks = None
Beispiel #16
0
    def __init__(self, meshdata):
        Visual.__init__(self, VERT_SHADER, FRAG_SHADER)

        v = meshdata.get_vertices(indexed='faces').astype(float32)
        self._vertices = VertexBuffer(v)

        v_norm = meshdata.get_vertex_normals(indexed='faces').astype(float32)
        self._normals = VertexBuffer(v_norm)

        v_col = meshdata.get_vertex_colors(indexed='faces').astype(float32)
        self._colors = VertexBuffer(v_col)

        self.set_light(
            position=(1., 0., 0.),
            ambient=.2,
            diffuse=.8,
        )
        self._draw_mode = 'triangles'
        # self.set_gl_state('opaque', depth_test=True, cull_face=True)
        self.set_gl_state('translucent',
                          depth_test=True,
                          cull_face=False,
                          blend=True,
                          blend_func=('src_alpha', 'one_minus_src_alpha'))
Beispiel #17
0
    def __init__(self, root, aggregatedTexture, light=None, camera=None):
        Visual.__init__(self, *aggregatedTexture.generateShaderCode())

        # GL init and settings
        self._draw_mode = 'triangles'
        wrappers.set_cull_face(mode='back')
        self.set_gl_state('opaque', depth_test=True, cull_face=True)

        # Default arguments
        if light is None:
            light = SimpleLight
        self.light = light(parent=self)

        if camera is None:
            raise RuntimeError('Default camera is not yet supported')
        self.camera = camera

        # Set mesh root node
        self.root = root

        # Initialize buffers
        self._vertexBuffer = None
        self._normalBuffer = None
        self._materialIDBuffer = None
        self._textureCoordinateBuffer = None
        self._textureBuffer = aggregatedTexture

        # Bind the texture buffer
        self.shared_program['aggregatedTexture'] = self._textureBuffer.build()
        self.shared_program.vert[
            'aggregatedTextureWidth'] = aggregatedTexture.shape[0]
        self.shared_program.vert[
            'aggregatedTextureHeight'] = aggregatedTexture.shape[1]

        self.updateLight()
        self.updateMesh()
Beispiel #18
0
    def __init__(self,
                 vertices,
                 faces,
                 colors=None,
                 texture=None,
                 textureCoordinates=None,
                 light=None,
                 ambientMaterialConstant=0.5,
                 diffuseMaterialConstant=0.4,
                 specularMaterialConstant=0.3,
                 vertexShader=defaultVertexShader,
                 fragmentShader=defaultFragmentShader,
                 camera=None):
        Visual.__init__(self, vertexShader, fragmentShader)

        # Culling mode (for debugging)
        #wrappers.set_cull_face(mode='back')

        # Default arguments
        if colors is None and texture is None:
            colors = np.array([(0.5, 0.5, 0.5)
                               for index in range(vertices.shape[0])],
                              dtype=np.float32)
        elif colors is not None and len(colors) is 3 and (isinstance(
                colors[0], float) or isinstance(colors[0], int)):
            colors = np.array([colors for index in range(len(vertices))],
                              dtype=np.float32)

        if light is None:
            light = SimpleLight(self, color=(1.0, 1.0, 1.0))
        else:
            light = light(self)

        # Geometry setup
        self._meshData = MeshData(vertices=vertices,
                                  faces=faces,
                                  vertex_colors=colors)
        self._vertices = None
        self._colors = None
        self._texture = None
        self._textureCoordinates = None
        self._normals = None
        self._draw_mode = 'triangles'

        self.set_gl_state('opaque', depth_test=True, cull_face=True)

        # Light setup
        self._light = light
        self._camera = camera

        self._ambientMaterialConstant = ambientMaterialConstant
        self._diffuseMaterialConstant = diffuseMaterialConstant
        self._specularMaterialConstant = specularMaterialConstant

        # Initial updates
        self.updateMesh(vertices=vertices,
                        faces=faces,
                        colors=colors,
                        texture=texture,
                        textureCoordinates=textureCoordinates)
        self.updateLight()
Beispiel #19
0
    def __init__(self):

        Visual.__init__(self, vcode=vert, fcode=frag)
Beispiel #20
0
 def __init__(self):
     Visual.__init__(self, self.VERTEX_SHADER, self.FRAGMENT_SHADER)
     self._vert = []
     self._color = []
     self._draw_mode = 'lines'
Beispiel #21
0
    def __init__(self,
                 vertices=None,
                 faces=None,
                 normals=None,
                 lr_index=None,
                 hemisphere='both',
                 sulcus=None,
                 alpha=1.,
                 mask_color='orange',
                 light_position=[100.] * 3,
                 light_color=[1.] * 4,
                 light_intensity=[1.] * 3,
                 coef_ambient=.05,
                 coef_specular=.5,
                 vertfcn=None,
                 camera=None,
                 meshdata=None,
                 invert_normals=False):
        """Init."""
        self._camera = None
        self._camera_transform = vist.NullTransform()
        self._translucent = True
        self._alpha = alpha
        self._hemisphere = hemisphere

        # Initialize the vispy.Visual class with the vertex / fragment buffer :
        Visual.__init__(self, vcode=VERT_SHADER, fcode=FRAG_SHADER)

        # _________________ TRANSFORMATIONS _________________
        self._vertfcn = vist.NullTransform() if vertfcn is None else vertfcn

        # _________________ BUFFERS _________________
        # Vertices / faces / normals / color :
        def_3 = np.zeros((0, 3), dtype=np.float32)
        def_4 = np.zeros((0, 4), dtype=np.float32)
        self._vert_buffer = gloo.VertexBuffer(def_3)
        self._color_buffer = gloo.VertexBuffer(def_4)
        self._normals_buffer = gloo.VertexBuffer(def_3)
        self._mask_buffer = gloo.VertexBuffer()
        self._sulcus_buffer = gloo.VertexBuffer()
        self._index_buffer = gloo.IndexBuffer()

        # _________________ PROGRAMS _________________
        self.shared_program.vert['a_position'] = self._vert_buffer
        self.shared_program.vert['a_color'] = self._color_buffer
        self.shared_program.vert['a_normal'] = self._normals_buffer
        self.shared_program.frag['u_alpha'] = alpha

        # _________________ DATA / CAMERA / LIGHT _________________
        self.set_data(vertices, faces, normals, hemisphere, lr_index,
                      invert_normals, sulcus, meshdata)
        self.set_camera(camera)
        self.mask_color = mask_color
        self.light_color = light_color
        self.light_position = light_position
        self.light_intensity = light_intensity
        self.coef_ambient = coef_ambient
        self.coef_specular = coef_specular

        # _________________ GL STATE _________________
        self.set_gl_state('translucent',
                          depth_test=True,
                          cull_face=False,
                          blend=True,
                          blend_func=('src_alpha', 'one_minus_src_alpha'))
        self._draw_mode = 'triangles'
        self.freeze()
    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
Beispiel #23
0
 def draw(self, *args, **kwds):
     """Call when drawing only."""
     Visual.draw(self, *args, **kwds)
Beispiel #24
0
 def view(self):
     v = Visual.view(self)
     self._init_view(v)
     return v
    def __init__(self, n_volume_max=10, threshold=None, relative_step_size=0.8,
                 emulate_texture=False):

        # Choose texture class
        tex_cls = TextureEmulated3D if emulate_texture else Texture3D

        self._n_volume_max = n_volume_max
        self._initial_shape = True
        self._vol_shape = (10, 10, 10)
        self._need_vertex_update = True

        # Create OpenGL program
        vert_shader, frag_shader = get_shaders(n_volume_max)

        # We deliberately don't use super here because we don't want to call
        # VolumeVisual.__init__
        Visual.__init__(self, vcode=vert_shader, fcode=frag_shader)

        # Create gloo objects
        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.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 and default colormap to shader program
            self.shared_program['u_volumetex_{0}'.format(i)] = self.textures[i]
            self.shared_program.frag['cmap{0:d}'.format(i)] = Function(get_colormap('grays').glsl_map)

            # Make sure all textures are disbaled
            self.shared_program['u_enabled_{0}'.format(i)] = 0
            self.shared_program['u_weight_{0}'.format(i)] = 1

        self.shared_program['a_position'] = self._vertices
        self.shared_program['a_texcoord'] = self._texcoord
        self.shared_program['u_shape'] = self._vol_shape[::-1]
        self._draw_mode = 'triangle_strip'
        self._index_buffer = IndexBuffer()

        self.shared_program.frag['sampler_type'] = self.textures[0].glsl_sampler_type
        self.shared_program.frag['sample'] = self.textures[0].glsl_sample

        # 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)

        self.relative_step_size = relative_step_size

        self.volumes = defaultdict(dict)

        self._data_shape = None
        self._block_size = np.array([1,1,1])

        try:
            self.freeze()
        except AttributeError:  # Older versions of VisPy
            pass
Beispiel #26
0
 def draw(self, *args, **kwds):
     """Call when drawing only."""
     Visual.draw(self, *args, **kwds)
Beispiel #27
0
 def __init__(self):
     Visual.__init__(self, self.VERTEX_SHADER, self.FRAGMENT_SHADER)
     self._vert = []
     self._color = []
     self._draw_mode = 'lines'
Beispiel #28
0
    def __init__(self,
                 n_volume_max=10,
                 threshold=None,
                 relative_step_size=0.8,
                 emulate_texture=False):

        # Choose texture class
        tex_cls = TextureEmulated3D if emulate_texture else Texture3D

        self._n_volume_max = n_volume_max
        self._initial_shape = True
        self._vol_shape = (10, 10, 10)
        self._need_vertex_update = True

        # Create OpenGL program
        vert_shader, frag_shader = get_shaders(n_volume_max)

        # We deliberately don't use super here because we don't want to call
        # VolumeVisual.__init__
        Visual.__init__(self, vcode=vert_shader, fcode=frag_shader)

        # Create gloo objects
        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.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 and default colormap to shader program
            self.shared_program['u_volumetex_{0}'.format(i)] = self.textures[i]
            self.shared_program.frag['cmap{0:d}'.format(i)] = Function(
                get_colormap('grays').glsl_map)

            # Make sure all textures are disbaled
            self.shared_program['u_enabled_{0}'.format(i)] = 0
            self.shared_program['u_weight_{0}'.format(i)] = 1

        self.shared_program['a_position'] = self._vertices
        self.shared_program['a_texcoord'] = self._texcoord
        self.shared_program['u_shape'] = self._vol_shape[::-1]
        self._draw_mode = 'triangle_strip'
        self._index_buffer = IndexBuffer()

        self.shared_program.frag['sampler_type'] = self.textures[
            0].glsl_sampler_type
        self.shared_program.frag['sample'] = self.textures[0].glsl_sample

        # 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)

        self.relative_step_size = relative_step_size

        self.volumes = defaultdict(dict)

        self._data_shape = None
        self._block_size = np.array([1, 1, 1])

        try:
            self.freeze()
        except AttributeError:  # Older versions of VisPy
            pass