Esempio n. 1
0
def initialize_renderer():
    """Initialize the OpenGL renderer.

    For an OpenGL based renderer this sets up the viewport and creates
    the shader programs.

    """
    global fbuffer
    global fbuffer_prog
    global default_prog

    fbuffer = FrameBuffer()

    vertices = np.array(
        [[-1.0, -1.0], [+1.0, -1.0], [-1.0, +1.0], [+1.0, +1.0]], np.float32)
    texcoords = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]],
                         dtype=np.float32)

    fbuf_vertices = VertexBuffer(data=vertices)
    fbuf_texcoords = VertexBuffer(data=texcoords)

    fbuffer_prog = Program(src_fbuffer.vert, src_fbuffer.frag)
    fbuffer_prog['texcoord'] = fbuf_texcoords
    fbuffer_prog['position'] = fbuf_vertices

    default_prog = Program(src_default.vert, src_default.frag)

    reset_view()
Esempio n. 2
0
File: line.py Progetto: ds604/vispy
 def set_data(self, **kwds):
     """
     Keyword arguments:
     pos     (N, 2-3) array
     color   (3-4) or (N, 3-4) array
     width   scalar or (N,) array
     """
     self._opts.update(kwds)
     typ = [('pos', np.float32, self._opts['pos'].shape[-1])]
     if isinstance(self._opts['color'], np.ndarray):
         typ.append(('color', np.float32, self._opts['color'].shape[-1]))
     self._data = np.empty(self._opts['pos'].shape[:-1], typ)
     self._data['pos'] = self._opts['pos']
     if isinstance(self._opts['color'], np.ndarray):
         self._data['color'] = self._opts['color']
     
     self.vbo = VertexBuffer(data=self._data)
     #tex = np.zeros((len(self._data), 1, 3), dtype=np.float32)
     #tex[...,:2] = self._data['pos'][:,np.newaxis]
     
     # recast float to RGBA bytes
     d = self._data['pos'].astype(np.float32).view(np.ubyte).reshape(len(self._data), 2, 4)
     self.ptex = Texture2D(d)
     self.ptex.set_filter(gl.GL_NEAREST, gl.GL_NEAREST)
     
     self.indexes = VertexBuffer(data=np.arange(len(self._data)*2, dtype=np.float32))
Esempio n. 3
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()
    def __init__(self):
        app.Canvas.__init__(self)

        # Time
        self._t = time.time()
        self._pos = 0.0, 0.0
        self._button = None

        # Create program
        self.program = Program(VERT_SHADER, FRAG_SHADER)
        self.program['color'] = VertexBuffer(particles['color'], client=True)
        self.program['size'] = VertexBuffer(particles['size'], client=True)
    def __init__(self):
        app.Canvas.__init__(self)

        # Create program
        self._program = Program(VERT_SHADER, FRAG_SHADER)

        # Set uniforms and samplers
        self._program['a_position'] = VertexBuffer(positions)
        self._program['a_texcoord'] = VertexBuffer(texcoords)
        #
        self._program['u_texture1'] = Texture2D(im1)
        self._program['u_texture2'] = Texture2D(im2)
        self._program['u_texture3'] = Texture2D(im3)
    def __init__(self, data, relative_step_size=0.8,
                 emulate_texture=False):

        # Choose texture class
        tex_cls = TextureEmulated3D if emulate_texture else Texture3D

        # Storage of information of volume
        self._need_vertex_update = True

        # Create OpenGL program
        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))

        # Set up RGBA texture
        self.texture = tex_cls((10, 10, 10, 4), interpolation='linear',
                                                wrapping='clamp_to_edge')
        self.texture.set_data(data.astype(np.float32))
        self.shared_program['u_volumetex'] = self.texture

        self._vol_shape = data.shape[:-1]
        self.shared_program['u_shape'] = self._vol_shape[::-1]

        self.shared_program['a_position'] = self._vertices
        self.shared_program['a_texcoord'] = self._texcoord

        self._draw_mode = 'triangle_strip'
        self._index_buffer = IndexBuffer()

        self.shared_program.frag['sampler_type'] = self.texture.glsl_sampler_type
        self.shared_program.frag['sample'] = self.texture.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.freeze()
Esempio n. 7
0
    def updateMesh(self,
                   vertices=None,
                   faces=None,
                   colors=None,
                   texture=None,
                   textureCoordinates=None):
        # Set
        if vertices is not None:
            self._meshData.set_vertices(verts=vertices)
        if faces is not None:
            self._meshData.set_faces(faces)
        if colors is not None:
            self._meshData.set_vertex_colors(colors)

        # Update
        if vertices is not None or faces is not None:
            self._vertices = VertexBuffer(
                self._meshData.get_vertices(indexed='faces').astype(
                    np.float32))
        if faces is not None and vertices is not None:
            self._normals = VertexBuffer(
                self._meshData.get_vertex_normals(indexed='faces').astype(
                    np.float32))
        if colors is not None:
            self._colors = VertexBuffer(
                self._meshData.get_vertex_colors(indexed='faces').astype(
                    np.float32))
        if texture is not None:
            self._texture = Texture2D(np.array(texture, dtype=np.float32),
                                      interpolation='linear',
                                      wrapping='mirrored_repeat')
        if textureCoordinates is not None:
            textureMesh = MeshData(vertices=textureCoordinates,
                                   faces=self._meshData.get_faces())
            self._textureCoordinates = VertexBuffer(
                textureMesh.get_vertices(indexed='faces').astype(np.float32))

        # Update GPU - geometry
        self.shared_program.vert['position'] = self._vertices
        self.shared_program.vert['normal'] = self._normals

        # Update GPU - color
        if self._texture is None:
            self.shared_program.vert['color'] = self._colors
        else:
            self.shared_program.vert[
                'textureCoordinates'] = self._textureCoordinates
            self.shared_program['u_objectTexture'] = self._texture
Esempio n. 8
0
    def __init__(self, texture, texcoords, enabled=True):
        """Apply a texture on a mesh."""
        vfunc = Function("""
            void pass_coords() {
                $v_texcoords = $texcoords;
            }
        """)
        ffunc = Function("""
            void apply_texture() {
                if ($enabled == 1) {
                    gl_FragColor *= texture2D($u_texture, $texcoords);
                }
            }
        """)
        self._texcoord_varying = Varying('v_texcoord', 'vec2')
        vfunc['v_texcoords'] = self._texcoord_varying
        ffunc['texcoords'] = self._texcoord_varying
        self._texcoords_buffer = VertexBuffer(
            np.zeros((0, 2), dtype=np.float32)
        )
        vfunc['texcoords'] = self._texcoords_buffer
        super().__init__(vcode=vfunc, vhook='pre', fcode=ffunc)

        self.enabled = enabled
        self.texture = texture
        self.texcoords = texcoords
Esempio n. 9
0
    def __init__(self, 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', **kwargs):
        Visual.__init__(self, vcode=vertex_template, fcode=fragment_template,
                        **kwargs)
        self.set_gl_state('translucent', depth_test=True, cull_face=False)

        self.events.add(data_updated=Event)

        # Define buffers
        self._vertices = VertexBuffer(np.zeros((0, 3), dtype=np.float32))
        self._cmap = get_colormap('cubehelix')
        self._clim = 'auto'

        # Uniform color
        self._color = Color(color)

        # add filters for various modifiers
        self.shading_filter = None
        self.shading = shading

        # Init
        self._bounds = None
        # Note we do not call subclass set_data -- often the signatures
        # do no match.
        MeshVisual.set_data(
            self, vertices=vertices, faces=faces, vertex_colors=vertex_colors,
            face_colors=face_colors, vertex_values=vertex_values,
            meshdata=meshdata, color=color)

        # primitive mode
        self._draw_mode = mode

        self.freeze()
Esempio n. 10
0
    def setup_features(self):
        verts = np.zeros(
            0, [('position', np.float32, 3), ('normal', np.float32, 3),
                ('color', np.float32, 3)])  #start with an empty array

        all_feature_groups = self.current_data['features']
        if self.render_params['top_dogs_only'] or all_feature_groups == None:
            all_feature_groups = self.current_data['top_dog_features']

        colors = distinct_colors(2)

        base_roof_color = [0.35, 0.35, 0.35]

        wallcolor = [0.72, 0.72, 0.72]
        yellow = [1, 0.76, 0]
        topwallcolor = [0.94, 0.94, 0.99]

        origin = [0, 0]

        for feature_group, gid in zip(all_feature_groups,
                                      range(len(all_feature_groups))):

            feature_group_wall_color = yellow
            feature_roof_color = base_roof_color

            top_roof_colors = distinct_colors(len(feature_group))

            if self.render_params['top_dogs_only'] or self.__bfps[
                    gid].id in self.__top_dogs:
                feature_group_wall_color = topwallcolor

            for feature, fid in zip(feature_group, range(len(feature_group))):
                get_verts = feature['roof'].get_gl_vertex_data(origin)
                data = np.zeros(len(get_verts), [('position', np.float32, 3),
                                                 ('normal', np.float32, 3),
                                                 ('color', np.float32, 3)])
                data['position'] = get_verts['position']
                data['normal'] = get_verts['normal']
                data['color'] = feature_roof_color
                if self.render_params['top_dogs_only'] or self.__bfps[
                        gid].id in self.__top_dogs:
                    data['color'] = top_roof_colors[fid]
                if self.render_params['debug_colors']:
                    data['color'] = top_roof_colors[fid]

                verts = np.concatenate([verts, data])

                get_verts = feature['walls'].get_gl_vertex_data(origin)
                data = np.zeros(len(get_verts), [('position', np.float32, 3),
                                                 ('normal', np.float32, 3),
                                                 ('color', np.float32, 3)])
                data['position'] = get_verts['position']
                data['normal'] = get_verts['normal']
                data['color'] = feature_group_wall_color
                if self.render_params['debug_colors']:
                    data['color'] = [i * 1.3 for i in top_roof_colors[fid]]

                verts = np.concatenate([verts, data])

        self.program_solids.bind(VertexBuffer(verts))
Esempio n. 11
0
    def __init__(self):
        app.Canvas.__init__(self,
                            size=(512, 512),
                            title='Textured cube',
                            keys='interactive')
        self.timer = app.Timer('auto', self.on_timer)

        # Build cube data
        V, I, _ = create_cube()
        vertices = VertexBuffer(V)
        self.indices = IndexBuffer(I)

        # Build program
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        view = np.eye(4, dtype=np.float32)
        model = np.eye(4, dtype=np.float32)
        translate(view, 0, 0, -5)
        self.program['model'] = model
        self.program['view'] = view
        self.program['texture'] = checkerboard()

        self.phi, self.theta = 0, 0

        # OpenGL initalization
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True)
        self.timer.start()
Esempio n. 12
0
    def __init__(self, *args, **kwargs):
        '''Drawable(*args, **kwargs) -> Drawable
        Everything is tracked internally, different drawables will handle things differently
        Inherit from this for all drawables.

        Inheriting:
            You must define a make_mesh, make_shaders, and draw method. 
            If you do not make shaders, you will get a default
            If you do not make a mesh, you'll get a square that takes up the screen

        '''
        self.model = np.eye(4)
        self.view = np.eye(4)
        self.projection = np.eye(4)

        self.mesh = self.make_mesh()
        self.vert_shader, self.frag_shader = self.make_shaders()
        self.program = Program(self.vert_shader, self.frag_shader)
        self.program.bind(VertexBuffer(self.mesh))
        if hasattr(self, make_texture):
            self.texture = self.make_texture()
            assert isinstance(self.texture,
                              Texture2D), "Texture passed is not a texture!"

        self.program['texture'] = self.texture
        cube["texture"].interpolation = 'linear'
    def _update(self):
        """ Update vertex buffers & texture """

        if self._vertices_buffer is not None:
            self._vertices_buffer.delete()
        self._vertices_buffer = VertexBuffer(self._vertices_list.data)

        if self.itype is not None:
            if self._indices_buffer is not None:
                self._indices_buffer.delete()
            self._indices_buffer = IndexBuffer(self._indices_list.data)

        if self.utype is not None:
            if self._uniforms_texture is not None:
                self._uniforms_texture.delete()

            # We take the whole array (_data), not the data one
            texture = self._uniforms_list._data.view(np.float32)
            size = len(texture) / self._uniforms_float_count
            shape = self._compute_texture_shape(size)

            # shape[2] = float count is only used in vertex shader code
            texture = texture.reshape(shape[0], shape[1], 4)
            self._uniforms_texture = Texture2D(texture)
            self._uniforms_texture.data = texture
            self._uniforms_texture.interpolation = "nearest"

        if len(self._programs):
            for program in self._programs:
                program.bind(self._vertices_buffer)
                if self._uniforms_list is not None:
                    program["uniforms"] = self._uniforms_texture
                    program["uniforms_shape"] = self._ushape
Esempio n. 14
0
    def __init__(self, texture, texcoords, enabled=True):
        """Apply a texture on a mesh.

        Parameters
        ----------
        texture : (M, N) or (M, N, C) array
            The 2D texture image.
        texcoords : (N, 2) array
            The texture coordinates.
        enabled : bool
            Whether the display of the texture is enabled.
        """
        vfunc = Function("""
            void pass_coords() {
                $v_texcoords = $texcoords;
            }
        """)
        ffunc = Function("""
            void apply_texture() {
                if ($enabled == 1) {
                    gl_FragColor *= texture2D($u_texture, $texcoords);
                }
            }
        """)
        self._texcoord_varying = Varying('v_texcoord', 'vec2')
        vfunc['v_texcoords'] = self._texcoord_varying
        ffunc['texcoords'] = self._texcoord_varying
        self._texcoords_buffer = VertexBuffer(
            np.zeros((0, 2), dtype=np.float32))
        vfunc['texcoords'] = self._texcoords_buffer
        super().__init__(vcode=vfunc, vhook='pre', fcode=ffunc)

        self.enabled = enabled
        self.texture = texture
        self.texcoords = texcoords
Esempio n. 15
0
 def on_initialize(self, event):
     # Note: read as bytes, then decode; py2.6 compat
     with open(op.join(this_dir, 'vertex_vispy.glsl'), 'rb') as fid:
         vert = fid.read().decode('ASCII')
     with open(op.join(this_dir, 'fragment_seed.glsl'), 'rb') as f:
         frag_seed = f.read().decode('ASCII')
     with open(op.join(this_dir, 'fragment_flood.glsl'), 'rb') as f:
         frag_flood = f.read().decode('ASCII')
     with open(op.join(this_dir, 'fragment_display.glsl'), 'rb') as f:
         frag_display = f.read().decode('ASCII')
     self.programs = [
         Program(vert, frag_seed),
         Program(vert, frag_flood),
         Program(vert, frag_display)
     ]
     # Initialize variables
     # using two FBs slightly faster than switching on one
     self.fbo_to = [FrameBuffer(), FrameBuffer()]
     self._setup_textures('shape1.tga')
     vtype = np.dtype([('position', 'f4', 2), ('texcoord', 'f4', 2)])
     vertices = np.zeros(4, dtype=vtype)
     vertices['position'] = [[-1., -1.], [-1., 1.], [1., -1.], [1., 1.]]
     vertices['texcoord'] = [[0., 0.], [0., 1.], [1., 0.], [1., 1.]]
     vertices = VertexBuffer(vertices)
     for program in self.programs:
         program.bind(vertices)
Esempio n. 16
0
    def setup_bfps(self):

        verts = np.zeros(
            0, [('position', np.float32, 3), ('normal', np.float32, 3),
                ('color', np.float32, 3)])  #start with an empty array
        colors = distinct_colors(2)

        for i in range(len(self.__solids)):
            if self.render_params['top_dogs_only']:
                if self.__bfps[i].id in self.__top_dogs:
                    get_verts = self.__solids[i].get_gl_vertex_data(
                        self.__offset)
                    data = np.zeros(len(get_verts),
                                    [('position', np.float32, 3),
                                     ('normal', np.float32, 3),
                                     ('color', np.float32, 3)])
                    data['position'] = get_verts['position']
                    data['normal'] = get_verts['normal']
                    data['color'] = colors[1]
                    verts = np.concatenate([verts, data])
            else:
                get_verts = self.__solids[i].get_gl_vertex_data(self.__offset)
                data = np.zeros(len(get_verts), [('position', np.float32, 3),
                                                 ('normal', np.float32, 3),
                                                 ('color', np.float32, 3)])
                data['position'] = get_verts['position']
                data['normal'] = get_verts['normal']
                if self.__bfps[i].id in self.__top_dogs:
                    data['color'] = colors[1]
                else:
                    data['color'] = colors[0]
                verts = np.concatenate([verts, data])

        self.program_solids.bind(VertexBuffer(verts))
Esempio n. 17
0
    def render_image(self, image, location, size):
        """Render the image.

		:param image: image to be rendered
		:type image: builtins.Image

		:param location: top-left corner of the image
		:type location: tuple | list | builtins.Vector

		:param size: target size of the image to draw.
		:type size: tuple | list | builtins.Vector
		"""
        self.flush_geometry()

        self.texture_prog[
            'fill_color'] = self.tint_color if self.tint_enabled else self.COLOR_WHITE
        self.texture_prog['transform'] = self.transform_matrix.T.flatten()

        x, y = location
        sx, sy = size
        imx, imy = image.size
        data = np.zeros(4,
                        dtype=[('position', np.float32, 2),
                               ('texcoord', np.float32, 2)])
        data['texcoord'] = np.array(
            [[0.0, 1.0], [1.0, 1.0], [0.0, 0.0], [1.0, 0.0]], dtype=np.float32)
        data['position'] = np.array(
            [[x, y + sy], [x + sx, y + sy], [x, y], [x + sx, y]],
            dtype=np.float32)

        self.texture_prog['texture'] = image._texture
        self.texture_prog.bind(VertexBuffer(data))
        self.texture_prog.draw('triangle_strip')
Esempio n. 18
0
    def on_initialize(self, event):
        # Build cube data
        V, F, O = create_cube()
        vertices = VertexBuffer(V)
        self.faces = IndexBuffer(F)
        self.outline = IndexBuffer(O)

        # Build view, model, projection & normal
        # --------------------------------------
        self.view = np.eye(4, dtype=np.float32)
        model = np.eye(4, dtype=np.float32)
        translate(self.view, 0, 0, -5)
        normal = np.array(np.matrix(np.dot(self.view, model)).I.T)

        # Build program
        # --------------------------------------
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)
        self.program["u_light_position"] = 2, 2, 2
        self.program["u_light_intensity"] = 1, 1, 1
        self.program["u_model"] = model
        self.program["u_view"] = self.view
        self.program["u_normal"] = normal
        self.phi, self.theta = 0, 0

        # OpenGL initalization
        # --------------------------------------
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True,
                       polygon_offset=(1, 1),
                       blend_func=('src_alpha', 'one_minus_src_alpha'),
                       line_width=0.75)
        self.timer.start()
Esempio n. 19
0
    def __init__(self):
        app.Canvas.__init__(self,
                            title='Rain [Move mouse]',
                            size=(512, 512),
                            keys='interactive')

        # Build data
        # --------------------------------------
        n = 500
        self.data = np.zeros(n, [('a_position', np.float32, 2),
                                 ('a_fg_color', np.float32, 4),
                                 ('a_size', np.float32, 1)])
        self.index = 0
        self.program = Program(vertex, fragment)
        self.vdata = VertexBuffer(self.data)
        self.program.bind(self.vdata)
        self.program['u_antialias'] = 1.00
        self.program['u_linewidth'] = 1.00
        self.program['u_model'] = np.eye(4, dtype=np.float32)
        self.program['u_view'] = np.eye(4, dtype=np.float32)

        self.activate_zoom()

        gloo.set_clear_color('white')
        gloo.set_state(blend=True,
                       blend_func=('src_alpha', 'one_minus_src_alpha'))
        self.timer = app.Timer('auto', self.on_timer, start=True)

        self.show()
Esempio n. 20
0
    def __init__(self, shading='flat',
                 ambient_coefficient=(1, 1, 1, 1),
                 diffuse_coefficient=(1, 1, 1, 1),
                 specular_coefficient=(1, 1, 1, 1),
                 shininess=100,
                 light_dir=(10, 5, -5),
                 ambient_light=(1, 1, 1, .25),
                 diffuse_light=(1, 1, 1, 0.7),
                 specular_light=(1, 1, 1, .25),
                 enabled=True):
        self._shading = shading

        self._ambient_coefficient = _as_rgba(ambient_coefficient)
        self._diffuse_coefficient = _as_rgba(diffuse_coefficient)
        self._specular_coefficient = _as_rgba(specular_coefficient)
        self._shininess = shininess

        self._light_dir = light_dir
        self._ambient_light = _as_rgba(ambient_light)
        self._diffuse_light = _as_rgba(diffuse_light)
        self._specular_light = _as_rgba(specular_light)

        self._enabled = enabled

        vfunc = Function(shading_vertex_template)
        ffunc = Function(shading_fragment_template)

        self._normals = VertexBuffer(np.zeros((0, 3), dtype=np.float32))
        vfunc['normal'] = self._normals

        super().__init__(vcode=vfunc, fcode=ffunc)
Esempio n. 21
0
    def on_initialize(self, event):
        self.rho = 0.0
        # Build cube data
        # --------------------------------------
        self.checker = Program(cube_vertex, cube_fragment)
        self.checker['texture'] = checkerboard()
        self.checker['position'] = [(-1, -1), (-1, +1), (+1, -1), (+1, +1)]
        self.checker['texcoord'] = [(0, 0), (0, 1), (1, 0), (1, 1)]

        # sheet, indices = make_sheet((960, 1080))
        # sheet_buffer = VertexBuffer(sheet)

        left_eye = Texture2D((960, 1080, 3), interpolation='linear')
        self.left_eye_buffer = FrameBuffer(left_eye, RenderBuffer((960, 1080)))
        # Build program
        # --------------------------------------
        self.view = np.eye(4, dtype=np.float32)
        self.program = Program(vertex, fragment)
        distortion_buffer = VertexBuffer(make_distortion())
        self.program.bind(distortion_buffer)
        self.program['rotation'] = self.view
        self.program['texture'] = left_eye

        # OpenGL and Timer initalization
        # --------------------------------------
        set_state(clear_color=(.3, .3, .35, 1), depth_test=True)
        self.timer = app.Timer('auto', connect=self.on_timer, start=True)
        self._set_projection(self.size)
Esempio n. 22
0
    def __init__(self):
        app.Canvas.__init__(self)
        self.position = 50, 50
        self.size = 512, 512

        self.program = Program(VS, FS)
        self.tex = Texture2D(data1)
        self.program['a_position'] = VertexBuffer(positions)
        self.program['a_texcoord'] = VertexBuffer(texcoords)
        self.program['u_tex'] = self.tex

        self._timer = app.Timer(.01)
        self._timer.connect(self.on_timer)
        self._timer.start()

        self.measure_fps(.05, callback=self.fps_callback)
Esempio n. 23
0
    def on_initialize(self, event):
        # Build cube data
        V, I, O = create_cube()
        vertices = VertexBuffer(V)
        self.faces = IndexBuffer(I)
        self.outline = IndexBuffer(O)

        # Build program
        # --------------------------------------
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        # --------------------------------------
        view = np.eye(4, dtype=np.float32)
        model = np.eye(4, dtype=np.float32)
        translate(view, 0, 0, -5)
        self.program['u_model'] = model
        self.program['u_view'] = view
        self.phi, self.theta = 0, 0

        # OpenGL initalization
        # --------------------------------------
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00),
                       depth_test=True,
                       polygon_offset=(1, 1),
                       line_width=0.75,
                       blend_func=('src_alpha', 'one_minus_src_alpha'))
        self.timer.start()
Esempio n. 24
0
    def __init__(self):
        app.Canvas.__init__(self,
                            size=(512, 512),
                            title='Colored cube',
                            keys='interactive')

        # Build cube data
        V, I, _ = create_cube()
        vertices = VertexBuffer(V)
        self.indices = IndexBuffer(I)

        # Build program
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        view = translate((0, 0, -5))
        model = np.eye(4, dtype=np.float32)
        self.program['model'] = model
        self.program['view'] = view
        self.phi, self.theta = 0, 0
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00), depth_test=True)

        self.activate_zoom()

        self.timer = app.Timer('auto', self.on_timer, start=True)

        self.show()
Esempio n. 25
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.timer = app.Timer('auto', connect=self.on_timer, start=True)

        with open('vertex.glsl') as f:
            self.vshader = f.read()
        with open('fragment.glsl') as f:
            self.fshader = f.read()
        self.program = Program(self.vshader, self.fshader)

        v, i, iOutline = create_cube()
        self.vertices = VertexBuffer(v)
        self.indices = IndexBuffer(i)
        self.outlineIndices = IndexBuffer(iOutline)
        self.program.bind(self.vertices)

        self.theta, self.phi = 0, 0
        self.program['model'] = np.eye(4)
        self.program['view'] = translate([0, 0, -5])

        self.program['texture'] = checkerboard()
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00),
                       polygon_offset=(1, 1),
                       blend_func=('src_alpha', 'one_minus_src_alpha'),
                       line_width=5,
                       depth_test=True)
Esempio n. 26
0
    def __init__(self):
        self.use_shaders = True
        app.Canvas.__init__(self, size=(512, 512), keys='interactive')
        # Note: read as bytes, then decode; py2.6 compat
        with open(op.join(this_dir, 'vertex_vispy.glsl'), 'rb') as fid:
            vert = fid.read().decode('ASCII')
        with open(op.join(this_dir, 'fragment_seed.glsl'), 'rb') as f:
            frag_seed = f.read().decode('ASCII')
        with open(op.join(this_dir, 'fragment_flood.glsl'), 'rb') as f:
            frag_flood = f.read().decode('ASCII')
        with open(op.join(this_dir, 'fragment_display.glsl'), 'rb') as f:
            frag_display = f.read().decode('ASCII')
        self.programs = [
            Program(vert, frag_seed),
            Program(vert, frag_flood),
            Program(vert, frag_display)
        ]
        # Initialize variables
        # using two FBs slightly faster than switching on one
        self.fbo_to = [FrameBuffer(), FrameBuffer()]
        self._setup_textures('shape1.tga')
        vtype = np.dtype([('position', 'f4', 2), ('texcoord', 'f4', 2)])
        vertices = np.zeros(4, dtype=vtype)
        vertices['position'] = [[-1., -1.], [-1., 1.], [1., -1.], [1., 1.]]
        vertices['texcoord'] = [[0., 0.], [0., 1.], [1., 0.], [1., 1.]]
        vertices = VertexBuffer(vertices)
        for program in self.programs:
            program.bind(vertices)
        self._timer = app.Timer('auto', self.update, start=True)

        self.show()
Esempio n. 27
0
    def __init__(self):
        app.Canvas.__init__(self, keys='interactive')

        # This size is used for comparison with agg (via matplotlib)
        self.size = 512, 512 + 2 * 32
        self.title = "Markers demo [press space to change marker]"

        self.vbo = VertexBuffer(data)
        self.view = np.eye(4, dtype=np.float32)
        self.model = np.eye(4, dtype=np.float32)
        self.projection = ortho(0, self.size[0], 0, self.size[1], -1, 1)
        self.programs = [
            Program(markers.vert, markers.frag + markers.tailed_arrow),
            Program(markers.vert, markers.frag + markers.disc),
            Program(markers.vert, markers.frag + markers.diamond),
            Program(markers.vert, markers.frag + markers.square),
            Program(markers.vert, markers.frag + markers.cross),
            Program(markers.vert, markers.frag + markers.arrow),
            Program(markers.vert, markers.frag + markers.vbar),
            Program(markers.vert, markers.frag + markers.hbar),
            Program(markers.vert, markers.frag + markers.clobber),
            Program(markers.vert, markers.frag + markers.ring)
        ]

        for program in self.programs:
            program.bind(self.vbo)
            program["u_antialias"] = u_antialias,
            program["u_size"] = 1
            program["u_model"] = self.model
            program["u_view"] = self.view
            program["u_projection"] = self.projection
        self.index = 0
        self.program = self.programs[self.index]
Esempio n. 28
0
    def __init__(self):
        app.Canvas.__init__(self,
                            size=(512, 512),
                            title='Rotating cube',
                            keys='interactive')
        self.timer = app.Timer('auto', self.on_timer)

        # Build cube data
        V, I, O = create_cube()
        vertices = VertexBuffer(V)
        self.faces = IndexBuffer(I)
        self.outline = IndexBuffer(O)

        # Build program
        # --------------------------------------
        self.program = Program(vertex, fragment)
        self.program.bind(vertices)

        # Build view, model, projection & normal
        # --------------------------------------
        view = np.eye(4, dtype=np.float32)
        model = np.eye(4, dtype=np.float32)
        translate(view, 0, 0, -5)
        self.program['u_model'] = model
        self.program['u_view'] = view
        self.phi, self.theta = 0, 0

        # OpenGL initalization
        # --------------------------------------
        gloo.set_state(clear_color=(0.30, 0.30, 0.35, 1.00),
                       depth_test=True,
                       polygon_offset=(1, 1),
                       line_width=0.75,
                       blend_func=('src_alpha', 'one_minus_src_alpha'))
        self.timer.start()
Esempio n. 29
0
 def clearPoints(self):
     print("Clear Points")
     verts = np.zeros(0, [('position', np.float32, 3),
                          ('normal', np.float32, 3),
                          ('color', np.float32, 3)])  #start empty...
     self.program_points.bind(VertexBuffer(verts))
     self.update()
Esempio n. 30
0
    def initialize_renderer(self):
        self.fbuffer = FrameBuffer()

        vertices = np.array(
            [[-1.0, -1.0], [+1.0, -1.0], [-1.0, +1.0], [+1.0, +1.0]],
            np.float32)
        texcoords = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]],
                             dtype=np.float32)

        self.fbuf_vertices = VertexBuffer(data=vertices)
        self.fbuf_texcoords = VertexBuffer(data=texcoords)

        self.fbuffer_prog['texcoord'] = self.fbuf_texcoords
        self.fbuffer_prog['position'] = self.fbuf_vertices

        self.vertex_buffer = VertexBuffer()
        self.index_buffer = IndexBuffer()